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
복사





