user667430
user667430

Reputation: 1547

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();
    }

Upvotes: 0

Views: 618

Answers (1)

Kazekage Gaara
Kazekage Gaara

Reputation: 15052

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"));

Upvotes: 3

Related Questions