Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
12
rated 0 times [  17] [ 5]  / answers: 1 / hits: 101436  / 12 Years ago, tue, december 4, 2012, 12:00:00

I have the following code in JSP:



<%
if(session.getAttribute(Username) == null || session.getAttribute(Username) == _INVALID_)
{
response.sendRedirect(LoginPage.html);
}
%>

<form>
<input type=button value=Change Account Details onClick=location.href='ChangeDetails.jsp'>
<br></br>
<input type=button value=Add Customers onClick=location.href='AddCustomers.jsp'>
<br></br>
<input type=button value=Manage Flights onClick=location.href='ManageFlights.jsp'>
<br></br>
<input type=button value=Book Flights onClick=location.href='BookFlights.jsp'>
<br></br>
<input type=button value=Log Out onClick=location.href='LoginPage.html'>
</form>


When the user clicks on the log out button, I want to redirect him to the log-in page and kill the current session. I have succeeded in the redirection part but I do not know how to kill the session. How can this be done please?


More From » java

 Answers
133

In order to kill the current session, you basically need to call HttpSession#invalidate() and perform a redirect to the login or main page. This code is supposed to be placed in doPost() method of a servlet which is invoked by a POST request.



E.g.



<form action=${pageContext.request.contextPath}/logout method=post>
<input type=submit value=Logout />
</form>


with



@WebServlet(/logout)
public class LogoutServlet extends HttpServlet {

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getSession().invalidate();
response.sendRedirect(request.getContextPath() + /LoginPage.html);
}

}





Unrelated to the concrete problem, your username checking code is not at the right place. You shouldn't be copypasting the same code over every single JSP page. You should be performing this job in a single place in a servlet filter. Java code in JSP files should be avoided as much as possible.



Further, there's another potential problem when the enduser uses the browser's back button to navigate back in history. By default, the browser will cache all responses and thus the back button might display the page from the browser cache instead of requesting a brand new straight from the server. In order to fix this, see this related question Prevent user from seeing previously visited secured page after logout



Last but not least, you've there some quite strange HTML. Buttons with onClick to navigate? How user and SEO unfriendly. Use normal <a> links instead. For the button look'n'feel, throw in some CSS.


[#81623] Monday, December 3, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zariahdiamondz

Total Points: 649
Total Questions: 109
Total Answers: 88

Location: Tajikistan
Member since Thu, Apr 14, 2022
2 Years ago
;