五. 三层架构
表示层(USL,User Show Layer,视图层)
业务逻辑层(BLL,Bussiness Logic Layer,Service层)
数据访问层(DAL,Data Access Layer,Dao层)
1. 三层架构与MVC
a. 表示层(USL,User Show Layer,视图层)
- 前台:对应MVC中的view,用于和用户交互、界面的显示
jsp、js、html、css、jquery等Web前端技术
代码位置:WebContent
- 后台:对应MVC中的controller,用于控制跳转、调用业务逻辑层
Servlet(SpringMVC Struts2)
代码位置:xxx.servlet包中
b. 业务逻辑层(BLL,Bussiness Logic Layer,Service层)
- 接受表示层的请求 调用
- 组装数据访问层,逻辑性的操作(增删改查,增删改:查+增删改)
代码位置:xxx.service包中(有时候也称为:xxx.manager、xx. bll)
c. 数据访问层(DAL,Data Access Layer,Dao层)
- 直接访问数据库的操作,原子性操作(增删改查)
代码位置:xxx.dao
2. 三层间的关系
上层 将请求传递给下层,下层处理后 返回给上层
3. 三层优化
a.加入接口
建议面向接口开发:先接口-再实现类
–service、dao加入接口
–接口与实现类的命名规范
-
接口:interface,
起名:I实体类Service、IStudentService、IStudentDao -
实现类:implements
起名:实体类ServiceImpl、StudentServiceImpl、StudentDaoImpl -
接口: I实体类层所在包名 IStudentService、IStudentDao
-
实现类:实体类层所在包名 Impl StudentServiceImpl、 StudentDaoImpl
以后使用接口/实现类时,推荐写法:
接口x = new 实现类();
IStudentDao studentDaoImpl = new StudentDaoImpl();
a. DBUtil 数据库帮助类,
简化Dao层
4. 示例:
整体结构👇
其中几个文件
DBUtil.java👇
package three_tier.util;
import three_tier.entity.Student;
import java.sql.*;
/**
* @Author: qsX
* @Time: 2020-05-06 16:18
* @Description: 数据库帮助类
*/
public class DBUtil {
private static final String URL = "jdbc:oracle:thin:@localhost:1521:ORCL";
private static final String USERNAME = "scott";
private static final String PSAAWORD = "tiger";
public static Connection connection = null;
public static PreparedStatement pstmt = null;
public static ResultSet rs = null;
/**
* @Description 获取连接
* @Param []
* @Return java.sql.Connection
*/
public static Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName("oracle.jdbc.OracleDriver");
return DriverManager.getConnection(URL, USERNAME, PSAAWORD);
}
/**
* @Description 关闭所有接口
* @Param [rs, stmt, connection]
* @Return void
*/
public static void closeAll (ResultSet rs,Statement stmt,Connection connection) {
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* @Description 获取PreparedStatement
* @Param [String sql,Object[] params]
* @Return PreparedStatement
*/
public static PreparedStatement createPreparedStatement(String sql,Object[] params) throws SQLException, ClassNotFoundException {
//Object[] params = {name,age,...};
pstmt = getConnection().prepareStatement(sql);
//setxxx()的个数依赖于?的个数 ; ?的个数依赖于数组params的长度
if (params!=null) {
for (int i = 0 ; i < params.length ; i++) {
pstmt.setObject(i+1,params[i]);
}
}
return pstmt;
}
/**
* @Description 通用增删改
* @Param [String sql,Object[] params]
* @Return boolean
*/
public static boolean executeUpdate(String sql,Object[] params) {
try {
pstmt = createPreparedStatement(sql, params);
int count = pstmt.executeUpdate();
if (count > 0