struts+service+action+数据库

用户登录流程

1.jsp根据form表单中的action的login   <form action="/test02/login" method="post">

    请求struts.xml文件中的 

<action name="login" class="action.LoginAction" method="add">

2.struts.xml根据  class="action.LoginAction"会访问  action.LoginAction中的add()方法

 3.LoginAction.action文件中的

    public String add() throws SQLException {

        User user = loginService.login(username, password);

4.根据 User user = loginService.login(username, password);会访问loginService 中的 login  public User login(String username, String password) throws SQLException

5.执行loginDao文件中的  login(访问数据库)

public User login(String username, String password) throws SQLException {

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        User u = null;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(
                    "jdbc:mysql://127.0.0.1:3306/mydb?characterEncoding=UTF8",
                    "root", "123456");
            String sql = "select * from user where username = ? and password =?";
            ps = conn.prepareStatement(sql);// 预编译的,对于批量处理可以大大提高效率
            ps.setString(1, username);// 相当于上面的前一个问号
            ps.setString(2, password);
            rs = ps.executeQuery();// 查询数据库,在访问数据库的时候需要查询,别的三个操作指示更新数据库
            while (rs.next()) {
                u = new User();
                u.setUsername(rs.getString("username"));
                u.setPassword(rs.getString("password"));

            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }
            if (conn != null) {
                conn.close();
            }
        }

        return u;

    }

 

posted @ 2016-01-11 22:24  sunli0205  阅读(198)  评论(0编辑  收藏  举报