目录
4.工具类文件SqlSessionFactoryUtils.java
3. 注意细节3 : 表格宽度不够,可以brank.jsp中设置
4.书写数据时 描述信息:这里>${brand.description}<是写在外面的
1.MVC介绍
1.MVC 是一种分层开发的模式,其中:
- M:Model,业务模型,处理业务
- V:View,视图,界面展示
- C:Controller,控制器,处理请求,调用模型和视图
2.MVC 好处:
- 职责单一,互不影响
- 有利于分工协作
- 有利于组件重用
2.三层架构
- 数据访问层:对数据库的CRUD基本操作
- 业务逻辑层:对业务逻辑进行封装,组合数据访问层层中基本功能,形成复杂的业务逻辑功能
- 表现层:接收请求,封装数据,调用业务逻辑层,响应数据
一、准备使用操作
1.创建项目后,快速补齐web.xml文件
2.创建三层架构的包文件
3.数据库文件tb_brand.sql
-- 删除tb_brand表
drop table if exists tb_brand;
-- 创建tb_brand表
create table tb_brand
(
-- id 主键
id int primary key auto_increment,
-- 品牌名称
brand_name varchar(20),
-- 企业名称
company_name varchar(20),
-- 排序字段
ordered int,
-- 描述信息
description varchar(100),
-- 状态:0:禁用 1:启用
status int
);
-- 添加数据
insert into tb_brand (brand_name, company_name, ordered, description, status)
values ('三只松鼠', '三只松鼠股份有限公司', 5, '好吃不上火', 0),
('华为', '华为技术有限公司', 100, '华为致力于把数字世界带入每个人、每个家庭、每个组织,构建万物互联的智能世界', 1),
('小米', '小米科技有限公司', 50, 'are you ok', 1);
SELECT * FROM tb_brand;
4.工具类文件SqlSessionFactoryUtils.java
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 {
//静态代码块会随着类的加载而自动执行,且只执行一次
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;
}
}
5.MyBatis 基础环境
- 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="hsp"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--扫描mapper-->
<package name="com.itheima.mapper"/>
</mappers>
</configuration>
- 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.itheima.mapper.BrandMapper">
<resultMap id="brandResultMap" type="brand">
<result column="brand_name" property="brandName"></result>
<result column="company_name" property="companyName"></result>
</resultMap>
</mapper>
- BrandMapper接口
package com.itheima.mapper;
import com.itheima.pojo.Brand;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface BrandMapper {
/*
* 查询所有
* */
@Select("select * from tb_brand")
@ResultMap("brandResultMap")
List<Brand> selectAll();
/*
* 添加
* */
@Insert("insert into tb_brand values (null,#{brandName}," +
"#{companyName},#{ordered},#{description},#{status})")
void add(Brand brand);
/*
* 根据id查询(修改)
* */
@Select("select * from tb_brand where id=#{id}")
@ResultMap("brandResultMap")
Brand selectById(int id);
/*
* 修改
* */
@Update("update tb_brand set brand_name = #{brandName},company_name = #{companyName},ordered = #{ordered},description = #{description},status = #{status} where id =#{id}")
void update(Brand brand);
/*
删除单个
*/
@Delete("delete from tb_brand where id = #{id}")
void deleteById(int id);
}
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>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<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>
6.实体类 Brand
package com.itheima.pojo;
/**
* 品牌实体类
*/
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 +
'}';
}
}
二、案例演示步骤
1.查询
三层架构好处:大大提高了代码的复用性
1.注意细节1 :提高访问权限(可以放在成员位置)
private BrandService service = new BrandService();
2. 注意细节2 :在JSP中引入了jstl 的标签库
3. 注意细节3 : 表格宽度不够,可以brank.jsp中设置
4. 注意细节4:访问有没有值的问题解决
1.原因:对应实体类属性名称和数据库字段名称不一致导致
2.解决:@ResultMap("brandResultMap") 位置如下图所示:
<resultMap id="brandResultMap" type="brand"> <result column="brand_name" property="brandName"></result> <result column="company_name" property="companyName"></result> </resultMap>
最终成功 访问到值
5.代码
selectAllServlet.java
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;
/**
* @author Administrator
*/
@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);
}
}
mapper
/*
* 查询所有
* */
@Select("select * from tb_brand")
@ResultMap("brandResultMap")
List<Brand> selectAll();
BrandService
SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
/*
*
* 查询所有
*
* */
public List<Brand> selectAll() {
//1. 调用BrandMapper.selectAll()
//2.获取SqlSession
SqlSession sqlSession = factory.openSession();
//3.获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//4.调用方法
List<Brand> brands = mapper.selectAll();
sqlSession.close();
return brands;
}
2.添加
1.运用了请求加响应
2.细节一: 对于页面操作的onclick事件编写
使用document.getElementById()在文档中指定id元素,并使用function(){}处理单击该元素时发生的事件。
3.细节二:添加中要提交事务
4.细节三:添加中的数据乱码问题解决
//处理Post请求乱码问题 request.setCharacterEncoding("utf-8");
5.细节四:添加中页面的操作,跳转
6.代码
AddServlet.java
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;
/**
* @author Administrator
*/
@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");
//1.1.封装一个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.转发到查询所有的service
request.getRequestDispatcher("/selectAllServlet").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
mapper
/*
* 添加
* */
@Insert("insert into tb_brand values (null,#{brandName}," +
"#{companyName},#{ordered},#{description},#{status})")
void add(Brand brand);
BrandService
/*
* 添加
*
* */
public void add(Brand brand){
//2.获取SqlSession
SqlSession sqlSession = factory.openSession();
//3.获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//4.调用方法
mapper.add(brand);
//5.提交事务
sqlSession.commit();
//6释放资源
sqlSession.close();
}
addBrand.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2022/8/14
Time: 15:11
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="/brand-demo/addServlet" 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>
brand.jsp
<body> <input type="button" value="新增" id="add"><br> <hr> <table border="1" cellspacing="0" width="80%">
<script> document.getElementById("add").onclick = function (){ location.href = "/brand-demo/addBrand.jsp"; } </script>
3.修改-回显数据
1.存在id的操作
@Select("select * from tb_brand where id=#{id}") @ResultMap("brandResultMap") Brand selectById(int id);
2.隐藏id的操作(用户不想看到id)
<%-- 隐藏域 提交id --%> <input type="hidden" name="id" value="${brand.id}">
3.回显操作的原理
回显代码
update.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2022/8/14
Time: 15:11
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>修改品牌</title>
</head>
<body>
<h3>修改品牌</h3>
<form action="/brand-demo/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>
mapper
/*
* 根据id查询(修改)
* */
@Select("select * from tb_brand where id=#{id}")
@ResultMap("brandResultMap")
Brand selectById(int id);
BrandService
/*
* 根据id查询
*
* */
public Brand selectById(int id) {
//1. 调用BrandMapper.selectAll()
//2.获取SqlSession
SqlSession sqlSession = factory.openSession();
//3.获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//4.调用方法
Brand brand = mapper.selectById(id);
sqlSession.close();
return brand;
}
brand.jsp
<td width=80><a href="/brand-demo/selectByIdServlet?id=${brand.id}">修改</a>
4.书写数据时 描述信息:这里>${brand.description}<是写在外面的
5.细节:<c:if> 判断status默认值
结果:
6.进行真正修改工作时,页面的路径和数据库的对应数据要一致
成功修改:
7.代码
UpdateServlet.java
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;
/**
* @author Administrator
*/
@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");
//1.1.封装一个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.转发到查询所有的service
request.getRequestDispatcher("/selectAllServlet").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
mapper
/*
* 修改
* */
@Update("update tb_brand set brand_name = #{brandName},company_name = #{companyName},ordered = #{ordered},description = #{description},status = #{status} where id =#{id}")
void update(Brand brand);
brand.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="button" value="新增" id="add"><br>
<hr>
<table border="1" cellspacing="0" width="80%">
<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>${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 width=80><a href="/brand-demo/selectByIdServlet?id=${brand.id}">修改</a> <a href="/brand-demo/deleteByIdServlet?id=${brand.id}">删除</a></td>
</tr>
</c:forEach>
</table>
<script>
document.getElementById("add").onclick = function (){
location.href = "/brand-demo/addBrand.jsp";
}
</script>
</body>
</html>
4.删除
代码:
mapper
/* 删除单个 */ @Delete("delete from tb_brand where id = #{id}") void deleteById(int id);
BrandService
/*
* 根据id删除
*
* */
public void deleteById(int id) {
//2.获取SqlSession
SqlSession sqlSession = factory.openSession();
//3.获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//4.调用方法
mapper.deleteById(id);
//5.提交事务
sqlSession.commit();
//6释放资源
sqlSession.close();
}
SelectByIdServlet
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;
/**
* @author Administrator
*/
@WebServlet("/selectByIdServlet")
public class SelectByIdServlet 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 查询
Brand brand = service.selectById(Integer.parseInt(id));
//3. 存储到request中
request.setAttribute("brand",brand);
//4.转发到update.jsp
request.getRequestDispatcher("/update.jsp").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
brand.jsp
<a href="/brand-demo/deleteByIdServlet?id=${brand.id}">删除</a></td>
成功