简体   繁体   中英

session variable not being set

I am trying to make a Java web application where users can log into a Java web app I am creating to access a certian page on the website. I have this code below which checks if the user email and password exists in my database of members.

However when i try to set the seesion variable it is 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();
    }

There is a simple syntax error in your code. Your session variable needs to be within quotes. Try this :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM