Note:this approach is very old; Java/jsp scriptlets were deprecated a long time ago. I don ' t has time to update this article to the correct, modern approach, and I hope this JSP session example would point Y OU in the right direction.
Every once in a while I'm asked something like, "What can I tell if I had a valid user session in my JSP code?"
According to the JSP specification, a implicit variable named session
(which is a instance of anhttpsession) is made avail Able to your JSP's automatically by your servlet container. So, all of you has a valid user session in a JSP are to test whether this session
reference is , or not, like this:
if (session = = NULL) { //the user *does not* has a valid session; Handle this however your need to.} else{ //The user *does* has a valid session. Do whatever your need to for logged in users. String username = (string) session.getvalue ("username");}
One-to-deal with a null user session
If you ' re in a situation where a user needs to has a valid user session to access your Jsp/servlet content, you can deal With the situation using JSP code like this:
<% if (session = = null) { String address = websitecontext + "/login.jsp"; RequestDispatcher dispatcher = Getservletcontext (). Getrequestdispatcher (address); Dispatcher.forward (Request,response); } %>
The example I ' ve already set the variable websiteContext
somewhere earlier in my JSP. For example, if this is a discussion forum, this variable might is set to the string "/forums".
If you prefer the JSP forward
tag, you can also forward to the login page like this:
<% if (session = = null) { %><jsp:forward page= "login.jsp"/><% }%>
Which one you choose are up to you.
How to test for a valid user session in a JSP