How do I invalidate user's session?
Category: javax.servlet, viewed: 7118 time(s).
In a web application you might want to invalidate user session, for instance in a logout Servlet or JSP. There is an invalidate() method in the HttpSession interface, this method invalidates the session and it removes all attributes from the session object.
package org.kodejava.example.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class InvalidateSessionServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
//
// Invalidate the session and removes any attribute related to it
//
session.invalidate();
//
// Get an HttpSession related to this request, if no session exist don't
// create a new one. This is just a check to see after invalidation the
// session will be null.
//
session = request.getSession(false);
response.getWriter().println("Session : " + session);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
Download Hundreds of Complimentary Industry Resources
Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more;
all available at no cost to you. With more than 600 complimentary offers, you'll find
plenty of titles to suit your professional interests and needs.
Click Here and Sign up today!