web/service/dao 三层每层的作用
三层结构目的就是解耦,一般分别在三个包下
案例:使用三层结构和DAO模式登陆
(1) 数据库信息
(2). 创建数据库表对应的类User
public class User {
private int id;
private String username;
private String password;
private String email;
public int getId() {
return id;
}
public User(int id, String username, String password, String email) {
this.id = id;
this.username = username;
this.password = password;
this.email = email;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getEmail() {
return email;
}
public void setId(int id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", email='" + email + '\'' +
'}';
}
}
(3) web 层代码: 主要接收前端数据,以及响应数据
public class LoginWeb {
public static void main(String[] args) {
// 定义变量, 存储 `用户名和密码`
String username = "zhangsan";
String password = "888";
LoginServce servce = new LoginServce();
//登陆成功返回用户信息
User user = servce.login(username, password);
//判断是否登陆成功
if (user == null) {
System.out.println("登陆失败!!!!!!");
System.out.println("用户名或者密码错误~~~~~");
} else {
System.out.println("登陆成功!!!!!!");
System.out.println(user);
}
}
}
(4)service 层代码: 主要处理业务代码
异常也是在这层处理
public class LoginServce {
public User login(String username, String password) {
//登陆 查询数据库
User user = null;
try {
LoginDao dao = new LoginDao();
user = dao.findUserByNameAndPwd(username, password);
} catch (SQLException e) {
e.printStackTrace();
System.out.println("服务器正在维护~~~~");
}
return user;
}
}
(5)Dao 层代码: 和数据库打交道,对数据库增删改
这里连接数据库使用的是数据库连接池获取连接
public class LoginDao {
public User findUserByNameAndPwd(String name, String pwd) throws SQLException {
//和数据库连接
ComboPooledDataSource dataSource = new ComboPooledDataSource();
Connection connection = dataSource.getConnection();
String sql = "select * from user where username=? and password =? ";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, name);
preparedStatement.setString(2, pwd);
ResultSet resultSet = preparedStatement.executeQuery();
User user = null;
while (resultSet.next()) {
int id = resultSet.getInt("id");
String password = resultSet.getString("password");
String username = resultSet.getString("username");
String email = resultSet.getString("email");
user = new User(id, username, password, email);
}
return user;
}
}