【问题标题】:session.getAttribute returns nullsession.getAttribute 返回 null
【发布时间】:2013-12-01 18:28:13
【问题描述】:

我正在使用 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); 关联的用户的登录名时 它返回空值。 我该如何解决这个问题?

【问题讨论】:

    标签: session jakarta-ee servlets


    【解决方案1】:

    你必须使用

    session.getAttribute("username") 
    

    而不是

    session.getAttribute(username)
    

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

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

    【讨论】:

    • 感谢您的回答,它很有用且运行良好。关于我发布的代码正在运行它并且它也在工作。
    • response.sendRedirect(home.xhtml"); 不会在您的代码中编译。它缺少双引号。
    • 您是对的,但输入错误。我还以为出了点问题。
    猜你喜欢
    • 2019-08-25
    • 2019-09-21
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-28
    • 1970-01-01
    相关资源
    最近更新 更多