How to test for a valid user session in a JSP

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.