JSP μ¬μ΄νΈ μ μμ μ
νμΌ
β’
index.jsp
β’
SessionListener.java
μ μμ μ μ¦κ°
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.concurrent.atomic.AtomicInteger" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>μ¬μ΄νΈ μ μμ μ</title>
</head>
<body>
<%
// application κ°μ²΄μμ μ μμ μλ₯Ό κ°μ Έμ€κ±°λ μ΄κΈ°νν©λλ€.
// AtomicIntegerλ₯Ό μ¬μ©νμ¬ μ€λ λ μμ ν μ μμ μ μ¦κ°/κ°μλ₯Ό 보μ₯ν©λλ€.
AtomicInteger visitorCount = (AtomicInteger)application.getAttribute("visitorCount");
if (visitorCount == null) {
visitorCount = new AtomicInteger(0);
application.setAttribute("visitorCount", visitorCount);
}
// μ μμ μλ₯Ό 1 μ¦κ°μν΅λλ€.
int currentCount = visitorCount.incrementAndGet();
%>
<h1>μ¬μ΄νΈ μ μμ μ: <%= currentCount %></h1>
<%
// μ΄νμλ λ€λ₯Έ μμ
μν κ°λ₯
%>
<!-- μ΄νμλ νμ΄μ§ λ΄μ©μ ꡬμ±νκ³ , νμν λ‘μ§μ μΆκ°ν©λλ€. -->
</body>
</html>
HTML
볡μ¬
μ μμ μ κ°μ
β’
μ¬μ©μκ° νμ΄μ§λ₯Ό λ²μ΄λ λ μ μμ μ κ°μ
β¦
μΈμ
μ’
λ£ μ
β¦
λ‘κ·Έμμ μ
SessionListener.java
// μ¬μ©μ μΈμ
μ΄ μ’
λ£λ λ νΈμΆλλ λ©μλ (HttpSessionListenerλ₯Ό ꡬν)
public class SessionListener implements HttpSessionListener {
@Override
public void sessionDestroyed(HttpSessionEvent event) {
// μΈμ
μ’
λ£ μ application κ°μ²΄μμ μ μμ μλ₯Ό κ°μμν΄
ServletContext application = event.getSession().getServletContext();
AtomicInteger visitorCount = (AtomicInteger)application.getAttribute("visitorCount");
if (visitorCount != null) {
visitorCount.decrementAndGet();
}
}
// λ€λ₯Έ λ©μλ ꡬν
}
Java
볡μ¬