开发者

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 i开发者_如何学Cs logged in or not.


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?


HttpServletRequest.getUserPrincipal()


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜