[Web] 세션 유효 기간 설정 / 세션 삭제하기

2024. 8. 19. 20:18자바 웹 개발/세션 쿠키 필터 리스너

web.xml에 session-config을 이용해서 유효 시간을 바꿀 수 있다. 기본 시간은 30분이다. 

    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>

 

setMaxInactiveInterval()을 이용해서 세션 유효 시간을 5초로 정해보자. 

@WebServlet("/sess2")
public class SessionTest2 extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter out = resp.getWriter();
		HttpSession session = req.getSession();
		out.println("세션 아이디 :" + session.getId() + "<br>");
		out.println("최근 세션 생성 시간 :" + new Date(session.getCreationTime()) + "<br>");
		out.println("최근 세션 접근 시간 :" + new Date(session.getLastAccessedTime()) + "<br>");
		out.println("기본 세션 유효 시간 :" + session.getMaxInactiveInterval() + "<br>");
		session.setMaxInactiveInterval(5);
		out.println("세션 유효 시간 : " + session.getMaxInactiveInterval() + "<br>");
		if(session.isNew()) {
			out.print("새 세션이 만들어졌습니다.");
		}
	}
	
}

 

5초 이후에는 세션 아이디가 바뀐다. 

 

세션 삭제하기

invalidate()를 이용하면 강제로 세션을 삭제할 수 있다. 

@WebServlet("/sess3")
public class SessionTest3 extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter out = resp.getWriter();
		HttpSession session = req.getSession();
		out.println("세션 아이디 : " + session.getId() + "<br>");
		out.println("최초 세션 생성 시각 : " + new Date(session.getCreationTime()) + "<br>");
		out.println("최근 세션 접근 시각 : " + new Date(session.getLastAccessedTime()) + "<br>" );
		out.println("세션 유효 시간 : " + session.getMaxInactiveInterval() + "<br>");
		if(session.isNew()) {
			out.print("새 세션이 만들어졌습니다.");
		}
		session.invalidate();
	}
}

 

삭제를 했기 때문에 계속 '새 세션이 만들어졌습니다'가 뜨고 세션 아이디가 새로 발급된다.