目录
前言
一、前期准备
1.pom.xml---依赖与插件的导入
2.jdbc.properties---数据库连接
3.log4j2.xml---日志文件
4.spring-mybatis---mybatis与spring整合文件
5.spring-context---spring上下文配置
6.spring-mvc
7.generatorConfig.xml---代码生成器
8.web.xml
二、增删改查的实现
1.model与mapper层的生成
2.biz层与切面
3.工具类
4.controller层
三、测试结果
总结
【参考资料】
Spring MVC是一种基于Java的Web框架,它提供了一种简单而强大的方式来构建Web应用程序。在本文中,我们将详细讲解如何使用Spring MVC来实现增删改查功能。我们将从基本概念开始,逐步介绍每个步骤,并提供示例代码来帮助您更好地理解和应用这些概念。
先创建一个maven工程
将相关依赖于插件进行添加,并将
4.0.0
com.ctb
ctbssm
1.0-SNAPSHOT
war
ctbssm 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}
ctbssm
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
数据库驱动---数据库连接路径---数据库登录用户名---数据库登录密码
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis_ssm?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123456
用于记录日志
/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
扫描包、数据源、sqlsessionfactory、mapper扫描、事务管理所、开启自动代理
helperDialect=mysql
扫描包、视图解析器、静态资源处理、开启自动代理
主要生成model/mapper接口/mapper.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
/
package com.ctb.model;
import lombok.ToString;
@ToString
public class Book {
private Integer bid;
private String bname;
private Float price;
public Book(Integer bid, String bname, Float price) {
this.bid = bid;
this.bname = bname;
this.price = price;
}
public Book() {
super();
}
public Integer getBid() {
return bid;
}
public void setBid(Integer bid) {
this.bid = bid;
}
public String getBname() {
return bname;
}
public void setBname(String bname) {
this.bname = bname;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
}
BookMapper.java
package com.ctb.mapper;
import com.ctb.model.Book;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface BookMapper {
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 selectPager(Book book);
}
BookMapper.xml
bid, bname, price
delete from t_mvc_book
where bid = #{bid,jdbcType=INTEGER}
insert into t_mvc_book (bid, bname, price
)
values (#{bid,jdbcType=INTEGER}, #{bname,jdbcType=VARCHAR}, #{price,jdbcType=REAL}
)
insert into t_mvc_book
bid,
bname,
price,
#{bid,jdbcType=INTEGER},
#{bname,jdbcType=VARCHAR},
#{price,jdbcType=REAL},
update t_mvc_book
bname = #{bname,jdbcType=VARCHAR},
price = #{price,jdbcType=REAL},
where bid = #{bid,jdbcType=INTEGER}
update t_mvc_book
set bname = #{bname,jdbcType=VARCHAR},
price = #{price,jdbcType=REAL}
where bid = #{bid,jdbcType=INTEGER}
PagerAspect
package com.ctb.aspect;
import com.ctb.utils.PageBean;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
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;
/**
*
* * *..*Service.*Pager(..)
* * :任意返回值类型
* *..:任意包,不限层级 com.ctb com.biao.ctb
* *Service:以Service结尾的类/接口
* *Pager:以Pager结尾的方法
* ..:任意参数
* 符合上述条件,即为目标类或者目标方法
*
*/
@Aspect //代表当前类为切面类
@Component // 代表当前类交给spring进行管理
public class PagerAspect {
@Around("execution(* *..*Biz.*Pager(..))")
public Object invoke(ProceedingJoinPoint args) throws Throwable {
PageBean pageBean = null;
// 获取目标方法中的所有参数
Object[] ags = args.getArgs();
for (Object param : ags) {
if(param instanceof PageBean){
pageBean = (PageBean) param;
break;
}
}
if(pageBean != null && pageBean.isPagination())
PageHelper.startPage(pageBean.getPage(),pageBean.getRows());
执行目标方法
Object lst = args.proceed();
if(pageBean != null && pageBean.isPagination()){
PageInfo info = new PageInfo((List) lst);
pageBean.setTotal((int)info.getTotal());
}
return lst;
}
}
BookBizImpl
package com.ctb.biz.impl;
import com.ctb.biz.BookBiz;
import com.ctb.mapper.BookMapper;
import com.ctb.model.Book;
import com.ctb.utils.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author 彪
* @remark
* @create 2023-09-07 16:55
*/
@Service
public class BookBizImpl implements BookBiz {
@Autowired
private BookMapper bookMapper;
@Override
public int deleteByPrimaryKey(Integer bid) {
return bookMapper.deleteByPrimaryKey(bid);
}
@Override
public int insert(Book record) {
return bookMapper.insert(record);
}
@Override
public int insertSelective(Book record) {
return bookMapper.insertSelective(record);
}
@Override
public Book selectByPrimaryKey(Integer bid) {
return bookMapper.selectByPrimaryKey(bid);
}
@Override
public int updateByPrimaryKeySelective(Book record) {
return bookMapper.updateByPrimaryKeySelective(record);
}
@Override
public int updateByPrimaryKey(Book record) {
return bookMapper.updateByPrimaryKey(record);
}
@Override
public List listPager(Book book, PageBean pageBean) {
return bookMapper.selectPager(book);
}
}
pagebean---分页
package com.ctb.utils;
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
+ "]";
}
}
pagetag---自定义分页标签
package com.ctb.tag;
import com.ctb.utils.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;
}
@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();
}
}
ctb.tld---自定义标签配置
ctb 1.1 core library
ctb core
1.1
ctb
http://jsp.veryedu.cn
page
com.ctb.tag.PageTag
JSP
pageBean
true
true
responseutil---返回结果显示
package com.ctb.utils;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
public class ResponseUtil {
public static void write(HttpServletResponse response,Object o)throws Exception{
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
out.println(o.toString());
out.flush();
out.close();
}
public static void writeJson(HttpServletResponse response,Object o)throws Exception{
ObjectMapper om = new ObjectMapper();
// om.writeValueAsString(o)代表了json串
write(response, om.writeValueAsString(o));
}
}
package com.ctb.controller;
import com.ctb.biz.BookBiz;
import com.ctb.model.Book;
import com.ctb.utils.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;
@Controller
@RequestMapping("/book")
public class BookController {
@Autowired
private 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){
bookBiz.deleteByPrimaryKey(bid);
return "redirect:/book/list";
}
// 改
@RequestMapping("/edit")
public String edit(Book Book){
bookBiz.updateByPrimaryKeySelective(Book);
return "redirect:list";
}
// 查
@RequestMapping("/list")
public String list(Book Book, HttpServletRequest request){
PageBean pageBean = new PageBean();
pageBean.setRequest(request);
List Books = bookBiz.listPager(Book, pageBean);
request.setAttribute("lst",Books);
request.setAttribute("pageBean",pageBean);
return "book/list";
}
// 查询单个
@RequestMapping("/detail")
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";
}
}
1.查
2.模糊查询
3.删
4.改
5.增
在本文中,我们详细讲解了如何使用Spring MVC来实现增删改查功能。我们从基本概念开始,逐步介绍了每个步骤,并提供了示例代码来帮助您更好地理解和应用这些概念。希望本文对您有所帮助,谢谢阅读!