session.getAttribute返回null
在访问应用程序之前,我使用jsp和servlet实现身份验证 以下是我的doPost方法的代码:session.getAttribute返回null,session,jakarta-ee,servlets,Session,Jakarta Ee,Servlets,在访问应用程序之前,我使用jsp和servlet实现身份验证 以下是我的doPost方法的代码: protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username");
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
Account account;
try {
//Checking if the user already exists
account = accountBesinessLocal.findByLogin(String.valueOf(username));
if (account != null) {
logger.log(Level.WARNING, "[User exists:{0}]", username);
if (accountBesinessLocal.authentificateUser(String.valueOf(username), String.valueOf(password))) {
HttpSession session = request.getSession(true);
System.out.println(session);
session.setAttribute("username", account.getLogin());
session.setAttribute("password", account.getPassword());
System.out.println("this "+session.getAttribute(username)+" is connected");
response.sendRedirect(home.xhtml");
} else {
request.setAttribute("erreur", "Incorrect Authentication");
getServletContext().getRequestDispatcher("/loginForm.jsp").forward(request, response);
}
} else {
request.setAttribute("erreur", "Incorrect Authentication");
logger.log(Level.WARNING, "[User does not exist:{0}]", username);
getServletContext().getRequestDispatcher("/loginForm.jsp").forward(request, response);
}
} finally {
}
}
当我尝试获取与session.getAttribute(用户名)连接的用户登录名时代码>
它返回null。
如何解决此问题?您必须使用
session.getAttribute("username")
而不是
session.getAttribute(username)
用户名的值是用户在登录输入字段中输入的值。它不是“userame”
旁注:您的代码没有编译,您可能正在运行的代码不是您发布的代码。谢谢您的回答,它很有用,而且运行良好。关于我发布的代码,我正在运行它,它也在工作。response.sendRedirect(home.xhtml”);
没有在您的代码中编译。它缺少一个双引号。您是对的,但它输入错误。我认为其他方面有问题。