目录
一.前言
二.crud---配置文件
2.1 pom.xml文件
2.2 web.xml文件
2.3 spring-context.xml
2.4 spring-mvc.xml
2.5 spring-MyBatis.xml
2.6 jdbc.properties数据库配置文件
2.7 generatorConfig.xml
2.8 日志文件log4j
三.后台
3.1 pageBean.java
3.2 pageTag
3.3 切面类
3.4 biz层
3.5 web层
四.前端
4.1 list.jsp
4.2 edit.jsp
今天的分享就到这啦!!!
今天给大家分享,每个框架都需要学习的增删改查,在我们后端上班敲代码期间似乎60%的时间都是在写增删改查,所以这是我们作为程序员或却不可的技能,接下来,我们一起来学习吧!!!
用到的工具是Idea,我们创建好项目之后,就需要来配置相应的文件。
可以看到注释知道pom.xml文件中导入了哪一些文件工具
4.0.0
com.zking
yzssm
1.0-SNAPSHOT
war
yzssm Maven Webapp
http://www.example.com
UTF-8
1.8
1.8
3.7.0
5.0.2.RELEASE
3.4.5
5.1.44
5.1.2
1.3.1
2.1.1
2.4.3
2.9.1
3.2.0
1.7.13
4.12
4.0.0
1.18.2
1.1.0
2.10.0
2.9.0
1.7.1.RELEASE
2.9.3
1.2
1.1.2
8.0.47
1.3.3
5.0.2.Final
1.3.2
org.springframework
spring-core
${spring.version}
org.springframework
spring-beans
${spring.version}
org.springframework
spring-context
${spring.version}
org.springframework
spring-orm
${spring.version}
org.springframework
spring-tx
${spring.version}
org.springframework
spring-aspects
${spring.version}
org.springframework
spring-web
${spring.version}
org.springframework
spring-test
${spring.version}
org.mybatis
mybatis
${mybatis.version}
mysql
mysql-connector-java
${mysql.version}
com.github.pagehelper
pagehelper
${pagehelper.version}
org.mybatis
mybatis-spring
${mybatis.spring.version}
org.springframework
spring-context-support
${spring.version}
org.mybatis.caches
mybatis-ehcache
${mybatis.ehcache.version}
net.sf.ehcache
ehcache
${ehcache.version}
redis.clients
jedis
${redis.version}
org.springframework.data
spring-data-redis
${redis.spring.version}
com.fasterxml.jackson.core
jackson-databind
${jackson.version}
com.fasterxml.jackson.core
jackson-core
${jackson.version}
com.fasterxml.jackson.core
jackson-annotations
${jackson.version}
org.apache.commons
commons-dbcp2
${commons.dbcp2.version}
commons-pool2
org.apache.commons
org.apache.commons
commons-pool2
${commons.pool2.version}
org.springframework
spring-webmvc
${spring.version}
org.slf4j
slf4j-api
${slf4j.version}
org.slf4j
jcl-over-slf4j
${slf4j.version}
runtime
org.apache.logging.log4j
log4j-api
${log4j2.version}
org.apache.logging.log4j
log4j-core
${log4j2.version}
org.apache.logging.log4j
log4j-slf4j-impl
${log4j2.version}
org.apache.logging.log4j
log4j-web
${log4j2.version}
runtime
com.lmax
disruptor
${log4j2.disruptor.version}
junit
junit
${junit.version}
javax.servlet
javax.servlet-api
${servlet.version}
provided
org.projectlombok
lombok
${lombok.version}
provided
jstl
jstl
${jstl.version}
taglibs
standard
${standard.version}
org.apache.tomcat
tomcat-jsp-api
${tomcat-jsp-api.version}
commons-fileupload
commons-fileupload
${commons-fileupload.version}
org.hibernate
hibernate-validator
${hibernate-validator.version}
org.apache.shiro
shiro-core
${shiro.version}
org.apache.shiro
shiro-web
${shiro.version}
org.apache.shiro
shiro-spring
${shiro.version}
yzssm
src/main/java
**/*.xml
src/main/resources
jdbc.properties
*.xml
org.apache.maven.plugins
maven-compiler-plugin
${maven.compiler.plugin.version}
${maven.compiler.target}
${project.build.sourceEncoding}
org.mybatis.generator
mybatis-generator-maven-plugin
1.3.2
mysql
mysql-connector-java
${mysql.version}
true
maven-clean-plugin
3.1.0
maven-resources-plugin
3.0.2
maven-compiler-plugin
3.8.0
maven-surefire-plugin
2.22.1
maven-war-plugin
3.2.2
maven-install-plugin
2.5.2
maven-deploy-plugin
2.8.2
在这里我们需要建立两个资源包,一个是spring-context.xml,一个是spring-mvc.xml
Archetype Created Web Application
contextConfigLocation
classpath:spring-context.xml
org.springframework.web.context.ContextLoaderListener
encodingFilter
org.springframework.web.filter.CharacterEncodingFilter
true
encoding
UTF-8
encodingFilter
/*
SpringMVC
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring-mvc.xml
1
true
SpringMVC
/
视图解析
spring与MyBatis的整合
helperDialect=mysql
连接数据库
/root/workspace/lucenedemo/logs
/root/workspace/lucenedemo/logs/error
/root/workspace/lucenedemo/logs/warn
%d{yyyy-MM-dd HH:mm:ss.SSS} [%t-%L] %-5level %logger{36} - %msg%n
我们先写好需要的工具类
等下需要分页,所有单独写了两个类,来写分页的属性及方法
上一页,下一页,最大页,最小页,及判空
package com.yinzi.util;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Map;
public class PageBean implements Serializable {
private static final long serialVersionUID = 2422581023658455731L;
//页码
private int page=1;
//每页显示记录数
private int rows=10;
//总记录数
private int total=0;
//是否分页
private boolean isPagination=true;
//上一次的请求路径
private String url;
//获取所有的请求参数
private Map map;
public PageBean() {
super();
}
//设置请求参数
public void setRequest(HttpServletRequest req) {
String page=req.getParameter("page");
String rows=req.getParameter("rows");
String pagination=req.getParameter("pagination");
this.setPage(page);
this.setRows(rows);
this.setPagination(pagination);
this.url=req.getContextPath()+req.getServletPath();
this.map=req.getParameterMap();
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Map getMap() {
return map;
}
public void setMap(Map map) {
this.map = map;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public void setPage(String page) {
if(null!=page&&!"".equals(page.trim()))
this.page = Integer.parseInt(page);
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
public void setRows(String rows) {
if(null!=rows&&!"".equals(rows.trim()))
this.rows = Integer.parseInt(rows);
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public void setTotal(String total) {
this.total = Integer.parseInt(total);
}
public boolean isPagination() {
return isPagination;
}
public void setPagination(boolean isPagination) {
this.isPagination = isPagination;
}
public void setPagination(String isPagination) {
if(null!=isPagination&&!"".equals(isPagination.trim()))
this.isPagination = Boolean.parseBoolean(isPagination);
}
/**
* 获取分页起始标记位置
* @return
*/
public int getStartIndex() {
//(当前页码-1)*显示记录数
return (this.getPage()-1)*this.rows;
}
/**
* 末页
* @return
*/
public int getMaxPage() {
int totalpage=this.total/this.rows;
if(this.total%this.rows!=0)
totalpage++;
return totalpage;
}
/**
* 下一页
* @return
*/
public int getNextPage() {
int nextPage=this.page+1;
if(this.page>=this.getMaxPage())
nextPage=this.getMaxPage();
return nextPage;
}
/**
* 上一页
* @return
*/
public int getPreivousPage() {
int previousPage=this.page-1;
if(previousPage<1)
previousPage=1;
return previousPage;
}
@Override
public String toString() {
return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", isPagination=" + isPagination
+ "]";
}
}
首页,尾页
package com.yinzi.tag;
import com.yinzi.util.PageBean;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;
public class PageTag extends BodyTagSupport{
private PageBean pageBean;// 包含了所有分页相关的元素
public PageBean getPageBean() {
return pageBean;
}
public void setPageBean(PageBean pageBean) {
this.pageBean = pageBean;
}
@Override
public 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表单---这个就是上一次请求下次重新发的奥义所在
// 上一次请求的URL
sb.append("");
// 分页条
sb.append("");
// 分页执行的JS代码
sb.append("");
return sb.toString();
}
}
运用了环绕通知,日志管理,进行筛选及判断分页是否为空
package com.yinzi.aspect;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yinzi.util.PageBean;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @author yinzi
* @create 2023-08-25 17:05
*/
@Aspect //代表为切面类
@Component //代表该类交给spring管理
public class PageAspect {
@Around("execution(* *..*Biz.*List(..))") //环绕通知
//* *..*Service.*Pager(..))
//第一个* 代表了任意返回值
//*.. 代表了任意包,不限层级
//*Service 代表了以Service结尾的类/接口
//*Pager 代表了以pager结尾的方法
//.. 括号的点点 代表了任意参数
//符合以上则为目标类或者目标方法
public Object invoke(ProceedingJoinPoint args) throws Throwable {
PageBean pageBean=null;
//获取目标方法的所有参数
Object[] args1 = args.getArgs();
for (Object parm:args1){
//如果有参数是pageBean 那么就强转
if(parm instanceof PageBean){
pageBean = (PageBean) parm;
break;
}
}
//判空分页
if(pageBean!=null && pageBean.isPagination())
PageHelper.startPage(pageBean.getPage(),pageBean.getRows());
//执行目标方法
Object proceed = args.proceed();
if(pageBean!=null && pageBean.isPagination()){
PageInfo info = new PageInfo((List) proceed);
pageBean.setTotal((int) info.getTotal());
}
return proceed;
}
}
上面的分页工具类写完之后,就可以正式的开始写后台代码了,增删改查应该还有模糊查询,所以我们要自己写一个模糊查询的方法
定义一个接口
然后写一个类实现接口
package com.yinzi.Biz;
import com.yinzi.mapper.BookMapper;
import com.yinzi.model.Book;
import com.yinzi.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author yinzi
* @create 2023-09-07 14:32
*/
@Service
//将类交给spring处理
public class BookBizImpl implements BookBiz {
@Autowired //相当于set,get方法
private BookMapper bm;
@Override
public int deleteByPrimaryKey(Integer bid) {
return bm.deleteByPrimaryKey(bid);
}
@Override
public int insert(Book record) {
return bm.insert(record);
}
@Override
public int insertSelective(Book record) {
return bm.insertSelective(record);
}
@Override
public Book selectByPrimaryKey(Integer bid) {
return bm.selectByPrimaryKey(bid);
}
@Override
public int updateByPrimaryKeySelective(Book record) {
return bm.updateByPrimaryKeySelective(record);
}
@Override
public int updateByPrimaryKey(Book record) {
return bm.updateByPrimaryKey(record);
}
@Override
public List selectList(Book book, PageBean pageBean) {
return bm.selectList(book,pageBean);
}
}
调用增删改查的方法,跳转页面
package com.yinzi.web;
import com.yinzi.Biz.BookBiz;
import com.yinzi.model.Book;
import com.yinzi.util.PageBean;
import lombok.extern.slf4j.Slf4j;
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 yinzi
* @create 2023-09-07 14:38
*/
@Slf4j
@Controller //代替之前的自定义mvc的ActionSupport
@RequestMapping("/book")
public class BookController {
@Autowired //代表set,get的方法
private BookBiz bookBiz;
@RequestMapping("/list")
public String list(Book book, HttpServletRequest request){
//分页
PageBean pageBean=new PageBean();
pageBean.setRequest(request);
//调用查询方法
List books = bookBiz.selectList(book, pageBean);
request.setAttribute("list",books);
request.setAttribute("pageBean",pageBean);
return "list";
}
//增加
@RequestMapping("/add")
public String add(Book book){
//调用新增的方法
int i = bookBiz.insertSelective(book);
return "redirect:list";
}
//删
@RequestMapping("/del")
public String del(Book book){
//调用删除的方法
int i = bookBiz.deleteByPrimaryKey(book.getBid());
return "redirect:list";
}
//改Book
@RequestMapping("/update")
public String update(Book book){
//调用修改的方法
int i = bookBiz.updateByPrimaryKeySelective(book);
return "redirect:list";
}
//修改回显数据
@RequestMapping("/edit")
public String edit(Book book, Model model) {
//判断ID是否为空
if (book != null && book.getBid() != null && book.getBid() != 0) {
//不为空时,调用查询单个的方法
Book book1 = bookBiz.selectByPrimaryKey(book.getBid());
model.addAttribute("c",book1);
}
return "edit";
}
}
<%@ 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"%>
书籍列表
书籍ID
书籍名称
书籍价格
操作
${b.bid }
${b.bname }
${b.price }
修改
删除
${pageBean }
<%--
Created by IntelliJ IDEA.
User: 86131
Date: 2023/9/7
Time: 16:29
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title