Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 428
Satya Avatar asked Feb 03 '23 08:02

Satya


1 Answers

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:

  • How to redirect to Login page when Session is expired in Java web application?
  • How to handle authentication/authorization with users in a database?
like image 61
BalusC Avatar answered Feb 06 '23 14:02

BalusC