9

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

Jens Piegsa
  • 7,399
  • 5
  • 58
  • 106
Satya
  • 1,421
  • 4
  • 19
  • 32

3 Answers3

12

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:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
0

HttpServletRequest.getUserPrincipal()

david a.
  • 5,283
  • 22
  • 24
  • thanks yes i can work. But tell me how i can set the usename in servlet so that it is further called by getUserPrincipal() – Satya Oct 21 '09 at 05:18
  • You can't set the principal in a J2EE app. App server has to that instead. Your app only has to provide definitions of security rules and its assignments to servlets, app server does the rest (i.e. identifying a user and authorizing them to access particular endpoint. There are many tutorials regarding J2EE security, e.g. one here: http://java.sun.com/javaee/5/docs/tutorial/doc/bncbx.html – david a. Oct 21 '09 at 11:58
0

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.

Parker
  • 7,244
  • 12
  • 70
  • 92