I have three simple HttpServlet classes in my JSP project: "LoginServlet", "LogoutServlet" and "ProfileServlet".
- LoginServlet: log in by setting the name attribute for the session
- LogoutServlet: logout and session cancellation
- ProfileServlet: display user greeting information if the user is logged in
The last two servlets, as shown below, I find problematic.
@SuppressWarnings("serial")
public class LogoutServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
HttpSession session=request.getSession(false);
session.invalidate();
request.getRequestDispatcher("link.jsp").include(request, response);
out.print("You are successfully logged out!");
out.close();
}
}
and
@SuppressWarnings("serial")
public class ProfileServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
request.getRequestDispatcher("link.jsp").include(request, response);
HttpSession session = request.getSession(false);
if (session != null) {
String name = (String) session.getAttribute("name");
out.print("Hello, " + name + " Welcome to Profile");
} else {
out.print("Please login first");
request.getRequestDispatcher("login.html").include(request,
response);
}
out.close();
}
}
And link.jsp:
<% HttpSession nsession = request.getSession(false);
if(nsession == null) {
%>
<a href="login.html">Login</a>
<%
}
else {
%>
<a href="LogoutServlet">Logout</a>
<%
}
%>
<a href="ProfileServlet">Profile</a>
<hr/>
The problem is that during user login, when the "Logout" link is clicked and the "LogoutServlet" is called, the session is invalid and the ProfileServlet still prints
"Hello, null Welcome to Profile"
"login.html", - . "" "link.jsp". .
EDIT:
, html- ,
request.getRequestDispatcher("link.html").include(request, response);
"link.html".
<a href="login.html">Login</a>
<a href="LogoutServlet">Logout</a>
<a href="ProfileServlet">Profile</a>
<hr/>
, , ! , ,
request.getRequestDispatcher("link.jsp").include(request, response);
, ...