如何使用java从sql中检索会话中的数据

时间:2015-02-08 11:29:06

标签: java jsp

我正在尝试创建简单的网络应用。但登录用户界面后我遇到了问题。

我的数据库包括ID,用户名,密码和电子邮件。

我已经创建了Login表单并且正常工作。

在html / jsp中我使用此<%=session.getAttribute("name")%>获取“欢迎回来USERNAME,您的电子邮件为NULL。”

我想收到用户的电子邮件。

我的代码在这里:

THERE IS FIRST FILE
------------------------------------------------------------------------------------



package com.promo4free.servlets;

import java.io.IOException;
import java.io.PrintWriter;


import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.promo4free.dao.LoginDao;

public class LoginServlet extends HttpServlet {

        private static final long serialVersionUID = 1L;

        public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

                response.setContentType("text/html");
                PrintWriter out = response.getWriter();

                String n = request.getParameter("username");
                String p = request.getParameter("userpass");

                HttpSession session = request.getSession(false);
                if (session != null) session.setAttribute("name", n); // WORKING

                if (LoginDao.validate(n, p)) {
                        RequestDispatcher rd = request.getRequestDispatcher("after_login_user_interface.jsp");
                        rd.forward(request, response);
                } else {
                        out.print("<p style=\"color:red\">Sorry username or password error</p>");
                        RequestDispatcher rd = request.getRequestDispatcher("loginToPage.jsp");
                        rd.include(request, response);
                }

                out.close();
        }
}



-----------------------------------------------------------------------------------------------------------
THERE IS SECOND FILE
-----------------------------------------------------------------------------------------------------------
package com.promo4free.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

//working
public class LoginDao {
        public static boolean validate(String name, String pass) {
                boolean status = false;
                Connection conn = null;
                PreparedStatement pst = null;
                ResultSet rs = null;

                String url = "jdbc:mysql://localhost:3306/";
                String dbName = "ps";
                String driver = "com.mysql.jdbc.Driver";
                String userName = "root";
                String password = "root";
                try {
                        Class.forName(driver).newInstance();
                        conn = DriverManager.getConnection(url + dbName, userName, password);

                        pst = conn.prepareStatement("SELECT * FROM members WHERE username=? AND password=?"); //working
                        System.out.println("SELECT * FROM members WHERE username=? AND password=?"); //working
                        pst.setString(1, name);
                        pst.setString(2, pass);

                        rs = pst.executeQuery();
                        status = rs.next();

                } catch (Exception e) {
                        System.out.println(e);
                } finally {
                        if (conn != null) {
                                try {
                                        conn.close();
                                } catch (SQLException e) {
                                        e.printStackTrace();
                                }
                        }
                        if (pst != null) {
                                try {
                                        pst.close();
                                } catch (SQLException e) {
                                        e.printStackTrace();
                                }
                        }
                        if (rs != null) {
                                try {
                                        rs.close();
                                } catch (SQLException e) {
                                        e.printStackTrace();
                                }
                        }
                }
                return status;
        }
}

-----------------------------------------------------------------------------------------------------------
THERE IS SECOND FILE web.xml
-----------------------------------------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>  
<web-app xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" version="2.5">  
    <servlet>  
        <servlet-name>login</servlet-name>  
        <servlet-class>com.promo4free.servlets.LoginServlet</servlet-class>  
    </servlet>  

    <servlet-mapping>  
        <servlet-name>login</servlet-name>  
        <url-pattern>/loginServlet</url-pattern>  
    </servlet-mapping>  

    <welcome-file-list>  
        <welcome-file>index.jsp</welcome-file>  
    </welcome-file-list>
</web-app>

2 个答案:

答案 0 :(得分:1)

如果登录有效,我修改了您的方法以返回电子邮件

package com.promo4free.dao; 
import java.sql.*;

        /**
         * Created by Zexter on 09/02/2015.
         */
        public class LoginDAO {
            public static String validate(String name, String pass) {
                boolean status = false;
                String email="";
                Connection conn = null;
                PreparedStatement pst = null;
                ResultSet rs = null;

                String url = "jdbc:mysql://localhost:3306/";
                String dbName = "ps";
                String driver = "com.mysql.jdbc.Driver";
                String userName = "root";
                String password = "root";
                try {
                    Class.forName(driver).newInstance();
                    conn = DriverManager.getConnection(url + dbName, userName, password);

                    pst = conn.prepareStatement("SELECT * FROM members WHERE username=? AND password=?"); //working

                    pst.setString(1, name);
                    pst.setString(2, pass);

                    rs = pst.executeQuery();
                    //status = rs.next();
                    if(rs.next()){
                        email=rs.getString("email");
                    }

                } catch (Exception e) {
                    System.out.println(e);
                } finally {
                    if (conn != null) {
                        try {
                            conn.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                    if (pst != null) {
                        try {
                            pst.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                    if (rs != null) {
                        try {
                            rs.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }
                return email;
            }
        }

在Servelet上,您可以执行以下操作

package com.promo4free.servlets;

import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import java.io.IOException;
    import java.io.PrintWriter;

    /**
     * Created by Zexter on 09/02/2015.
     */
    @WebServlet(name = "Test",urlPatterns = "/path")
    public class LoginServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();

            String n = request.getParameter("username");
            String p = request.getParameter("userpass");
            String email="";
            email=LoginDAO.validate(n, p);


            if (email.trim()!="" && email.length()>0) {
                HttpSession session = request.getSession(true); // The session will be set only if there is a valid login 
                session.setAttribute("name", n);
                session.setAttribute("email",email);
                RequestDispatcher rd = request.getRequestDispatcher("after_login_user_interface.jsp");
                rd.forward(request, response);
            } else {
                out.print("<p style=\"color:red\">Sorry username or password error</p>");
                RequestDispatcher rd = request.getRequestDispatcher("loginToPage.jsp");
                rd.include(request, response);
            }

        }

        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        }
    }

最后,在JSp上,您可以尝试检查他是否已登录并检索信息。

<%
            String email="",name="";
            if(session.getAttribute("email")!=null && session.getAttribute("name")!=null ){
            email=session.getAttribute("email").toString();//Setting the session data to variable for reuse 
            name=session.getAttribute("name").toString();
            }
            %>

答案 1 :(得分:0)

创建一个类来表示系统用户:

public class User{

String userName;
String emailAddress;

//...

}

更新DAO以返回此类的实例,如果用户不存在,则返回null:

public static User validate(String name, String pass) {

    //...

    User  user = null;

    if(rs.next()){
        user = new User();
        user.setuserName(r.getString("userName");
        //etc
    }

    //...

    return user;
}

更新您的Servlet,以便在成功登录时在会话中添加用户:

   public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

        // ...
        User user = LoginDao.validate(n, p);

        if (user != null) {
                RequestDispatcher rd = request.getRequestDispatcher("after_login_user_interface.jsp");
                request.getSession().setAttribute("user", user);
                rd.forward(request, response);
        } 

        //...

    }

使用EL表示法输出JSP中用户的属性:

Welcome back ${user.userName}, your email is ${user.emaiLAddress}.