Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java httpsession is valid?

I'm using the java servlet API in tomcat.

I save in a hash table the username and the httpsession with the attribute username and I would like to know if there is a way to check if the httpsession is valid.

I've tried:

try {
    String user = httpSession.getAttribute("username")
    return "is valid";
} catch (IllegalStateException e) {
    return "is not valid";
}

What can I do if I don't want that a "logged" user connect from more than one place? If I control only if I create a new session, I can't know if he was connected already with another session.

like image 740
Matteo Avatar asked Jul 15 '11 17:07

Matteo


2 Answers

No need to store the httpSession in your own hash.

Look at the API for the HttpServletRequest. If you look at method getSession(Boolean x) (pass false so it doesn't create a new session) will determine if the session is valid.

Here is an example

public void doGet(HttpServletRequest req, HttpServletResponse res) {
    HttpSession session = req.getSession(false);
    
    if (session == null) {
       //valid session doesn't exist
       //do something like send the user to a login screen
    }

    if (session.getAttribute("username") == null) {
       //no username in session
       //user probably hasn't logged in properly
    }

    //now let's pretend to log the user out for good measure
    session.invalidate();
}

On a side note, If I read your question properly and you are storing the information in your own map, you need to be careful that you don't create a memory leak and are clearing the entries out of the hash table yourself.

like image 106
Sean Avatar answered Nov 07 '22 22:11

Sean


I agree with Sean. I will add that a good practice for this type of checking is to use a Filter

See here Servlet Filter

Just take the code Sean have written and put it in a Filter instead. Define you filter in the web.xml and every time a request come in, the filter will execute.

This way you can validate if the user is auth. without cluttering your servlet code.

like image 45
Cygnusx1 Avatar answered Nov 07 '22 23:11

Cygnusx1