We have already seen invalidate() method in session implicit object tutorial. In this post we are going to discuss it in detail. Here we will see how to validate/invalidate a session.
Example
Lets understand this with the help of an example: In the below example we have three jsp pages.
- index.jsp: It is having four variables which are being stored in session object.
- display.jsp: It is fetching the attributes (variables) from session and displaying them.
- errorpage.jsp: It is first calling session.invalidate() in order to invalidate (make the session inactive) the session and then it has a logic to validate the session (checking whether the session is active or not).
index.jsp
<% String firstname="Chaitanya"; String middlename="Pratap"; String lastname="Singh"; int age= 26; session.setAttribute( "fname", firstname ); session.setAttribute( "mname", middlename ); session.setAttribute( "lname", lastname ); session.setAttribute( "UAge", age ); %> <a href="display.jsp">See Details</a> <a href="errorpage.jsp">Invalidate Session</a>
display.jsp
<%= session.getAttribute( "fname" ) %> <%= session.getAttribute( "mname" ) %> <%= session.getAttribute( "lname" ) %> <%= session.getAttribute( "UAge" ) %>
errorpage.jsp
<%session.invalidate();%> <% HttpSession nsession = request.getSession(false); if(nsession!=null) { String data=(String)session.getAttribute( "fname" ); out.println(data); } else out.println("Session is not active"); %>
Output:
while opening display page, all the attributes are getting displayed on client (browser).
Since we have already called invalidate in the first line of errorpage.jsp, it is displaying the message “Session is not active” on the screen
Points to Note:
1) This will deactivate the session
<%session.invalidate();%>
2) This logic will exceute the if body when the session is active else it would run the else part.
<% HttpSession nsession = request.getSession(false); if(nsession!=null) ... else ... %>
Leave a Reply