JSP(三层架构与MVC模式)

例子:
1.准备数据库
2.BASEDAO
3.用户登录包含两类:会员、管理员
管理员:操作的是Admin类
会员:操作的是User类
4.创建两个表对应的实体类
5.创建对应表格的DAO类

MVC与三层架构
三层架构 MVC(Model、View、Controller)
表示层(servlet、jsp)------->C(servlet)、V(jsp)
业务逻辑层(service)------------>M(service、entity)
数据访问层(DAO)--------------->M(DAO)

  1. BaseDAO部分代码:
    private static final String URL="jdbc:mysql://127.0.0.1:3306/cartoondb2018"private static final String URL=“jdbc:mysql://127.0.0.1:3306/cartoondb2018”
    private static final String USER=“root”;
    private static final String PASSWORD=“123456”;
    private static final String DRIVER=“com.mysql.jdbc.Driver”;
    public static final Connection getConnection(){
    try{
    Class.forName(DRIVER);
    }catch{… return null;}
    Connection con =null;
    try{
    con=DriverManager.getConnection(URL,USER,PASSWORD);
    return con;
    }catch{…}
    return null;
    }
    public static void close(Connection con,PreparedStatement pstmt,ResultSet rs){
    try{
    if(rs != null)rs.close();
    if(pstmt != null)pstmt.close();
    if(con != null&& !con.isClosed())con.close();
    }catch{…}
    }

  2. Admin.java(实体类):
    private int id;
    private String userName;
    private String trueName;
    ----->空白处右击------>Source------->Generate Getters and Setters

  3. AdminDAO(增删改查四个方法,这里只写查询)
    public Admin select (String userName,String userPwd){
    Connection con=BaseDAO.getConnection();
    if(con != null){
    preparedStatement pstmt=null;
    try{
    String sql=“select * from admin where username=? and userpwd=?”;
    pstmt=con.prepareStatement(sql);
    pstmt.setString(1,userName);
    pstmt.setString(2,userPwd);
    rs=pstmt.executeQuery();
    if(rs != null&& rs.next()){
    Admin admin=new Admin();
    admin.setId(rs.getInt(“id”));
    admin.setUserName(rs.getString(“username”));
    admin.setUserPwd(rs.getString(“userpwd”));
    admin.setTrueName(rs.getString(“truename”));
    return admin;
    }
    }catch{…}finally{
    BaseDAO.close(con,pstmt,rs);
    }

}
return null;
}
4. AdminService.java(完成管理员的登陆功能)
private AdminDAO admindao=new AdminDAO();
public boolean login(String userName,String userPwd){
Admin admin=admindao.select(userName,userPwd);
if(admin == null){
return false;
}else{
return true;
}

} 

你可能感兴趣的:(myeclipse,课堂笔记)