3

Following is my navigation bar for include the logout button for the page.

I want to end the session when a user click the logout button.

I found sample codes by googling and added for my code but following code shows an error.(Check the error in screenshot)

<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Hi, <%=session.getValue("Username") %><b class="caret"></b></a> <ul class="dropdown-menu"> <li align="center" class="well"> <a href="index.jsp" class="btn btn-sm btn-default"><span class="glyphicon glyphicon-log-out"></span> Logout</a> <% session.invalidate(); response.sendRedirect("index.jsp"); %> </li> </ul> </li> </ul> </div><!-- /.navbar-collapse --> 

Help me to correct this code..

enter image description here

2 Answers 2

1

By default, a session is created for you by container if the session is not available. For JSP use to avoid create new session:

<%@ page session="false" %> 

Before accessing the session variables check for the session if available not. Without session, if we call the session object methods it will raise IlleagalStateExcetion.

 <% if (session!=null) {%> <%=session.getValue("Username") %><b class="caret"></b></a> <% } %> 

The session is getting invalidated every time the page loads, by not clicking on the Logout. So by clicking on the Logout put a separate page to invalidate the session.

Here I ma using it as logout.jsp, it contains the session invalidation code:

 <!-- For not creating new session --> <%@ page session="false" %> <body> <% // for checking the session is available or not, if not available it will throw exception, "Session already invalidated." if (sesssion!=null) { session.invalidate(); response.sendRedirect("index.jsp"); } %> </body> 

And Finally change the Logout link like the following:

<a href="logout.jsp" class="btn btn-sm btn-default"><span class="glyphicon glyphicon-log-out"></span> Logout</a> 

Give it a try :)

Sign up to request clarification or add additional context in comments.

Comments

1

Problem is your session is already killed before you click the logout link. Also in jsp pages session are auto-created. You need to take care of that while accessing any attribute from the session. Do follow the steps suggested by Srinu.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.