gpt4 book ai didi

java - getRemoseUser() 使用简单的登录 html 表单返回 null

转载 作者:行者123 更新时间:2023-11-28 23:10:38 26 4
gpt4 key购买 nike

我是网络技术的新手,我正在努力处理 session 跟踪,尤其是用户身份验证。

我有这个 html 页面:

<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<p>Click
<a href="login.jsp">here</a>
to authenticate.</p>
</body>
</html>

重定向到以下 jsp:

    <%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login JSP Page</title>
</head>
<body>
<form action="LoginServlet" method="POST">
<input type="text" name="username">
<input type="password" name="password">
<input type="Submit" value="Conferma">
</form>
</body>
</html>

其中 LoginServlet servlet 有以下方法:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
String paramUser = request.getParameter("username");
String paramPassword = request.getParameter("password");

if(paramUser.equals("demo") && paramPassword.equals("demo")){
// Success
// Invalid session if existing
HttpSession oldSession = request.getSession(false);
if(oldSession != null)
oldSession.invalidate();
HttpSession currentSession = request.getSession(); // Creates new session
currentSession.setAttribute(u, paramUser);
currentSession.setAttribute(p, paramPassword);
response.sendRedirect("success.jsp");
}
else{
// Failed authentication
response.sendRedirect("login.jsp");
}
}
}

其结果通过以下 View 显示:

    <%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Success Page</title>
</head>
<body>
<p>Hello</p>
<a href="LogoutServlet">logout</a>
<%= request.getRemoteUser() %> <%--RETURN NULL--%>
</body>
</html>

但不幸的是,在 jsp View 中 request.getRemoteUser() 返回 null 我不知道为什么(我希望它显示 "demo "(登录用户的名称)。

  • 谁能解释一下?

最佳答案

只需在 session 上设置任意属性,容器(tomcat)就不会任意神奇地知道用户。

您需要将身份验证委托(delegate)给 tomcat,以便正确初始化请求。 servlet 规范将其命名为“Container Managed Security”,因此它是标准化的。 Tomcat documentation有你需要的所有指针 - 它们涉及领域的配置,并将你的实现更改为指向不同的登录 URL - 而不是处理它。您将不会再看到用户的密码。

关于java - getRemoseUser() 使用简单的登录 html 表单返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58508559/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com