To anyone, who has a similar issue, here is the solution that worked for me.
- Create your
login.jsp
page with the user input form (method should be POST
)
<form action="${pageContext.request.contextPath}/userAuth" method="POST">
...
</form>
- Create a filter class and map it to
login.jsp
. Inside the filter class make a check for null, retrieve session and check if it contains an attribute, which will signal that the user has already logged in (I used User object and mapped it as "user")
@WebFilter("/login.jsp")
public class AuthFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpSession session = ((HttpServletRequest) request).getSession();
if (session.getAttribute("user") != null) {
response.setContentType("text/html;charset=UTF-8");
request.getRequestDispatcher("homepage.jsp").forward(request, response);
}
chain.doFilter(request, response);
}
}
- Create servlet class and map it to the form action inside
login.jsp
. Override doPost
and doGet
methods: former will contain user credentials processing logic, latter will contain log out logic.
@WebServlet("/userAuth")
public class AuthServlet extends HttpServlet {
/**
* Log in
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String email = request.getParameter("email");
String password = request.getParameter("password");
try {
User user = UserDAO.getUser(email, password);
session.setAttribute("user", user);
response.sendRedirect(request.getContextPath() + "/login.jsp");
} catch (DAOException e) {
e.printStackTrace();
}
}
/**
* Log out
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
request.getSession().invalidate();
response.setContentType("text/html;charset=UTF-8");
response.sendRedirect("login.jsp");
}
}
- Create your
homepage.jsp
and add the logout button which will send GET
to the servlet
<a href="${pageContext.request.contextPath}/userAuth">Logout</a>
Now the logic behind this is as follows:
The servlet doesn't actually redirect to user homepage. All it does is adding that one attribute, that the filter is looking for, and redirecting request back to login.jsp
. And login.jsp
always gets intercepted by the filter, who redirects to the homepage if that attribute is present.
This way you will solve the problem of keeping the user logged in until the session is on, as well as the problem of user being able to return or refresh page (which will cause form resubmission) after logging out. No additional headers like "no-cache" are needed.