14

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();
user82302124
  • 1,143
  • 5
  • 32
  • 57
  • 1
    I have the impression that your concrete problem needs to be solved in a different way. – BalusC Apr 05 '12 at 21:48
  • Probably. The ultimate goal is I want to end a session in my session pool after their request is handled. Whether or not that is killing the request object or creating a session object for that session to delete it, I am not sure. – user82302124 Apr 06 '12 at 13:13

5 Answers5

26
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

yoozer8
  • 7,361
  • 7
  • 58
  • 93
csupnig
  • 3,327
  • 1
  • 24
  • 22
5

you can remove an attribute from a session using

session.removeAttribute("attribute name");
animuson
  • 53,861
  • 28
  • 137
  • 147
mykey
  • 575
  • 2
  • 10
  • 24
2

Try with

session = request.getSession(false); // so if no session is active no session is created
if (session != null)
  session.setMaxInactiveInterval(1); // so it expires immediatly
dash1e
  • 7,677
  • 1
  • 30
  • 35
1

If you dont want Session behavior i.e, having state between multiple requests. Why do you want to create/use session at all. Do not create session or do not store anything in the session.

To make sure that your code is not using session, write a request wrapper which will override getSession() methods.

user207421
  • 305,947
  • 44
  • 307
  • 483
Ramesh PVK
  • 15,200
  • 2
  • 46
  • 50
0

Set a time-out period in web.xml