java 如何在 Servlets 中检查用户是否登录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1577236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 17:09:42  来源:igfitidea点击:

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

javajakarta-eeauthenticationservlets

提问by Satya

In a Java ServletI want to check programmatically whether a user is logged inor not.

Java Servlet的我想编程方式检查用户是否登录没有

回答by BalusC

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.

HttpServletRequest#getUserPrincipal()在其他的答案中指出,只有当你使用的Java EE提供的容器管理的安全性所概述适用在这里

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:

但是,如果您在自己的家庭中发展自己的安全,那么您需要依赖HttpSession. 这并不难,这里概述了您需要在每个步骤中实现的内容:

On login, get the Userfrom the DB and store it in session in servlet'sdoPost():

登录时,User从数据库中获取并将其存储在会话中的servlet 中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.

注销时,只需使 servlet 的doPost(). 它将破坏会话并清除所有属性。

session.invalidate();

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

要检查如果User是登录或没有,创建一个过滤器,其映射与url-pattern覆盖受限的页面,例如/secured/*/protected/*,等等并实现doFilter()象下面这样:

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:

也可以看看:

回答by vallismortis

The Java Servlet 3.1 Specification(Section 13.10) states:

的Java Servlet 3.1规范(第13.10节)规定:

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

一个请求的处理过程中被记录到一个应用程序,对应正是于存在一个有效的-null与请求相关联的可调用来确定呼叫方身份getRemoteUsergetUserPrincipal所述请求。null这些方法中的任何一个的返回值表明调用者没有登录到与请求处理相关的应用程序。