Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java servlet - Session cleanup (HttpServletRequest)

General question about java servlets and the best way to handle requests. If I hit my doGet method from a remote server request:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
  ....
  <do work here>
  ....
  kill(request);
}

private void kill(HttpServletRequest request) {
//How do I kill the user session here?
}

After I process the request at my end and generate my output to the requester, I want to basically "kill" their session. Currently, that session lingers and thus eats up memory. Then once the max is reached, all other calls are timed out.

I tried creating a HttpSession object using the request object, but got the same results:

HttpSession session = request.getSession();
session.invalidate();
like image 294
user82302124 Avatar asked Apr 05 '12 21:04

user82302124


People also ask

How do I clear a Java session?

Full Stack Java developer - Java + JSP + Restful WS + Spring Remove a particular attribute − You can call the public void removeAttribute(String name) method to delete the value associated with the particular key. Delete the whole session − You can call the public void invalidate() method to discard an entire session.

What is HttpSession in Java?

Interface HttpSession. public interface HttpSession. Provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user. The servlet container uses this interface to create a session between an HTTP client and an HTTP server.

How do you end a session in servlet?

Setting Session timeout − You can call public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually. Log the user out − The servers that support servlets 2.4, you can call logout to log the client out of the Web server and invalidate all sessions belonging to all the users.

How can we maintain session in Java Web application?

Since HTTP and Web Server both are stateless, the only way to maintain a session is when some unique information about the session (session id) is passed between server and client in every request and response. There are several ways through which we can provide unique identifier in request and response.


1 Answers

HttpSession session = request.getSession(false);
if (session != null) {
    session.invalidate();
}

is the proper way to go as suggested by the documentation. A new session will be created once the client sends a new request.

You mentioned that your sessions still take up memory. Do you have any other references to those objects on the session?

You also might want to have a look at: Servlet Session behavior and Session.invalidate

like image 91
csupnig Avatar answered Sep 22 '22 09:09

csupnig