satya satya - 1 year ago 136
Java Question

How to check whether a user is logged in or not in Servlets?

In a Java Servlet I want to check programmatically whether a user is logged in or not.

Answer Source

The HttpServletRequest#getUserPrincipal() as pointed out in the other answer only applies when you make use of Java EE provided container managed security as outlined here.

If you're however homegrowing your own security, then you need to rely on the HttpSession. It's not that hard, here is an overview what you need to implement on each step:

On login, get the User from the DB and store it in session in servlet's doPost():

User user = userDAO.find(username, password);
if (user != null) {
    session.setAttribute("user", user);
} else {
    // Show error like "Login failed, unknown user, try again.".

On logout, just invalidate the session in servlet's doPost(). It will destroy the session and clear out all attributes.


To check if an User is logged in or not, create a filter which is mapped with an url-pattern which covers the restricted pages, e.g. /secured/*, /protected/*, etcetera and implement doFilter() like below:

if (session.getAttribute("user") == null) {
    response.sendRedirect(request.getContectPath() + "/login"); // Not logged in, redirect to login page.
} else {
    chain.doFilter(request, response); // Logged in, just continue chain.

That's basically all.

See also:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download