The effective Java logout servlet code

July 8, 2012 in Java, Java Web

What is the issue?

You may face an issue when you try to write your own Servlet logout code as follows:

protected void doGet(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {

	request.getSession().invalidate();
	response.sendRedirect(request.getContextPath() + "/login.jsp");
}

The issue in this code is that after it runs on the web container, You may find that the user session is not cleared completely in IE (However, on Safari, Chrome, and Firefox, it may work fine). i.e) You can access pages that requires a user authentication after running this logout code in IE.

Why do we have this issue?

Well, this issue is related to the caching of the pages in the Internet Explorer.

How to solve this issue?

You need to prevent the page caching from the HTTP response as follows:

protected void doGet(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {

	response.setHeader("Cache-Control", "no-cache, no-store");
	response.setHeader("Pragma", "no-cache");

	request.getSession().invalidate();
	response.sendRedirect(request.getContextPath() + "/login.jsp");
}

After writing the first two headers response lines, your logout will work in all the browsers.

Leave a reply

Your email address will not be published. Required fields are marked *

337,578 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Powered by sweet Captcha