i'm using java servlet in tomcat. i save in a hash table the username and the httpsession with the attribute usrname i would like to know if there is a way to know if the httpsession is valid.
i tried:
try{
String user = httpSession.getAttribute("username")
return "is valid";
}catch(IllegalStateException e){
return "is not valid";
}
tnks for the answer, but how can i do if i don't wont that a "logged" user connect from more the one place? if i controll only if i create a new session i can't know if he was connect whit another session.
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.
No need to store the httpSession in your own hash.
Look at the api for the HttpServletRequest. If you look at getSession(Boolean x) (pass false so it doesnt create a new session) will determine if the session is valid. Here is an example
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.
Rather than checking if a saved session is valid, you should be looking at the
HttpServletRequest
on your servlet, and checkingisRequestedSessionIdValid()
on that. When working in servlets you can always getSession
from theRequest
, rather than saving it to a hash table.