session.getAttribute返回null

时间:2013-11-18 14:47:20

标签: session java-ee servlets

我使用jsp和servlet在访问应用程序之前实现身份验证 这是我的doPost方法的代码:

 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(username);关联的用户的登录信息时 它返回null。 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您必须使用

session.getAttribute("username") 

而不是

session.getAttribute(username)

用户名的值是用户在登录输入字段中输入的内容。这不是"userame"

旁注:您的代码无法编译,您可能正在运行的代码不是您发布的代码。