目录
一、CRUD(增删改查)
1、导入相关pom依赖
1.1Pom.xml
1.2.相关配置文件
1.3.web.xml相关配置
1.4.逆向生成
2.代码开发
TomCat配置
界面代码
查询-主界面页面绑值
增加
修改
删除
二、文件上传
思路:
配置文件上传
pom依赖(非必须)
Springmvc.xml配置 文件上传多功能解析器
后台代码
ClazzDto
前台
在IDEA中完成图片请求地址与硬盘中地址的映射关系
三、文件下载
思路:
前端代码
后端代码
运行
新建一个Maven项目
显示BUILD SUCCESS就代表建立成功了
一步一步导入
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
4.12
4.0.0
1.18.2
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.apache.commons
commons-dbcp2
${commons.dbcp2.version}
org.apache.commons
commons-pool2
${commons.pool2.version}
org.apache.logging.log4j
log4j-core
${log4j2.version}
org.apache.logging.log4j
log4j-api
${log4j2.version}
org.apache.logging.log4j
log4j-web
${log4j2.version}
junit
junit
${junit.version}
test
javax.servlet
javax.servlet-api
${servlet.version}
provided
org.projectlombok
lombok
${lombok.version}
provided
org.springframework
spring-webmvc
${spring.version}
javax.servlet.jsp
javax.servlet.jsp-api
2.3.3
jstl
jstl
1.2
taglibs
standard
1.1.2
resources
src/main/java
**/*.xml
src/main/resources
jdbc.properties
*.xml
plugin
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
applicationContext.xml
applicationContext-mybatis.xml
helperDialect=mysql
generatorConfig.xml
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_2022_08?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123
log4j2.xml
/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
springmvc-servlet.xml
web.xml
Archetype Created Web Application
contextConfigLocation
classpath:applicationContext.xml
org.springframework.web.context.ContextLoaderListener
SpringMVC
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
/WEB-INF/springmvc-servlet.xml
1
true
SpringMVC
/
encodingFilter
org.springframework.web.filter.CharacterEncodingFilter
true
encoding
UTF-8
encodingFilter
/*
将t_struts_class表逆向生成出Model、Mapper.xml、Mapper.java
工具类
StringUtils
package com.oyang.ssm.util;
public class StringUtils {
// 私有的构造方法,保护此类不能在外部实例化
private StringUtils() {
}
/**
* 如果字符串等于null或去空格后等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isBlank(String s) {
boolean b = false;
if (null == s || s.trim().equals("")) {
b = true;
}
return b;
}
/**
* 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isNotBlank(String s) {
return !isBlank(s);
}
}
分页工具类
PageBean
package com.oyang.ssm.util;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
/**
* 分页工具类
*
*/
public class PageBean {
private int page = 1;// 页码
private int rows = 10;// 页大小
private int total = 0;// 总记录数
private boolean pagination = true;// 是否分页
private String url; //保存上一次请求的URL
private Map paramMap = new HashMap<>();// 保存上一次请求的参数
/**
* 初始化pagebean的,保存上一次请求的重要参数
* @param req
*/
public void setRequest(HttpServletRequest req) {
// 1.1 需要保存上一次请求的URL
this.setUrl(req.getRequestURL().toString());
// 1.2 需要保存上一次请求的参数 bname、price
this.setParamMap(req.getParameterMap());
// 1.3 需要保存上一次请求的分页设置 pagination
this.setPagination(req.getParameter("pagination"));
// 1.4 需要保存上一次请求的展示条目数
this.setRows(req.getParameter("rows"));
// 1.5 初始化请求的页码 page
this.setPage(req.getParameter("page"));
}
public void setPage(String page) {
if(StringUtils.isNotBlank(page))
this.setPage(Integer.valueOf(page));
}
public void setRows(String rows) {
if(StringUtils.isNotBlank(rows))
this.setRows(Integer.valueOf(rows));
}
public void setPagination(String pagination) {
// 只有在前台jsp填写了pagination=false,才代表不分页
if(StringUtils.isNotBlank(pagination))
this.setPagination(!"false".equals(pagination));
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Map getParamMap() {
return paramMap;
}
public void setParamMap(Map paramMap) {
this.paramMap = paramMap;
}
public PageBean() {
super();
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = 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 pagination;
}
public void setPagination(boolean pagination) {
this.pagination = pagination;
}
/**
* 获得起始记录的下标
*
* @return
*/
public int getStartIndex() {
return (this.page - 1) * this.rows;
}
/**
* 最大页
* @return
*/
public int maxPage() {
// total % rows == 0 ? total / rows : total / rows +1
return this.total % this.rows == 0 ? this.total / this.rows : this.total / this.rows + 1;
}
/**
* 下一页
* @return
*/
public int nextPage() {
// 如果当前页小于最大页,那就下一页为当前页+1;如果不小于,说明当前页就是最大页,那就无需+1
return this.page < this.maxPage() ? this.page + 1 : this.page;
}
/**
* 上一页
* @return
*/
public int previousPage() {
return this.page > 1 ? this.page - 1 : this.page;
}
@Override
public String toString() {
return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
}
}
PageTag
package com.oyang.ssm.tag;
import com.oyang.ssm.util.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();
}
}
ClazzMapper.xml
cid, cname, cteacher, pic
delete from t_struts_class
where cid = #{cid,jdbcType=INTEGER}
insert into t_struts_class (cid, cname, cteacher,
pic)
values (#{cid,jdbcType=INTEGER}, #{cname,jdbcType=VARCHAR}, #{cteacher,jdbcType=VARCHAR},
#{pic,jdbcType=VARCHAR})
insert into t_struts_class
cid,
cname,
cteacher,
pic,
#{cid,jdbcType=INTEGER},
#{cname,jdbcType=VARCHAR},
#{cteacher,jdbcType=VARCHAR},
#{pic,jdbcType=VARCHAR},
update t_struts_class
cname = #{cname,jdbcType=VARCHAR},
cteacher = #{cteacher,jdbcType=VARCHAR},
pic = #{pic,jdbcType=VARCHAR},
where cid = #{cid,jdbcType=INTEGER}
update t_struts_class
set cname = #{cname,jdbcType=VARCHAR},
cteacher = #{cteacher,jdbcType=VARCHAR},
pic = #{pic,jdbcType=VARCHAR}
where cid = #{cid,jdbcType=INTEGER}
ClazzMapper
package com.oyang.ssm.mapper;
import com.oyang.ssm.model.Clazz;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface ClazzMapper {
int deleteByPrimaryKey(Integer cid);
int insert(Clazz record);
int insertSelective(Clazz record);
Clazz selectByPrimaryKey(Integer cid);
int updateByPrimaryKeySelective(Clazz record);
int updateByPrimaryKey(Clazz record);
List listPager(Clazz clazz);
}
Clazz
package com.oyang.ssm.model;
public class Clazz {
private Integer cid;
private String cname;
private String cteacher;
private String pic;
public Clazz(Integer cid, String cname, String cteacher, String pic) {
this.cid = cid;
this.cname = cname;
this.cteacher = cteacher;
this.pic = pic;
}
public Clazz() {
super();
}
public Integer getCid() {
return cid;
}
public void setCid(Integer cid) {
this.cid = cid;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getCteacher() {
return cteacher;
}
public void setCteacher(String cteacher) {
this.cteacher = cteacher;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
}
ClazzBiz
package com.oyang.ssm.biz;
import com.oyang.ssm.model.Clazz;
import com.oyang.ssm.util.PageBean;
import java.util.List;
public interface ClazzBiz {
int deleteByPrimaryKey(Integer cid);
int insert(Clazz record);
int insertSelective(Clazz record);
Clazz selectByPrimaryKey(Integer cid);
int updateByPrimaryKeySelective(Clazz record);
int updateByPrimaryKey(Clazz record);
List listPager(Clazz clazz, PageBean pageBean);
}
ClazzBizImpl
package com.oyang.ssm.impl;
import com.oyang.ssm.biz.ClazzBiz;
import com.oyang.ssm.mapper.ClazzMapper;
import com.oyang.ssm.model.Clazz;
import com.oyang.ssm.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author oyang
* @site https://blog.csdn.net
* @qq 1828190940
* @create 2022-08-17 20:59
*/
@Service
public class ClazzBizImpl implements ClazzBiz {
@Autowired
private ClazzMapper clazzMapper;
@Override
public int deleteByPrimaryKey(Integer cid) {
return clazzMapper.deleteByPrimaryKey(cid);
}
@Override
public int insert(Clazz record) {
return clazzMapper.insert(record);
}
@Override
public int insertSelective(Clazz record) {
return clazzMapper.insertSelective(record);
}
@Override
public Clazz selectByPrimaryKey(Integer cid) {
return clazzMapper.selectByPrimaryKey(cid);
}
@Override
public int updateByPrimaryKeySelective(Clazz record) {
return clazzMapper.updateByPrimaryKeySelective(record);
}
@Override
public int updateByPrimaryKey(Clazz record) {
return clazzMapper.updateByPrimaryKey(record);
}
@Override
public List listPager(Clazz clazz, PageBean pageBean) {
return clazzMapper.listPager(clazz);
}
}
clzList 主界面
<%@ 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.cid }
${b.cname }
${b.cteacher }
${b.pic }
修改
删除
增加 / 修改界面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
界面图
ClazzController
package com.oyang.ssm.controller;
import com.oyang.ssm.biz.ClazzBiz;
import com.oyang.ssm.model.Clazz;
import com.oyang.ssm.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* @author oyang
* @site https://blog.csdn.net
* @qq 1828190940
* @create 2022-08-17 21:17
*/
@Controller
@RequestMapping("/clz")
public class ClazzController {
@Autowired
private ClazzBiz clazzBiz;
// list->clzList
// toList->重定向->"redirect:/clz/list"
//toEdit->跳转到编辑界面
//Clazz:以前是通过模型驱动接口封装,现在是直接在方法中接收参数即可
@RequestMapping("/list")
public String list(Clazz clazz, HttpServletRequest request){
PageBean pageBean =new PageBean();
pageBean.setRequest(request);
List lst = this.clazzBiz.listPager(clazz, pageBean);
request.setAttribute("lst",lst);
request.setAttribute("pageBean",pageBean);
return "clzList";
}
}
ClazzController
@RequestMapping("/toEdit")
public String toEdit(Clazz clazz, HttpServletRequest request){
Integer cid = clazz.getCid();
//传递了id代表修改,没传代表新增
if(cid!=null){
List lst = this.clazzBiz.listPager(clazz, null);
request.setAttribute("b",lst.get(0));
}
return "clzEdit";
}
@RequestMapping("/add")
public String add(Clazz clazz){
this.clazzBiz.insertSelective(clazz);
return "redirect:/clz/list";
}
@RequestMapping("/toEdit")
public String toEdit(Clazz clazz, HttpServletRequest request){
Integer cid = clazz.getCid();
//传递了id代表修改,没传代表新增
if(cid!=null){
List lst = this.clazzBiz.listPager(clazz, null);
request.setAttribute("b",lst.get(0));
}
return "clzEdit";
}
@RequestMapping("/edit")
public String edit(Clazz clazz){
this.clazzBiz.updateByPrimaryKeySelective(clazz);
return "redirect:/clz/list";
}
@RequestMapping("/del")
public String del(Clazz clazz){
this.clazzBiz.deleteByPrimaryKey(clazz.getCid());
return "redirect:/clz/list";
}
}
SpringMVC上传
Springmvc.xml中添加 多功能解析器 配置
前台的页面 添加 多功能表单设置 multipart/from-data
后台要利用multipartFile类进行 文件接收
注:multipartFile的属性名一定要跟form中的表单属性名一致
在IDEA中完成图片请求地址与硬盘中地址的映射关系
commons-fileupload
commons-fileupload
1.3.3
vo:view Object
Dto:接收参数 参数不仅仅存在于实体类Model中
package com.oyang.ssm.model.dto;
import com.oyang.ssm.model.Clazz;
import org.springframework.web.multipart.MultipartFile;
/**
* @author oyang
* @site https://blog.csdn.net
* @qq 1828190940
* @create 2022-08-18 11:27
*/
public class ClazzDto extends Clazz {
//multipartFile的属性名一定要跟form中的表单属性名一致
private MultipartFile pocFile;
public MultipartFile getPocFile() {
return pocFile;
}
public void setPocFile(MultipartFile pocFile) {
this.pocFile = pocFile;
}
}
注意,这里ClazzDto 继承了Clazz实体类,要将实体类的的属性修饰符改成 protected,同时,multipartFile的属性名一定要跟form中的表单属性名一致!
ClazzController
上诉小编有提到,pom依赖可导可不导。这是为什么呢?小编给个位看下区别吧
不导pom依赖:
//文件上传
@RequestMapping("/upload")
public String upload(ClazzDto clazzDto) {
try {
//前台上传的文件
MultipartFile pocFile = clazzDto.getPocFile();
InputStream inputStream = pocFile.getInputStream();
FileOutputStream fout = new FileOutputStream(new File("d/temp"));
byte[] bbuf=new byte[1024];
int len=0;
while (true){
len=inputStream.read(bbuf,0,len);
fout.write(bbuf,0,len);
if(len<0){
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:/clz/list";
}
加了pom依赖:
//文件上传
@RequestMapping("/upload")
public String upload(ClazzDto clazzDto) {
try {
//前台上传的文件
MultipartFile pocFile = clazzDto.getPocFile();
String diskPath="D:/temp/oyang";//图片存放地址
InputStream inputStream = pocFile.getInputStream();
FileUtils.copyInputStreamToFile(inputStream,new File(diskPath));
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:/clz/list";
}
完整代码:
//文件上传
@RequestMapping("/upload")
public String upload(ClazzDto clazzDto) {
try {
//前台上传的文件
MultipartFile pocFile = clazzDto.getPocFile();
//实际应该配置到resource.properties中
String diskPath="D:/temp/oyang";//图片存放地址
String requesPath="/upload/mvc/";//数据库保存地址,也是访问地址
//拿到上传文件的名字
String filename = pocFile.getOriginalFilename();
InputStream inputStream = pocFile.getInputStream();
FileUtils.copyInputStreamToFile(inputStream,new File(diskPath+filename));
//将图片上传之后,并且将图片地址更新到数据库中
Clazz clazz=new Clazz();
clazz.setCid(clazzDto.getCid());
clazz.setPic(requesPath+filename);
this.clazzBiz.updateByPrimaryKeySelective(clazz);
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:/clz/list";
}
clzList.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"%>
博客列表
ID
班级名称
指导老师
班级相册
操作
${b.cid }
${b.cname }
${b.cteacher }
${b.pic }
修改
删除
上传图片
下载图片
clzUpload.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2022/8/19
Time: 1:19
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
文件上传
这可以看见,出来的是地址,而不是图片,我们需要在IDEA中完成图片请求地址与硬盘中地址的映射关系
首先将服务停止
点击 + 号 External Source
选择我们的映射地址
再将我们主界面的图片展示更改一下
SpringMVC下载
1.点击下载传递文件的ID,通过文件的ID查询出文件的路径
2.通过文件的请求地址,转换成文件存放的硬盘地址
3.将硬盘中的文件下载下来
下载图片
clzUpload.jsp
//文件上传
@RequestMapping("/download")
public ResponseEntity download(ClazzDto clazzDto) {
try {
// 1.点击下载传递文件的ID,通过文件的ID查询出文件的路径
Clazz clazz = this.clazzBiz.selectByPrimaryKey(clazzDto.getCid());
String pic = clazz.getPic();//数据库里的地址
//实际应该配置到resource.properties中
String diskPath="D:/temp/oyang/";//图片存放地址
String requesPath="/upload/mvc/";//数据库保存地址,也是访问地址
// 2.通过文件的请求地址,转换成文件存放的硬盘地址
String replPath=pic.replace(requesPath,diskPath);
String fileName=replPath.substring(replPath.lastIndexOf("/")+1);
// 3.将硬盘中的文件下载下来->固定代码
//下载关键代码
File file=new File(replPath);
HttpHeaders headers = new HttpHeaders();//http头信息
String downloadFileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");//设置编码
headers.setContentDispositionFormData("attachment", downloadFileName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//MediaType:互联网媒介类型 contentType:具体请求中的媒体类型信息
return new ResponseEntity(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
OK,本章的分享就到此结束啦,如果对个位看官有帮助的话可以留下免费的赞哦(收藏或关注也行),如果文章中有什么问题或不足以及需要改正的地方可以私信博主,博主会做出改正的。个位看官,小陽在此跟大家说拜拜啦