一图胜万言
架构图
为什么要使用3层架构
1 方便团队分工 利于维护
2 规范代码,在开发软件时对每个层的代码进行规范,固定开发语言的风格。
3 降低更新难度,当软件系统要换数据库时,只要将数据访问层的代码修改就好了。
4 实现"高内聚、低耦合"。易于分配资源。
5 是使得代码逻辑清晰。
各个部分应有的文件
表现层
应该有的文件(jsp+servlet)
业务逻辑层
应该有的文件(service的接口,及其实现的逻辑代码)
数据访问层
应该有的
DAO(全称Data Access Object,意为数据访问接口/对象)
DAO中也应该定义接口,及其实现(具体指增删改查的代码)
entity(意为实体类是数据库表的映射)
utils是工具集的意思,其中连接数据库,关闭数据库/数据源/对象的一些操作应该写在这里的某个类里面
各层示例代码
表现层
jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<input type="button" id="add" value="新增"><br>
<hr>
<table border="1" cellspacing="0" width="800">
<tr>
<th>序号</th>
<th>品牌名称</th>
<th>企业名称</th>
<th>排序</th>
<th>品牌介绍</th>
<th>状态</th>
<th>操作</th>
<c:forEach items="${brands}" var="brand">
<tr align="center">
<td>${brand.id}</td>
<td>${brand.brandName}</td>
<td>${brand.companyName}</td>
<td>${brand.ordered}</td>
<td>${brand.description} </td>
<td>${brand.status}</td>
<td><a href="#">修改</a> <a href="#">删除</a></td>
</tr>
</c:forEach>
</table>
<script>
document.getElementById("add").onclick = function (){
location.href = "addBrand.jsp";
}
</script>
</body>
</html>
servlet
package com.teaching.jsp.servlet;
import com.teaching.jsp.entity.Brand;
import com.teaching.jsp.service.BrandService;
import com.teaching.jsp.service.impl.BrandServiceImpl;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet(name = "AddBrandServlet", value = "/addBrand")
public class AddBrandServlet extends HttpServlet {
BrandService brandService=new BrandServiceImpl();
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf8");
//接收参数
String brandName = request.getParameter("brandName");
String companyName = request.getParameter("companyName");
String ordered = request.getParameter("ordered");
String description = request.getParameter("description");
String status = request.getParameter("status");
//封装Brand
Brand brand = new Brand();
brand.setBrandName(brandName);
brand.setDescription(description);
brand.setCompanyName(companyName);
brand.setOrdered(Integer.valueOf(ordered));
brand.setStatus(Integer.valueOf(status));
//调用Service去处理业务
brandService.insertBrand(brand);
//转发到selectAll
response.sendRedirect("/teachingJsp/selectBrand");
}
}
业务逻辑层
service 接口
package com.teaching.jsp.service;
import com.teaching.jsp.entity.Brand;
import java.util.List;
public interface BrandService {
List<Brand> selectAllBrand();
boolean insertBrand(Brand brand);
Brand selectBrandById(String id);
boolean updateBrand(Brand brand);
}
service逻辑
package com.teaching.jsp.service.impl;
import com.teaching.jsp.dao.BrandDao;
import com.teaching.jsp.dao.impl.BrandDaoImpl;
import com.teaching.jsp.entity.Brand;
import com.teaching.jsp.service.BrandService;
import java.util.List;
public class BrandServiceImpl implements BrandService {
BrandDao brandDao=new BrandDaoImpl();
@Override
public List<Brand> selectAllBrand() {
//逻辑略。。。
return brandDao.selectAll();
}
@Override
public boolean insertBrand(Brand brand) {
//逻辑略。。。
return brandDao.insert(brand);
}
@Override
public Brand selectBrandById(String id) {
//逻辑略。。。
return brandDao.selectBrandById(id);
}
@Override
public boolean updateBrand(Brand brand) {
//逻辑略。。。
return brandDao.updateBrand(brand);
}
}
数据访问层
dao 接口
package com.teaching.jsp.dao;
import com.teaching.jsp.entity.Brand;
import java.util.List;
//DAO 的全称是Data Access Object
public interface BrandDao {
List<Brand> selectAll();
boolean insert(Brand brand);
Brand selectBrandById(String id);
boolean updateBrand(Brand brand);
}
dao 操作
package com.teaching.jsp.dao.impl;
import com.teaching.jsp.dao.BrandDao;
import com.teaching.jsp.entity.Brand;
import com.teaching.jsp.utils.DbUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
//impl implement是实现的意思
public class BrandDaoImpl implements BrandDao {
@Override
public List<Brand> selectAll() {
List<Brand> list=new ArrayList<>();
//获取链接
Connection connection=null;
try {
//获取链接
connection = DbUtils.getConnection();
//开启事务
connection.setAutoCommit(false);
String sql="select * from task1.tb_brand";
//执行对象
PreparedStatement ps = connection.prepareStatement(sql);
//结果集
ResultSet rs = ps.executeQuery();
while (rs.next()){
Brand brand = new Brand(
rs.getInt(1),
rs.getString(2),
rs.getString(3),
rs.getInt(4),
rs.getString(5),
rs.getInt(6)
);
list.add(brand);
}
connection.commit();
DbUtils.close(ps,rs,null);
} catch (SQLException e) {
try {
connection.rollback();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
throw new RuntimeException(e);
} finally {
try {
DbUtils.close(connection);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
return list;
}
@Override
public boolean insert(Brand brand) {
//获取链接
Connection connection=null;
int row=0;
try {
//获取链接
connection = DbUtils.getConnection();
//开启事务
connection.setAutoCommit(false);
String sql="insert into task1.tb_brand(brand_name,company_name,ordered,description,status) values (?,?,?,?,?)";
//执行对象
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1,brand.getBrandName());
ps.setString(2,brand.getCompanyName());
ps.setInt(3,brand.getOrdered());
ps.setString(4,brand.getDescription());
ps.setInt(5,brand.getStatus());
row+= ps.executeUpdate();
connection.commit();
DbUtils.close(ps,null,null);
} catch (SQLException e) {
try {
connection.rollback();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
throw new RuntimeException(e);
} finally {
try {
DbUtils.close(connection);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
return row>0;
}
@Override
public Brand selectBrandById(String id) {
//获取链接
Connection connection=null;
Brand brand=null;
try {
//获取链接
connection = DbUtils.getConnection();
//开启事务
connection.setAutoCommit(false);
String sql="select * from tb_brand where id=?";
//执行对象
PreparedStatement ps = connection.prepareStatement(sql);
ps.setInt(1,Integer.valueOf(id));
//结果集
ResultSet rs = ps.executeQuery();
if (rs.next()){
brand = new Brand(
rs.getInt(1),
rs.getString(2),
rs.getString(3),
rs.getInt(4),
rs.getString(5),
rs.getInt(6)
);
}
connection.commit();
DbUtils.close(ps,rs,null);
} catch (SQLException e) {
try {
connection.rollback();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
throw new RuntimeException(e);
} finally {
try {
DbUtils.close(connection);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
return brand;
}
@Override
public boolean updateBrand(Brand brand) {
//获取链接
Connection connection=null;
int row=0;
try {
//获取链接
connection = DbUtils.getConnection();
//开启事务
connection.setAutoCommit(false);
String sql="update tb_brand set brand_name=?,company_name=?,ordered=?,description=?,status=? where id=?";
//执行对象
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1,brand.getBrandName());
ps.setString(2,brand.getCompanyName());
ps.setInt(3,brand.getOrdered());
ps.setString(4,brand.getDescription());
ps.setInt(5,brand.getStatus());
ps.setInt(6,brand.getId());
row+= ps.executeUpdate();
connection.commit();
DbUtils.close(ps,null,null);
} catch (SQLException e) {
try {
connection.rollback();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
throw new RuntimeException(e);
} finally {
try {
DbUtils.close(connection);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
return row>0;
}
}
entity
package com.teaching.jsp.entity;
public class Brand {
// id 主键
private Integer id;
// 品牌名称
private String brandName;
// 企业名称
private String companyName;
// 排序字段
private Integer ordered;
// 描述信息
private String description;
// 状态:0:禁用 1:启用
private Integer status;
public Brand() {
}
public Brand(Integer id, String brandName, String companyName, String description) {
this.id = id;
this.brandName = brandName;
this.companyName = companyName;
this.description = description;
}
public Brand(Integer id, String brandName, String companyName, Integer ordered, String description, Integer status) {
this.id = id;
this.brandName = brandName;
this.companyName = companyName;
this.ordered = ordered;
this.description = description;
this.status = status;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public Integer getOrdered() {
return ordered;
}
public void setOrdered(Integer ordered) {
this.ordered = ordered;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
@Override
public String toString() {
return "Brand{" +
"id=" + id +
", brandName='" + brandName + ''' +
", companyName='" + companyName + ''' +
", ordered=" + ordered +
", description='" + description + ''' +
", status=" + status +
'}';
}
}
dbutils
package com.teaching.jsp.utils;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
public class DbUtils {
private static DataSource dataSource;
static {
Properties prop=new Properties();
try {
prop.load(new FileInputStream("F:\JAVA EE Preject\课堂练习\src\com\teaching\jsp\db.properties"));
System.out.println("iiii");
dataSource = DruidDataSourceFactory.createDataSource(prop);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void test(){
System.out.println(DbUtils.class.getClassLoader().getResource("db.properties"));
}
public static Connection getConnection() throws SQLException {
System.out.println("iiii111");
return dataSource.getConnection();
}
public static void close(Connection connection) throws SQLException {
if (connection!=null){
connection.close();
}
}
public static void close(PreparedStatement ps, ResultSet rs,Connection connection) throws SQLException {
if (rs!=null){
rs.close();
}
if (ps!=null){
ps.close();
}
if (connection!=null){
connection.close();
}
}
}