我正在参加「启航计划」
项目简介
1.四层架构的模型图
2.过程
1.创立数据库(创立表)
2.导入需求的jar包(导入WebContent目录下的WEB-INF下的bin目录里面)
3.创立包: com.yfh.pojo(装实体类)
com.yfh.web(装dao类
com.yfh.service(装service类
com.yfh.servlet(装servlet类)
com.yfh.util(装东西类)
4.创立JDBC东西类(运用Druid数据库连接池
5.装备数据库及连接池参数(放于src下)
6.实体类层:用来封装属性及其get set办法 toString办法,有参结构办法,无参结构办法等。
7.Dao层:对数据库的增删改查办法的封装(操作数据库)也是属于事务逻辑
8.Servlet(Controller):流程操控
9.Service:处理事务逻辑
10.jsp(View)页面(坐落WebContent目录下)
项目完结
项目包预览
环境搭建
创立新的模块 brand_demo,并在 pom.xml 文件引入坐标
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>brand-demo</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>brand-demo Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
</dependencies>
<build>
<finalName>brand-demo</finalName>
</build>
</project>
在 com.yfh 包下创立三层架构的包结构,并将创立(若现成的则导入)数据库表 tb_brand
在 com.yfh.pojo 包下创立实体类 Brand
/**
* 品牌实体类
*/
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 +
'}';
}
}
预备 MyBatis 基础环境
在 com.yfh.mapper 创立 BrandMapper
public interface BrandMapper {
}
在 resources 文件夹下增加 Mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="com.yfh.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///test?useSSL=false&useServerPrepStmts=true"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.yfh.mapper"/>
</mappers>
</configuration>
在 resources 文件夹下创立 com.yfh.mapper 包,并在该包下创立 BrandMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yfh.mapper.BrandMapper">
<resultMap id="brandResultMap" type="brand">
<result column="brand_name" property="brandName"></result>
<result column="company_name" property="companyName"></result>
</resultMap>
</mapper>
查询一切功用完结
完结 Dao 层,经过 select * from tb_brand 完结查询表中的一切内容
public interface BrandMapper {
/**
* 查询一切
* @return
*/
@Select("select * from tb_brand")
@ResultMap("brandResultMap")
List<Brand> selectAll();
}
在完结 Service 层之前将 SqlSessionFactory 类导入到 com.yfh.util 包下
public class SqlSessionFactoryUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
//静态代码块会随着类的加载而主动履行,且只履行一次
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSessionFactory getSqlSessionFactory(){
return sqlSessionFactory;
}
}
完结 Service 层,创立 BrandService 类,完结查询一切的逻辑功用 (根本过程:树立sql会话,经过sql会话获取mapper目标,最终调用存储在一个变量后回来,留意查询完之后一定要封闭会话)
/**
* 查询一切
* @return
*/
public List<Brand> selectAll(){
//调用BrandMapper.selectAll()
SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
//1.获取SqlSession
SqlSession sqlSession = factory.openSession();
//2.获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//3.调用办法
List<Brand> brands = mapper.selectAll();
sqlSession.close();
return brands;
}
完结 web 层之写好 index.html 页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="/brand-demo/selectAllServlet">查询一切</a>
</body>
</html>
完结 web 层之完结 SelectAllServlet 类完结页面交互
@WebServlet("/selectAllServlet")
public class SelectAllServlet extends HttpServlet {
private BrandService service = new BrandService();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 调用BrandService完结查询
List<Brand> brands = service.selectAll();
//2.存入request域中
request.setAttribute("brands",brands);
//3.转发到brand.jsp
request.getRequestDispatcher("/brand.jsp").forward(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
}
完结 web 层之在 webapp 包下完结 brand.jsp 页面
<%--
Created by IntelliJ IDEA.
User: yy
Date: 2023/1/10
Time: 00:41
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="addBrand.jsp">
<button>新增</button>
</a>
<hr>
<table border="1" cellpadding="0" width="100%" align="center">
<tr align="center">
<td>序号</td>
<td>品牌称号</td>
<td>企业称号</td>
<td>排序</td>
<td>品牌介绍</td>
<td>状况</td>
<td>操作</td>
</tr>
<c:forEach items="${brands}" var="brand" varStatus="status">
<tr align="center">
<td>${status.count}</td>
<td>${brand.brandName}</td>
<td>${brand.companyName}</td>
<td>${brand.ordered}</td>
<td>${brand.description}</td>
<c:if test="${brand.status == 1}">
<td>启用</td>
</c:if>
<c:if test="${brand.status != 1}">
<td>禁用</td>
</c:if>
<td><a href="/selectByIdServlet?id=${brand.id}">修改</a> <a href="/deleteByIdServlet?id=${brand.id}">删去</a></td>
</tr>
</c:forEach>
</table>
</body>
</html>
查询一切页面作用
增加数据功用完结
完结 Dao 层,经过 insert into tb_brand values(null,brand_name,company_name,ordered,description,status) 完结增加数据
public interface BrandMapper {
/**
* 增加数据
* @param brand
*/
@Insert("insert into tb_brand values(null,#{brandName},#{companyName},#{ordered},#{description},#{status})")
void add(Brand brand);
}
完结 Service 层,在 BrandService 类,完结查询一切的逻辑功用 (根本过程:树立sql会话,经过sql会话获取mapper目标,最终调用并commit,留意查询完之后一定要封闭会话)
/**
* 增加数据
* @param brand
*/
public void add(Brand brand){
//调用BrandMapper.selectAll()
SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
//1.获取SqlSession
SqlSession sqlSession = factory.openSession();
//2.获取brandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//3.调用办法
mapper.add(brand);
sqlSession.commit();
sqlSession.close();
}
完结 web 层之在 brand.jsp 的头部增加增加 “按钮”
<input type="button" value="新增" id="add"><br>
完结 web 层之在 brand.jsp 的下面完结增加按钮的 js 脚本
<script>
document.getElementById("add").onclick = function (){
location.href = "/brand-demo/addBrand.jsp";
}
</script>
完结 web 层之写好 addBrand.jsp 页面
<%--
Created by IntelliJ IDEA.
User: yy
Date: 2023/1/10
Time: 13:52
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>增加品牌</title>
</head>
<body>
<h3>增加品牌</h3>
<form action="/addServlet" method="post">
品牌称号:<input type="text" name="brandName"> <br>
企业称号:<input type="text" name="companyName"> <br>
排序:<input type="number" name="ordered"> <br>
描绘信息:<textarea name="description" rows="1" cols="20"></textarea> <br>
状况:
<input type="radio" name="status" value="0"> 禁用
<input type="radio" name="status" value="1"> 启用 <br>
<button type="submit">提交</button>
</form>
</body>
</html>
完结 web 层之完结 AddServlet 类完结页面交互
@WebServlet("/addServlet")
public class AddServlet extends HttpServlet {
private BrandService service = new BrandService();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//处理POST恳求的编码处理问题
request.setCharacterEncoding("utf-8");
//1.接纳表单提交的数据,封装为一个Brand目标
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 = new Brand();
brand.setBrandName(brandName);
brand.setCompanyName(companyName);
brand.setOrdered(Integer.parseInt(ordered));
brand.setDescription(description);
brand.setStatus(Integer.parseInt(status));
//2.调用Service,完结增加
service.add(brand);
//3.转发到查询一切Servlet
request.getRequestDispatcher("selectAllServlet").forward(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
}
增加数据页面作用
修正数据功用完结
回显数据
完结 Dao 层,经过 select * from tb_brand where id=#{id} 完结增加数据
public interface BrandMapper {
/**
* 根据id查询
* @param id
* @return
*/
@Select("select * from tb_brand where id=#{id}")
@ResultMap("brandResultMap")
Brand selectById(int id);
}
完结 Service 层,创立 BrandService 类,完结根据id查询逻辑功用 (根本过程:树立sql会话,经过sql会话获取mapper目标,最终调用存储在一个变量后回来,留意查询完之后一定要封闭会话);
/**
* 根据id查询
* @param id
* @return
*/
public Brand selectById(int id){
//调用BrandMapper.selectById(id)
SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
//1.获取SqlSession
SqlSession sqlSession = factory.openSession();
//2.获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//3.调用办法
Brand brand = mapper.selectById(id);
sqlSession.close();
return brand;
}
修正数据
完结 Dao 层,经过 update tb_brand set brand_name=#{brandName},company_name=#{companyName},ordered=#{ordered},description=#{description},status=#{status} where id=#{id} 完结修正数据
@Update("update tb_brand set brand_name=#{brandName},company_name=#{companyName},ordered=#{ordered},description=#{description},status=#{status} where id=#{id}")
@ResultMap("brandResultMap")
void update(Brand brand);
完结 Service 层,创立 BrandService 类,调用修正数据功用 (根本过程:树立sql会话,经过sql会话获取mapper目标,留意查询完之后一定要封闭会话);
/**
* 修正数据
* @param brand
*/
public void update(Brand brand){
//调用BrandMapper.update(brand)
SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
//1. 获取SqlSession
SqlSession sqlSession = factory.openSession();
//2.获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//3.调用办法
mapper.update(brand);
sqlSession.commit();
sqlSession.close();
}
完结 web 层之在 brand.jsp 页面把修正链接增加链接地址
完结 web 层之在 brand.jsp 页面把修正链接增加链接地址
完结 web 层之在 updata.jsp 页面回显数据,留意回显的数据回传回id,需求把id隐藏起来,这是不需求展现给用户来看的;
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: yy
Date: 2023/1/10
Time: 15:17
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>修改</title>
</head>
<body>
<h3>修改品牌</h3>
<form action="/upDateServlet" method="post">
<input type="text" name="id" value="${brand.id}">
品牌称号:<input type="text" name="brandName" value="${brand.brandName}"> <br>
企业称号:<input type="text" name="companyName" value="${brand.companyName}"> <br>
排序:<input type="text" name="ordered" value="${brand.ordered}"> <br>
描绘信息:<textarea name="description" rows="1" cols="20">${brand.description}</textarea> <br>
状况:
<c:if test="${brand.status == 0}">
<input type="radio" name="status" value="0" checked> 禁用
<input type="radio" name="status" value="1"> 启用 <br>
</c:if>
<c:if test="${brand.status == 1}">
<input type="radio" name="status" value="0"> 禁用
<input type="radio" name="status" value="1" checked> 启用 <br>
</c:if>
<button type="submit">提交</button>
</form>
</body>
</html>
完结 web 层之完结 UpdateServlet 类完结页面交互
@WebServlet("/updateServlet")
public class UpdateServlet extends HttpServlet {
private BrandService service = new BrandService();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//处理POST恳求的编码处理问题
request.setCharacterEncoding("utf-8");
//1.接纳表单提交的数据,封装为一个Brand目标
String id = request.getParameter("id");
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 = new Brand();
brand.setId(Integer.parseInt(id));
brand.setBrandName(brandName);
brand.setCompanyName(companyName);
brand.setOrdered(Integer.parseInt(ordered));
brand.setDescription(description);
brand.setStatus(Integer.parseInt(status));
//2.调用Service,完结修正
service.update(brand);
//3.转发到SelectAllServlet
request.getRequestDispatcher("selectAllServlet").forward(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
}
删去数据(额外增加的功用)
完结 Dao 层,经过 delete from tb_brand where id=#{id} 完结删去数据
/**
* 根据id删去数据
* @param id
*/
@Delete("delete from tb_brand where id=#{id}")
@ResultMap("brandResultMap")
void deleteById(int id);
完结 Service 层,创立 BrandService 类,调用删去数据功用 (根本过程:树立sql会话,经过sql会话获取mapper目标,留意查询完之后一定要封闭会话);
/**
* 根据id删去数据
* @param id
*/
public void delete(int id){
//调用BrandMapper.delete(id)
SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
//1.获取SqlSession
SqlSession sqlSession = factory.openSession();
//2.获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//3.调用办法
mapper.deleteById(id);
sqlSession.commit();
sqlSession.close();
}
完结 web 层之在 brand.jsp 页面把删去链接增加链接地址
<a href="/brand-demo/deleteByIdServlet?id=${brand.id}">删去</a>
完结 web 层之完结 DeleteByIdServlet 类完结页面交互
@WebServlet("/deleteByIdServlet")
public class DeleteByIdServlet extends HttpServlet {
private BrandService service = new BrandService();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.接纳需求删去数据的id
String id = request.getParameter("id");
//2.调用Service
service.delete(Integer.parseInt(id));
//3.转发至SelectAllServlet
request.getRequestDispatcher("selectAllServlet").forward(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
}