(2-23)使用jdbc实现web数据存储(二)

笔记如下
  • 设计规范


    (2-23)使用jdbc实现web数据存储(二)_第1张图片
    2018-02-23_115807.png
  • UserDao.java
public class UserDao {
    
    
    //查询单个用户 ,这里是dao的核心类,封装了对数据的操作
    public User selectOne(User user) {
        
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        
        
        
        try {
            //获得连接
            conn = JdbcUtils.getConnection();
            stmt = conn.createStatement();
            
            
            String sql = "select * from users where username='"+user.getUsername()+"' and password='"+user.getPassword()+"'";
            
            rs = stmt.executeQuery(sql);
            
            User loginuser = null;
            //解析结果集
            if(rs.next()) {
                
                loginuser = new User();
                
                int id = rs.getInt("id");
                String username = rs.getString("username");
                String password = rs.getString("password");
                String nickname = rs.getString("nickname");
                
                //封装用户信息
                loginuser.setId(id);
                loginuser.setNickname(nickname);
                loginuser.setPassword(password);
                loginuser.setUsername(username);
                
            }
            return loginuser;
            
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            
        }finally {
            
            //释放资源
            JdbcUtils.release(rs, stmt, conn);
            
        }
        
                
        
        return null;
    }
    
    //查询单个用户 ,这里是dao的核心类,封装了对数据的操作
        public User selectOne2(User user) {
            
            Connection conn = null;
            
            ResultSet rs = null;
            
            PreparedStatement stmt =null;
            
            
            try {
                //获得连接
                conn = JdbcUtils.getConnection();
                
                //String sql = "select * from users where username='"+user.getUsername()+"' and password='"+user.getPassword()+"'";
                
                //使用?占位符,防止sql注入(黑客改变关键字,达到不可告人的目的)
                String sql = "select * from users where username=? and password=?";
                stmt = conn.prepareStatement(sql);
                
                //替换占位符
                
                stmt.setString(1, user.getUsername());
                stmt.setString(2, user.getPassword());
                
                //executeQuery()有个重载无参数,预编译后直接执行
                //rs = stmt.executeQuery(sql);
                rs = stmt.executeQuery();
                
                User loginuser = null;
                //解析结果集
                if(rs.next()) {
                    
                    loginuser = new User();
                    
                    int id = rs.getInt("id");
                    String username = rs.getString("username");
                    String password = rs.getString("password");
                    String nickname = rs.getString("nickname");
                    
                    //封装用户信息
                    loginuser.setId(id);
                    loginuser.setNickname(nickname);
                    loginuser.setPassword(password);
                    loginuser.setUsername(username);
                    
                }
                return loginuser;
                
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
                
            }finally {
                
                //释放资源
                JdbcUtils.release(rs, stmt, conn);
                
            }
            
            
            
            
            
            
            return null;
        }
    
}
  • User.java
public class User {
    
    private int id;
    private String username;
    private String password;
    private String nickname;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getNickname() {
        return nickname;
    }
    public void setNickname(String nickname) {
        this.nickname = nickname;
    }
    
    
    
    
}

  • UserServlet.java
public class UserService {
    
    public User login(User user) {
        
        
        //调用dao核心类
        UserDao udao = new UserDao();
        
        return udao.selectOne2(user);
            
        
    }
    
}
  • JdbcUtils.java
/*
 * 
 * 配置文件:
 * 
 */
public class JdbcUtils {
    
    //使用ResouceBundle
    private static String driverClass = null ;
    private static String url = null ;
    private static String username = null ;
    private static String password = null ;
    
    static {
        //专门用于读取properties文件
        //properties文件要放在src下
        ResourceBundle bundle = ResourceBundle.getBundle("db");
        
        driverClass = bundle.getString("driverClass");
        url = bundle.getString("url");
        username = bundle.getString("username");
        password = bundle.getString("password");
    }
    
    
    
    
    public static Connection getConnection() {
        
        
        try {
            loadDriver();
            //建立连接
            
            
            
            return DriverManager.getConnection(url,username,password);
            
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
        
        
    }

    private static void loadDriver() {
        
        try {
            //这里是加载字节码.在Driver类中,
            Class.forName(driverClass);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    //释放资源
    public static void release(ResultSet rs ,Statement stmt, Connection conn) {
        if(rs != null) {
            try {
                //释放获得的资源
                rs.close();
            } catch (SQLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }   
            
            //设置为空:斩断引用的对象
            //有利于回收垃圾
            rs = null;
            
        }
        
        if(stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            stmt = null;
        }
        if(conn != null) {
            
            try {
                conn.close();
            } catch (SQLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            
            conn = null;
            
        }

    }
    
}

  • LoginService.java
/*
 * 
 * 处理用户登录请求的servlce
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        //获得用户名和密码
        User user = new User();
        
        try {
            
            //使用BeanUtils封装javabean
            BeanUtils.populate(user, request.getParameterMap());
            
            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
            //调用业务层完成登录
            UserService us = new UserService();
            User loginUser = us.login(user);
        
            if(loginUser == null) {
                //说明登录失败,提示错误信息
                request.setAttribute("message", "对不起,用户名或密码错误,不要瞎搞.....");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
            
            }else {
                
                //登录成功,将登陆的用户存到session域中
                request.getSession().setAttribute("loginUser", loginUser);
                response.sendRedirect(request.getContextPath()+"/index.jsp");
                
            }
    }

    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
  • .properties
url=jdbc\:mysql\:///day15_jdbc
username=root
password=123456
driverClass=com.mysql.jdbc.Driver

你可能感兴趣的:((2-23)使用jdbc实现web数据存储(二))