文章目录
- 0. 项目介绍
- 1. 环境准备
- 2. 查看所有
- 2.1 编写BrandMapper接口
- 2.2 编写服务类,创建BrandService,用于调用该方法
- 2.5 编写Servlet
- 2.4 编写brand.jsp页面
- 2.5 测试
- 3.添加
- 3.1 编写BrandMapper接口 添加方法
- 3.2 编写服务
- 3.3 改写Brand.jsp页面,添加新增按钮,并跳转到新的jsp页面(addBrand页面)
- 3.4 编写Servlet
- 3.5 测试
- 4.修改/回显
- 4.1 回显数据
- 4.2 修改数据
- 5. 删除
0. 项目介绍
其他项目-用户登录注册页面:https://blog.csdn.net/meini32/article/details/132305323
项目介绍
需求:完成品牌数据的增删改查操作
技术框架说明
三层架构是将我们的项目分成了三个层面,分别是 表现层 、 业务逻辑层 、 数据访问层。
整个流程是,浏览器发送请求,表现层的Servlet接收请求并调用业务逻辑层的方法进行业务逻辑处理,而业务逻辑层方法调用数据访问层方法进行数据的操作,依次返回到serlvet,然后servlet将数据交由 JSP 进行展示。
- 数据访问层:Mybatis、mysql
- 业务逻辑层:JAVA
- 表现层:JSP、Servlet
实现步骤
1. 环境准备
环境准备
- 创建新的项目 brand_demo,引入坐标配置pom文件()
- 创建三层架构的包结构
- 数据库表 tb_brand
- 实体类 Brand
MyBatis 基础环境配置
Mybatis-config.xml
BrandMapper.xml
BrandMapper接口
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.itheima.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:///db1?useSSL=false&useServerPrepStmts=true"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--扫描mapper-->
<package name="com.itheima.mapper"/>
</mappers>
</configuration>
pom.xml文件配置
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>brand-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<!--servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--jsp-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<!--jstl-->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
</plugin>
</plugins>
</build>
</project>
工具类 SqlsessionFactoryUtils
package com.itheima.util;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class SqlSessionFactoryUtils {
private static SqlSessionFactory sqlSessionFactory;
static{
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream("mybatis-config.xml");
} catch (IOException e) {
e.printStackTrace();
}
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
public static SqlSessionFactory getSqlSessionFactory(){
return sqlSessionFactory;
}
}
属性名称对应不上解决方法
在BrandMapper映射文件里,定义映射关系
<?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">
<!--
namespace:名称空间
-->
<mapper namespace="com.itheima.mapper.BrandMapper">
<!-- resultMap 标签定义映射关系-->
<resultMap id="brandRseultMap" type="brand">
<result column="brand_name" property="brandName"></result>
<result column="company_name" property="companyName"></result>
</resultMap>
</mapper>
在接口方法中指定该映射
public interface BrandMapper {
//查看所有
@ResultMap("brandResultMap")
@Select("select * from tb_brand;")
List<Brand> selectAll();
}
2. 查看所有
说明:当我们点击 index.html 页面中的 查询所有 这个超链接时,就能查询到上图右半部分的数据。
2.1 编写BrandMapper接口
public interface BrandMapper {
//查看所有
@Select("select * from tb_brand;")
List<Brand> selectAll();
}
2.2 编写服务类,创建BrandService,用于调用该方法
package com.itheima.service;
import com.itheima.mapper.BrandMapper;
import com.itheima.pojo.Brand;
import com.itheima.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import java.util.List;
public class BrandService {
SqlSessionFactory sqlSessionFactory =SqlSessionFactoryUtils.getSqlSessionFactory();
//查所有
public List<Brand> selectAll(){
//调用BrandMapper中的selectAll方法
//获取SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取Mapper
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//调用方法
List<Brand> brands = brandMapper.selectAll();
sqlSession.close();
return brands;
}
}
2.5 编写Servlet
package com.itheima.web;
import com.itheima.pojo.Brand;
import com.itheima.service.BrandService;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;
@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);
}
}
2.4 编写brand.jsp页面
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page isELIgnored="false" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="button" 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>
</tr>
<c:forEach items="${brands}" var="brand" varStatus="status">
<tr align="center">
<%-- <td>${brand.id}</td>--%>
<td>${brand.id}</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==0}">
<td>禁止</td>
</c:if>
<td><a href="/brand-demo/selectByIdServlet?id=${brand.id}">修改</a> <a href="#">删
除</a></td>
</tr>
</c:forEach>
</table>
</body>
</html>
2.5 测试
3.添加
3.1 编写BrandMapper接口 添加方法
//添加
@Insert("insert into tb_brand values(null,#{brandName},#{companyName},#{ordered},#{description},#{status})")
void add(Brand brand);
3.2 编写服务
public class BrandService {
SqlSessionFactory sqlSessionFactory =SqlSessionFactoryUtils.getSqlSessionFactory();
//添加数据
public void add(Brand brand){
//调用BrandMapper中的selectAll方法
//获取SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取Mapper
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//调用方法
brandMapper.add(brand);
//提交事务
sqlSession.commit();
sqlSession.close();
}
}
3.3 改写Brand.jsp页面,添加新增按钮,并跳转到新的jsp页面(addBrand页面)
<%--
Created by IntelliJ IDEA.
User: 11445
Date: 2023/8/18
Time: 20:31
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>添加品牌</title>
</head>
<body>
<h3>添加品牌</h3>
<form action="" method="post">
品牌名称:<input name="brandName"><br>
企业名称:<input name="companyName"><br>
排序:<input name="ordered"><br>
描述信息:<textarea rows="5" cols="20" name="description"></textarea><br>
状态:
<input type="radio" name="status" value="0">禁用
<input type="radio" name="status" value="1">启用<br>
<input type="submit" value="提交">
</form>
</body>
</html>
3.4 编写Servlet
在 web 包下创建 AddServlet 的 servlet ,该 servlet 的逻辑如下:
- 设置处理post请求乱码的字符集
- 接收客户端提交的数据
- 将接收到的数据封装到 Brand 对象中
- 调用 BrandService 的 add() 方法进行添加的业务逻辑处理
- 跳转到 selectAllServlet 资源重新查询数据
package com.itheima.web;
import com.itheima.pojo.Brand;
import com.itheima.service.BrandService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/addServlet")
public class AddServlet extends HttpServlet {
private BrandService service = new BrandService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//处理post请求的乱码问题
req.setCharacterEncoding("utf-8");
//1. 接收表单提交的数据,封装为一个Brand对象
String brandName = req.getParameter("brandName");
String companyName = req.getParameter("companyName");
String ordered = req.getParameter("ordered");
String description = req.getParameter("description");
String status = req.getParameter("status");
//封装为一个Brand对象
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
req.getRequestDispatcher("/selectAllServlet").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req,resp);
}
}
3.5 测试
4.修改/回显
在该修改页面我们可以看到将 编辑 按钮所在行的数据 回显 到表单,然后需要修改那个数据在表单中进行修改,然后点击 提交 的按钮将数据提交到后端,后端再将数据存储到数据库中。
4.1 回显数据
//编写BrandMapper接口 添加方法
//回显,根据id查询
@Select("select * from tb_brand where id = #{id}}")
@ResultMap("brandResultMap")
Brand selectById(int id);
//编写服务
import java.util.List;
public class BrandService {
SqlSessionFactory sqlSessionFactory =SqlSessionFactoryUtils.getSqlSessionFactory();
public Brand selectById(int id){
//调用BrandMapper中的selectById方法
//获取SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取Mapper
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//调用方法
Brand brand = brandMapper.selectById(id);
sqlSession.close();
return brand;
}
}
编写servlet方法
package com.itheima.web;
import com.itheima.pojo.Brand;
import com.itheima.service.BrandService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet("/selectByIdServlet")
public class SelectByIdServlet extends HttpServlet {
//创建这个服务
private BrandService service = new BrandService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//接受id
String id = req.getParameter("id");
//1. 调用BrandService完成查询
Brand brand = service.selectById(Integer.parseInt(id));
//2. 存入request域中
req.setAttribute("brand",brand);
//3. 转发到brand.jsp
req.getRequestDispatcher("/update.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}
//编写update xml
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page isELIgnored="false" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>修改品牌</title>
</head>
<body>
<h3>修改品牌</h3>
<form action="/updateServlet" method="post">
<%--隐藏域,提交id--%>
<input type="hidden" name="id" value="${brand.id}">
品牌名称:<input name="brandName" value="${brand.brandName}"><br>
企业名称:<input name="companyName" value="${brand.companyName}"><br>
排序:<input name="ordered" value="${brand.ordered}"><br>
描述信息:<textarea rows="5" cols="20" name="description">${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>
<input type="submit" value="提交">
</form>
</body>
</html>
修改Brand.jsp的修改连接地址
效果
4.2 修改数据
//修改
@Update(“update tb_brand set brand_name = #{brandName},company_name = #{companyName},ordered =\n” +
“#{ordered},description = #{description},status = #{status} where id = #{id}”)
void update(Brand brand);
// 修改
public void update(Brand brand){
//调用BrandMapper中的selectById方法
//获取SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取Mapper
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//调用方法
brandMapper.update(brand);
//提交
sqlSession.commit();
sqlSession.close();
}
@WebServlet("/updateServlet")
public class UpdateServlet extends HttpServlet {
//创建这个服务
private BrandService service = new BrandService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//处理post请求的乱码问题
req.setCharacterEncoding("utf-8");
//1. 接收表单提交的数据,封装为一个Brand对象
String id = req.getParameter("id");
String brandName = req.getParameter("brandName");
String companyName = req.getParameter("companyName");
String ordered = req.getParameter("ordered");
String description = req.getParameter("description");
String status = req.getParameter("status");
//封装为一个Brand对象
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. 转发到查询所有Servlet
req.getRequestDispatcher("/selectAllServlet").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req,resp);
}
}
5. 删除
//删除
@Delete("delete from tb_brand where id = #{id}")
void deleteById(int id);
public void deleteById(int id){
SqlSession sqlSession = sqlSessionFactory.openSession();
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
brandMapper.deleteById(id);
sqlSession.commit();
sqlSession.close();
}
@WebServlet("/deleteByIdServlet")
public class DeleteByIdServlet extends HttpServlet {
BrandService service = new BrandService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String id = req.getParameter("id");
service.deleteById(Integer.parseInt(id));
req.getRequestDispatcher("/selectAllServlet").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}