Satya
Satya

Reputation: 1421

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.

Upvotes: 9

Views: 21518

Answers (3)

Parker
Parker

Reputation: 7519

The Java Servlet 3.1 Specification (Section 13.10) states:

Being logged into an application during the processing of a request, corresponds precisely to there being a valid non-null caller identity associated with the request as may be determined by calling getRemoteUser or getUserPrincipal on the request. A null return value from either of these methods indicates that the caller is not logged into the application with respect to the processing of the request.

Upvotes: 0

BalusC
BalusC

Reputation: 1109735

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.

session.invalidate();

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:

Upvotes: 12

Related Questions