How do I end (invalidate) a session?

Richard Raszka

Sessions can be invalidated by calling the invalidate() method on the HttpSession Object. In a Servlet this can be performed using the following code:


import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class InvalidateSession extends HttpServlet
{
    public void doGet(
      HttpServletRequest req, HttpServletResponse res) 
      throws ServletException, IOException
    {
	res.setContentType("text/html");
	PrintWriter out = res.getWriter();

        // Get the current session
        HttpSession session = req.getSession(true);

	// Invalidate it for a particular reason
	if (....)
	{
	    session.invalidate();
	}
	// Continue processing 
	// - May need a session to be created to continue processing
	
    }
}

Invalidating a session could be done on an explicit logout of a user from the Web Site or after a period of inactivity that you have defined in the application.

Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.