目录
一、前期准备
1.1 编写页面跳转控制类
二、实现CRUD
2.1 相关依赖
2.2 配置文件
2.3 逆向生成
2.4 后台代码完善
2.4.1 编写切面类
2.4.2 编写工具类
2.4.3 编写biz层
2.4.4 配置mapper.xml
2.4.5 编写相应接口类(MusicMapper)
2.4.6 处理controller层发送到biz的请求(配置spring-mvc.xml)
2.4.7 编写tag助手标签类
2.4.8 引入tld标签库
2.4.9 编写controller类
2.5 前台代码
2.5.1 主页面编写
2.5.2 修改界面编写
三、展示效果
四、实战SpringMVC增删改查的收获
通过@PathVariable方式实现公共页面跳转。代码如下:
package com.Kissship.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author Kissship
* @site www.Kissship.com
* @company xxx公司
* @create 2023-09-07-15:01
*
* 用来处理页面跳转
*/
@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;
}
}
pom.xml:
4.0.0
org.example
kissshipssm
1.0-SNAPSHOT
war
kissshipssm 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}
test
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}
org.example
Spring-mybatis
1.0-SNAPSHOT
compile
kissshipssm
src/main/java
**/*.xml
src/main/resources
*.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
web.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
/
生成后的对应目标目录如下:
在生成后的HBookMapper接口中,需要加上@Repository给Spring进行托管。
PagerAspect:
package com.Kissship.aspect;
import com.Kissship.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;
@Aspect
@Component
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 pageInfo = new PageInfo((List) lst);
pageBean.setTotal((int) pageInfo.getTotal());
}
return lst;
}
}
PageBean:
package com.Kissship.utils;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Map;
/**
* @author Kissship
* @site www.Kissship.com
* @company xxx公司
* @create 2023-08-15-15:42
*/
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.Kissship.biz;
import com.Kissship.model.Music;
import com.Kissship.utils.PageBean;
import java.util.List;
public interface MusicBiz {
int deleteByPrimaryKey(Integer mid);
int insert(Music record);
int insertSelective(Music record);
Music selectByPrimaryKey(Integer mid);
int updateByPrimaryKeySelective(Music record);
int updateByPrimaryKey(Music record);
List listPager(Music music, PageBean pageBean);
}
注:
这个方法为查询返回列表方法,包含分页,因为切面类对其进行切面,所以在命名时,必须以Pager结尾。
在自动生成的代码下添加以下:
List selectBycon(Music music);
代码如下:
PageTag:
package com.Kissship.tag;
import com.Kissship.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();
}
}
kissship.tld:
kissship 1.1 core library
kissship core
1.1
kissship
http://jsp.veryedu.cn
page
com.Kissship.tag.PageTag
JSP
pageBean
true
true
MusicController:
package com.Kissship.web;
import com.Kissship.biz.MusicBiz;
import com.Kissship.model.Music;
import com.Kissship.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;
/**
* @author Kissship
* @site www.Kissship.com
* @company xxx公司
* @create 2023-09-08-15:15
*/
@Controller
@RequestMapping("/mic")
public class MusicController {
@Autowired
private MusicBiz musicBiz;
// 增
@RequestMapping("/add")
public String add(Music music, HttpServletRequest Request) {
int i = musicBiz.insertSelective(music);
return "redirect:list";
}
// 删
@RequestMapping("/del/{bid}")
public String del(@PathVariable("bid")Integer bid) {
musicBiz.deleteByPrimaryKey(bid);
return "redirect:/mic/list";
}
// 改
@RequestMapping("/edit")
public String edit(Music music, HttpServletRequest Request) {
musicBiz.updateByPrimaryKeySelective(music);
return "redirect:list";
}
// 查
@RequestMapping("/list")
public String list(Music music, HttpServletRequest Request) {
//music是用来接受前台传递后台的参数
PageBean pageBean = new PageBean();
pageBean.setRequest(Request);
List music1 = musicBiz.listPager(music, pageBean);
Request.setAttribute("lst", music1);
Request.setAttribute("pageBean", pageBean);
//WEB-INF/jsp/mic/list.jsp
return "mic/list";
}
//数据回显
@RequestMapping("/preSave")
public String preSave(Music music, Model model) {
if (music != null && music.getMid() != null && music.getMid() != 0) {
Music m = musicBiz.selectByPrimaryKey(music.getMid());
model.addAttribute("c",m);
}
return "mic/edit";
}
}
到此我们的后台代码编写完成了,接下来就是前端代码的编写。
作用:展示数据进行一系列操作。
list.jsp:
<%@ 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"%>
JayChou歌单列表
歌曲编号
歌曲名称
歌曲专辑
歌曲歌词
歌曲图片
${b.mid }
${b.mname }
${b.mtype }
${b.minfo }
${b.mpic }
修改
删除
${pageBean }
作用:操作数据。
edit.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
编辑歌单界面
控制台效果:
主页增删改查展示效果:
熟悉SpringMVC框架:通过实践,可以更深入地理解SpringMVC框架的工作原理和核心概念,如控制器、视图解析器、数据绑定等。
掌握请求处理和数据交互:实践中的增删改查操作涉及到请求处理和数据库数据交互,可以加深对请求的处理方式和数据库操作的理解。
强化编程技能:实战中需要编写具体的代码实现增删改查功能,可以提高编程能力,尤其是对Java和SpringMVC的理解和熟练度。
学习最佳实践:通过实践,可以学习到SpringMVC增删改查的最佳实践,包括使用合适的设计模式、优化数据库查询性能、错误处理等方面的经验。
增加项目经验:实战增删改查可以让您在实际项目中积累经验,对项目的整体流程和开发周期有更深入的认识。
提升自信心:通过实际操作和实践,可以提高对SpringMVC增删改查功能的自信心,为日后更复杂的项目开发打下基础。
请注意,SpringMVC是一个开源框架,通过参与实战项目可以更好地理解和应用它。同时,实践中也会遇到挑战和问题,但通过解决问题和学习,可以不断进步和成长。
最后实战SpringMVC之CRUD就到这里,祝大家在敲代码的路上一路通畅!
感谢大家的观看 !