[JAVA] HttpSessionBindingListener 구현과 valueBound, valueUnbound 메서드의 사용
HttpSessionBindingListener 를 implement 한 java 객체(ex : public class TestSession implements HttpSessionBindingListener)는 valueBound 메서드와 valueUnbound 메서드를 구현해야 한다.
보통 valueBound 메서드와 valueUnbound 메서드는 다음과 같이 구현할 수 있다.
|
public class TestSession implements HttpSessionBindingListener { private static Hashtable<HttpSession, String> userTable = new Hashtable<HttpSession, String>(); private HttpSession httpSession = null;
// 생성자 public TestSession(HttpServletRequest request) throws Exception {
public void valueBound(HttpSessionBindingEvent event) { public void valueUnbound(HttpSessionBindingEvent event) { } |
여기서 userTable 변수는 static 으로 선언된 HashTable 이다.
참고로 HashTable을 쓰는 이유는 Thread-safe하기 때문이다. HashMap은 Thread-safe하지 못하다.
이 때 valueBound 메서드는 직접적으로 호출할 필요 없다(new TestSession().valueBound(event); 이런 식의 코드를 작성할 필요 없다는 뜻이다).
세션에 TestSession 객체 (HttpSessionBindingListener 를 implement 한 java 객체)를 setAttribute 하면 valueBound 메서드가 호출된다. 예를 들어 String userId = “admin”; session.setAttribute(userId, this); 이러한 코드를 수행할 때 valueBound 메서드가 호출된다. 그리고 valueBound 메서드는 userTable 에 HttpSession 객체(event.getSession()) 를 저장하도록 구현한다고 가정하자.
결국 세션을 생성할 때(사용자 로그인 시) session.setAttribute(userId, this); 코드를 수행하도록 작성하면, userTable 에 세션을 하나씩 저장할 것이다. 이렇게 해두면 유사시에 (ex : 동일한 아이디의 사용자가 상이한 아이피로 접속했을 때) userTable 을 size 만큼 loop 돌면서 세션들을 invalidate 시킬 수 있게 된다.
|
HttpSession session = null; Enumeration e = userTable.keys(); |