会话变量未设置

时间:2012-03-09 11:41:21

标签: java session web-applications

我正在尝试创建一个Java Web应用程序,用户可以在其中登录我正在创建的Java Web应用程序来访问网站上的certian页面。我在下面的代码中检查用户电子邮件和密码是否存在于我的成员数据库中。

但是,当我尝试设置seesion变量时,它为null。

    try {
        Class.forName(driver).newInstance();
        conn = DriverManager.getConnection(url, userName, password);
        if (request.getParameter("email") != null && !request.getParameter("email").equals("") && request.getParameter("password") != null && !request.getParameter("password").equals("")) {
            email = request.getParameter("email").toString();
            userpass = request.getParameter("password").toString();
            strQuery = "SELECT * FROM member WHERE email = ? and password =?";
            PreparedStatement stmt = conn.prepareStatement(strQuery);
            stmt.setString(1, email);
            stmt.setString(2, userpass);


            System.out.println(stmt);
            rs = stmt.executeQuery();
            int count = 0;
            while (rs.next()) {
                session.setAttribute("email", rs.getString(2));
                System.out.println(session.getAttribute(email)); //This is null in system console it should not be
                count++;
            }
            if (count > 0) {
                response.sendRedirect("index.jsp");
            } else {
                response.sendRedirect("index.jsp");
            }
        } else {
            response.sendRedirect("gourmet.jsp");
        }
        System.out.println("Connected to the database");
        conn.close();
        System.out.println("Disconnected from database");
    } catch (Exception e) {
        e.printStackTrace();
    }

1 个答案:

答案 0 :(得分:3)

代码中存在简单的语法错误。您的会话变量必须在引号内。 试试这个:

System.out.println(session.getAttribute("email"));