为什么Java会话属性返回null

时间:2017-04-26 17:57:36

标签: java session null

我试图将loggedIn String对象用作标志。当我在日志中打印出来时,为什么返回空值?

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String loggedIn = "false"; //create a marker to tell if the user is logged in

    String url = "/index.jsp";
    HttpSession session = request.getSession();

    // get a user object from the session. 
    User sessionUser =(User) session.getAttribute("user");

    // create empty message strings
    String messageSuccess = "";
    String passwordMismatch = "";


    session.setAttribute("loggedIn", loggedIn);
    System.out.println("The loggedIn attribute of the session object is: " + session.getAttribute(loggedIn));

    String action = request.getParameter("action");

    if (action == null) {
        action = "join";
    }

    if (action.equals("join")) {
        url = "/new_customer.jsp";

    } else if (action.equals("signIn")) {

//      User sessionUser = (User) session.getAttribute("sessionUser");

        if (sessionUser == null) {

            url = "/login_failure.jsp";

        } else {

            String username = request.getParameter("username");
            String password = request.getParameter("password");

            if (username.equals(sessionUser.getUserName()) && password.equals(sessionUser.getPassword())) {
                url = "/account_activity.jsp";
                loggedIn = "true";
                session.setAttribute("loggedIn", true);

            } else {
                url = "/login_failure.jsp";
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

由于

session.getAttribute(loggedIn)

结合使用
String loggedIn = "false";

将评估为

session.getAttribute("false")

并且该属性很可能未在您的会话中设置。

您可能正在寻找

session.getAttribute("loggedIn")