目录
一.前期环境搭建
1.替换pom.xml的内容
2.导入配置文件(小编上传资源)
3.修改xml文件
4.点击创建自动生成代码
5.写一个类用于处理页面跳转
二.正式启动SpringMVC的CRUD
1.建立接口,调用自动生成的接口
2.构建分页代码
2.1书写BookMapper.xml中分页的方法
2.2调用分页的方法
2.3导入一个工具类用于分页实现
2.4导入一个tid文件用于分页实现
3.实现后端功能
3.1构建功能实现代码
3.2在BookMapper.xml文件编写查询的方法(并且实现)
3.3构建list界面(展示数据)
3.4构建edit界面
3.5效果展示
1.增加
2.删除
3.修改
4.查询
前言:
小编讲述了参数传递,返回值以及页面跳转!为我们的CRUD提供了理论基础,接下来小编会通过SpringMvc实现CRUD来讲述在企业开发中必须要学会的CRUD
一.前期环境搭建
1.替换pom.xml的内容
<properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.compiler.source>1.8</maven.compiler.source><maven.compiler.target>1.8</maven.compiler.target><maven.compiler.plugin.version>3.7.0</maven.compiler.plugin.version><!--添加jar包依赖--><!--1.spring 5.0.2.RELEASE相关--><spring.version>5.0.2.RELEASE</spring.version><!--2.mybatis相关--><mybatis.version>3.4.5</mybatis.version><!--mysql--><mysql.version>5.1.44</mysql.version><!--pagehelper分页jar依赖--><pagehelper.version>5.1.2</pagehelper.version><!--mybatis与spring集成jar依赖--><mybatis.spring.version>1.3.1</mybatis.spring.version><!--3.dbcp2连接池相关 druid--><commons.dbcp2.version>2.1.1</commons.dbcp2.version><commons.pool2.version>2.4.3</commons.pool2.version><!--4.log日志相关--><log4j2.version>2.9.1</log4j2.version><log4j2.disruptor.version>3.2.0</log4j2.disruptor.version><slf4j.version>1.7.13</slf4j.version><!--5.其他--><junit.version>4.12</junit.version><servlet.version>4.0.0</servlet.version><lombok.version>1.18.2</lombok.version><mybatis.ehcache.version>1.1.0</mybatis.ehcache.version><ehcache.version>2.10.0</ehcache.version><redis.version>2.9.0</redis.version><redis.spring.version>1.7.1.RELEASE</redis.spring.version><jackson.version>2.9.3</jackson.version><jstl.version>1.2</jstl.version><standard.version>1.1.2</standard.version><tomcat-jsp-api.version>8.0.47</tomcat-jsp-api.version><commons-fileupload.version>1.3.3</commons-fileupload.version><hibernate-validator.version>5.0.2.Final</hibernate-validator.version><shiro.version>1.3.2</shiro.version></properties>
<dependencies><!--1.spring相关--><dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-beans</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-orm</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aspects</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>${spring.version}</version></dependency><!--2.mybatis相关--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>${mybatis.version}</version></dependency><!--mysql--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>${mysql.version}</version></dependency><!--pagehelper分页插件jar包依赖--><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper</artifactId><version>${pagehelper.version}</version></dependency><!--mybatis与spring集成jar包依赖--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>${mybatis.spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId><version>${spring.version}</version></dependency><!--mybatis与ehcache整合--><dependency><groupId>org.mybatis.caches</groupId><artifactId>mybatis-ehcache</artifactId><version>${mybatis.ehcache.version}</version></dependency><!--ehcache依赖--><dependency><groupId>net.sf.ehcache</groupId><artifactId>ehcache</artifactId><version>${ehcache.version}</version></dependency><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>${redis.version}</version></dependency><dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-redis</artifactId><version>${redis.spring.version}</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>${jackson.version}</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>${jackson.version}</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-annotations</artifactId><version>${jackson.version}</version></dependency><!--3.dbcp2连接池相关--><dependency><groupId>org.apache.commons</groupId><artifactId>commons-dbcp2</artifactId><version>${commons.dbcp2.version}</version><exclusions><exclusion><artifactId>commons-pool2</artifactId><groupId>org.apache.commons</groupId></exclusion></exclusions></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId><version>${commons.pool2.version}</version></dependency><!--springmvc依赖--><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>${spring.version}</version></dependency><!--4.log日志相关依赖--><!-- log4j2日志相关依赖 --><!-- log配置:Log4j2 + Slf4j --><!-- slf4j核心包--><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>${slf4j.version}</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>jcl-over-slf4j</artifactId><version>${slf4j.version}</version><scope>runtime</scope></dependency><!--核心log4j2jar包--><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-api</artifactId><version>${log4j2.version}</version></dependency><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-core</artifactId><version>${log4j2.version}</version></dependency><!--用于与slf4j保持桥接--><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-slf4j-impl</artifactId><version>${log4j2.version}</version></dependency><!--web工程需要包含log4j-web,非web工程不需要--><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-web</artifactId><version>${log4j2.version}</version><scope>runtime</scope></dependency><!--需要使用log4j2的AsyncLogger需要包含disruptor--><dependency><groupId>com.lmax</groupId><artifactId>disruptor</artifactId><version>${log4j2.disruptor.version}</version></dependency><!--5.其他--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>${junit.version}</version><scope>test</scope></dependency><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>${servlet.version}</version><scope>provided</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>${lombok.version}</version><scope>provided</scope></dependency><dependency><groupId>jstl</groupId><artifactId>jstl</artifactId><version>${jstl.version}</version></dependency><dependency><groupId>taglibs</groupId><artifactId>standard</artifactId><version>${standard.version}</version></dependency><dependency><groupId>org.apache.tomcat</groupId><artifactId>tomcat-jsp-api</artifactId><version>${tomcat-jsp-api.version}</version></dependency><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>${commons-fileupload.version}</version></dependency><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-validator</artifactId><version>${hibernate-validator.version}</version></dependency><!--shiro依赖--><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-core</artifactId><version>${shiro.version}</version></dependency><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-web</artifactId><version>${shiro.version}</version></dependency><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-spring</artifactId><version>${shiro.version}</version></dependency></dependencies>
2.导入配置文件(小编上传资源)
3.修改xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"version="3.1"><display-name>Archetype Created Web Application</display-name><!-- Spring和web项目集成start --><!-- spring上下文配置文件 --><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-context.xml</param-value></context-param><!-- 读取Spring上下文的监听器 --><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- Spring和web项目集成end --><!-- 中文乱码处理 --><filter><filter-name>encodingFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><async-supported>true</async-supported><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param></filter><filter-mapping><filter-name>encodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><!-- Spring MVC servlet --><servlet><servlet-name>SpringMVC</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><!--此参数可以不配置,默认值为:/WEB-INF/springmvc-servlet.xml--><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-mvc.xml</param-value></init-param><load-on-startup>1</load-on-startup><!--web.xml 3.0的新特性,是否支持异步--><async-supported>true</async-supported></servlet><servlet-mapping><servlet-name>SpringMVC</servlet-name><url-pattern>/</url-pattern></servlet-mapping>
</web-app>
4.点击创建自动生成代码
在book的类里面重写tostring方法!
5.写一个类用于处理页面跳转
package com.lz.controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;/*** @author lz* @create 2023-09-07 16:21*/
@Controller
public class PageController {@RequestMapping("/page/{page}")public String toPage(@PathVariable("page")String page){return page;}@RequestMapping("/page/{dir}{page}")public String toDirPage(@PathVariable("dir")String dir,@PathVariable("page")String page ){return dir + "/" + page;}
}
二.正式启动SpringMVC的CRUD
1.建立接口,调用自动生成的接口
package com.lz.Biz;import com.lz.model.Book;
import com.lz.utlis.PageBean;import java.util.List;public interface BookBiz {int deleteByPrimaryKey(Integer bid);int insert(Book record);int insertSelective(Book record);Book selectByPrimaryKey(Integer bid);int updateByPrimaryKeySelective(Book record);int updateByPrimaryKey(Book record);List<Book>listPager (Book book, PageBean pageBean);
}
实现接口的方法,并且用@serverce注解被spring管理,@Autowries调用Book.xml
文件
package com.lz.Biz;import com.lz.mapper.BookMapper;
import com.lz.model.Book;
import com.lz.utlis.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;/*** @author lz* @create 2023-09-08 9:32**/
@Service
public class BookBizImpl implements BookBiz{@Autowiredprivate BookMapper bookMapper;@Overridepublic int deleteByPrimaryKey(Integer bid) {return bookMapper.deleteByPrimaryKey(bid) ;}@Overridepublic int insert(Book record) {return bookMapper.insert(record);}@Overridepublic int insertSelective(Book record) {return bookMapper.insertSelective(record);}@Overridepublic Book selectByPrimaryKey(Integer bid) {return bookMapper.selectByPrimaryKey(bid);}@Overridepublic int updateByPrimaryKeySelective(Book record) {return bookMapper.updateByPrimaryKey(record);}@Overridepublic int updateByPrimaryKey(Book record) {return bookMapper.updateByPrimaryKey(record);}@Overridepublic List<Book> listPager(Book book, PageBean pageBean) {return bookMapper.listPager(book);
}
2.构建分页代码
2.1书写BookMapper.xml中分页的方法
<select id="listPager" resultType="com.lz.model.Book" parameterType="com.lz.model.Book" >select<include refid="Base_Column_List" />from t_mvc_book<where><if test="bname !=null">and cname like concat ('%',#{bname},'%')</if></where></select>
2.2调用分页的方法
List<Book> listPager(Book book);
2.3导入一个工具类用于分页实现
package com.lz.tag;import com.lz.utlis.PageBean;import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;public class PageTag extends BodyTagSupport{private PageBean pageBean;// 包含了所有分页相关的元素public PageBean getPageBean() {return pageBean;}public void setPageBean(PageBean pageBean) {this.pageBean = pageBean;}@Overridepublic int doStartTag() throws JspException {
// 没有标签体,要输出内容JspWriter out = pageContext.getOut();try {out.print(toHTML());} catch (IOException e) {e.printStackTrace();}return super.doStartTag();}private String toHTML() {StringBuffer sb = new StringBuffer();
// 隐藏的form表单---这个就是上一次请求下次重新发的奥义所在
// 上一次请求的URLsb.append("<form action='"+pageBean.getUrl()+"' id='pageBeanForm' method='post'>");sb.append(" <input type='hidden' name='page'>");
// 上一次请求的参数Map<String, String[]> paramMap = pageBean.getMap();if(paramMap != null && paramMap.size() > 0) {Set<Entry<String, String[]>> entrySet = paramMap.entrySet();for (Entry<String, String[]> entry : entrySet) {
// 参数名String key = entry.getKey();
// 参数值for (String value : entry.getValue()) {
// 上一次请求的参数,再一次组装成了新的Form表单
// 注意:page参数每次都会提交,我们需要避免if(!"page".equals(key)) {sb.append(" <input type='hidden' name='"+key+"' value='"+value+"' >");}}}}sb.append("</form>");// 分页条sb.append("<ul class='pagination justify-content-center'>");sb.append(" <li class='page-item "+(pageBean.getPage() == 1 ? "disabled" : "")+"'><a class='page-link'");sb.append(" href='javascript:gotoPage(1)'>首页</a></li>");sb.append(" <li class='page-item "+(pageBean.getPage() == 1 ? "disabled" : "")+"'><a class='page-link'");sb.append(" href='javascript:gotoPage("+pageBean.getPreivousPage()+")'><</a></li>");// less than 小于号
// sb.append(" <li class='page-item'><a class='page-link' href='#'>1</a></li>");
// sb.append(" <li class='page-item'><a class='page-link' href='#'>2</a></li>");sb.append(" <li class='page-item active'><a class='page-link' href='#'>"+pageBean.getPage()+"</a></li>");sb.append(" <li class='page-item "+(pageBean.getPage() == pageBean.getMaxPage() ? "disabled" : "")+"'><a class='page-link' href='javascript:gotoPage("+pageBean.getNextPage()+")'>></a></li>");sb.append(" <li class='page-item "+(pageBean.getPage() == pageBean.getMaxPage() ? "disabled" : "")+"'><a class='page-link' href='javascript:gotoPage("+pageBean.getMaxPage() +")'>尾页</a></li>");sb.append(" <li class='page-item go-input'><b>到第</b><input class='page-link'");sb.append(" type='text' id='skipPage' name='' /><b>页</b></li>");sb.append(" <li class='page-item go'><a class='page-link'");sb.append(" href='javascript:skipPage()'>确定</a></li>");sb.append(" <li class='page-item'><b>共"+pageBean.getTotal()+"条</b></li>");sb.append("</ul>");// 分页执行的JS代码sb.append("<script type='text/javascript'>");sb.append(" function gotoPage(page) {");sb.append(" document.getElementById('pageBeanForm').page.value = page;");sb.append(" document.getElementById('pageBeanForm').submit();");sb.append(" }");sb.append(" function skipPage() {");sb.append(" var page = document.getElementById('skipPage').value;");sb.append(" if (!page || isNaN(page) || parseInt(page) < 1 || parseInt(page) > "+pageBean.getMaxPage()+") {");sb.append(" alert('请输入1~"+pageBean.getMaxPage()+"的数字');");sb.append(" return;");sb.append(" }");sb.append(" gotoPage(page);");sb.append(" }");sb.append("</script>");return sb.toString();}
}
2.4导入一个tid文件用于分页实现
<?xml version="1.0" encoding="UTF-8" ?><taglib xmlns="http://java.sun.com/xml/ns/j2ee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"version="2.0"><description>zking 1.1 core library</description><display-name>zking core</display-name><tlib-version>1.1</tlib-version><short-name>zking</short-name><uri>http://jsp.veryedu.cn</uri><tag><name>page</name><tag-class>com.lz.tag.PageTag</tag-class><body-content>JSP</body-content><attribute><name>pageBean</name><required>true</required><rtexprvalue>true</rtexprvalue></attribute></tag></taglib>
3.实现后端功能
3.1构建功能实现代码
package com.lz.controller;import com.lz.Biz.BookBiz;
import com.lz.model.Book;
import com.lz.utlis.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;import javax.servlet.http.HttpServletRequest;
import java.util.List;/*** @author lz* @create 2023-09-08 16:20*/
@Controller
@RequestMapping("/book")
public class BookController {@Autowiredprivate BookBiz bookBiz;//增加@RequestMapping("/add")public String add(Book book){int i = bookBiz.insertSelective(book);return "redirect:list";}//删除@RequestMapping("/del/{bid}")public String del(@PathVariable("bid")Integer bid){int i = bookBiz.deleteByPrimaryKey(bid);return "redirect:/book/list";}//修改@RequestMapping("/edit")public String edit(Book book){int i = bookBiz.updateByPrimaryKeySelective(book);return "redirect:list";}// 查询@RequestMapping("/list")//Book接收前台传递的参数public String list(Book book , HttpServletRequest request){PageBean pageBean=new PageBean();pageBean.setRequest(request);List<Book> books = bookBiz.listPager(book, pageBean);request.setAttribute("lst",books);request.setAttribute("pageBean",pageBean);return "book/list";}//数据回显@RequestMapping("/preSave")public String preSave(Book book, Model model){if (book!=null && book.getBid()!=null && book.getBid()!=0) {Book b = bookBiz.selectByPrimaryKey(book.getBid());model.addAttribute("b",b);}return "book/edit";}}
3.2在BookMapper.xml文件编写查询的方法(并且实现)
<select id="listPager" resultType="com.lz.model.Book" parameterType="com.lz.model.Book" >select<include refid="Base_Column_List" />from t_mvc_book<where><if test="bname !=null">bname like concat ('%',#{bname},'%')</if></where></select>
3.3构建list界面(展示数据)
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<%@ taglib uri="http://jsp.veryedu.cn" prefix="z"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><linkhref="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css"rel="stylesheet"><scriptsrc="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js"></script><title>博客列表</title><style type="text/css">.page-item input {padding: 0;width: 40px;height: 100%;text-align: center;margin: 0 6px;}.page-item input, .page-item b {line-height: 38px;float: left;font-weight: 400;}.page-item.go-input {margin: 0 10px;}</style>
</head>
<body>
<form class="form-inline"action="${pageContext.request.contextPath }/book/list" method="post"><div class="form-group mb-2"><input type="text" class="form-control-plaintext" name="bname"placeholder="请输入书籍名称"><!-- <input name="rows" value="20" type="hidden"> --><!-- 不想分页 --><%-- <input name="pagination" value="false" type="hidden">--%></div><button type="submit" class="btn btn-primary mb-2">查询</button><a class="btn btn-primary mb-2" href="${pageContext.request.contextPath }/book/preSave">新增</a>
</form><table class="table table-striped"><thead><tr><th scope="col">书籍编号</th><th scope="col">书籍名字</th><th scope="col">书籍价格</th><th scope="col">操作</th></tr></thead><tbody><c:forEach var="b" items="${lst }"><tr><td>${b.bid }</td><td>${b.bname }</td><td>${b.price }</td><td><a href="${pageContext.request.contextPath }/book/preSave?bid=${b.bid}">修改</a><a href="${pageContext.request.contextPath }/book/del/${b.bid}">删除</a></td></tr></c:forEach></tbody>
</table>
<!-- 这一行代码就相当于前面分页需求前端的几十行了 -->
<z:page pageBean="${pageBean }"></z:page>
</body>
</html>
3.4构建edit界面
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>书籍编辑界面</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/${empty b ? 'book/add' : 'book/edit'}" method="post">书籍编号:<input type="text" name="bid" value="${b.bid }"><br>书籍名字:<input type="text" name="bname" value="${b.bname }"><br>书籍价格:<input type="text" name="price" value="${b.price }"><br><input type="submit">
</form>
</body>
</html>