Search

JSP μ‚¬μ΄νŠΈ μ ‘μ†μž 수 κΈ°λŠ₯

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