目录
本次目标:
一、CRUD
1.导pom依赖(记得导这个之前先联网!!)
2.框架配置文件
applicationContext.xml
applicationContext-mybatis.xml
generatorConfig.xml
jdbc.properties
log4j2.xml
springmvc-servlet.xml
3.Web.xml:
4.导入工具类 Pagebean,tag助手类,tid文件
5.做开发
二、文件上传
2.1 在springmv.xml中添加 多功能解析器 配置
2.1.1 pom依赖
2.1.2 Springmvc.xml配置
2.2 前台的页面 添加 多功能表单设置 multipart/form-data
2.3 后台要利用multipartFile类进行 文件接收
2.4 在IDEA中完成图片请求地址与硬盘中地址的映射关系
三、文件下载
- CRUD
- 文件上传
- 文件下载
(springmvc的增删改查: 自定义mvc)
4.0.0
org.example
ssm2
1.0-SNAPSHOT
war
ssm2 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
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
commons-fileupload
commons-fileupload
1.3.3
ssm2
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
导完后会有这个:(点左边那个 Import Changes)
等他下载完jar包就行
- applicationContext.xml
- applicationContext-mybatis.xml
- generatorConfig.xml
- jdbc.properties
- log4j2.xml
- mybatis.cfg.xml
- springmvc-servlet.xml
helperDialect=mysql
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?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
(这个配置文件要在WEB-INF目录下)
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
/*
pageBean:
package com.ps.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.ps.ssm.tag;
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;
import com.ps.ssm.util.PageBean;
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();
}
}
tld文件:zking.tld
zking 1.1 core library
zking core
1.1
zking
http://jsp.veryedu.cn
page
com.ps.ssm.tag.PageTag
JSP
pageBean
true
true
将t_struts_class表逆向生成出Model、Mapper.xml、Mapper.java
表:
在generatorConfig.xml配置中添加以下代码:
然后运行即可 ;
这是之前导入的那些环境配置文件:
还有(model、dao、service、前端)
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.xml)
ClazzMapper:
package com.ps.ssm.mapper;
import com.ps.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);
List listPager(Clazz clazz);
int updateByPrimaryKeySelective(Clazz record);
int updateByPrimaryKey(Clazz record);
}
biz层
package com.ps.ssm.biz;
import com.ps.ssm.model.Clazz;
import com.ps.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);
}
实现类
package com.ps.ssm.impl;
import com.ps.ssm.biz.ClazzBiz;
import com.ps.ssm.mapper.ClazzMapper;
import com.ps.ssm.model.Clazz;
import com.ps.ssm.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author 彭于晏
* @company 玉渊工作室
* @create 2022-08-19 00:42
*/
@Service
public class ClassBizImpl implements ClazzBiz {
@Autowired
private ClazzMapper clazzMapper;
@Override
public int deleteByPrimaryKey(Integer cid) {
return clazzMapper.deleteByPrimaryKey(cid);
}
@Override
public int insert(Clazz record) {
return clazzMapper.insertSelective(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);
}
}
切面类:
package com.ps.ssm.aspect;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ps.ssm.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 彭于晏
* @company 玉渊工作室
* @create 2022-08-15 16:32
*/
@Component
@Aspect
public class PagerAspect {
/**
* *:返回值类型
* *..:无限包
* *Biz:以Biz结尾的接口名
* *Pager:以Pager方法
* 只要同时匹配上诉四个条件就会被列为目标对象
* 上诉配置要生效,代理注释一定要打开:
* @param args
* @return
* @throws Throwable
*/
@Around("execution(* *..*Biz.*Pager(..))")
public Object invoke(ProceedingJoinPoint args) throws Throwable {
Object[] params = args.getArgs();
PageBean pageBean = null;
for (Object param : params) {
if(param instanceof PageBean){
pageBean = (PageBean)param;
break;
}
}
if(pageBean != null && pageBean.isPagination())
PageHelper.startPage(pageBean.getPage(),pageBean.getRows());
//执行目标
Object list = args.proceed(params);
if(null != pageBean && pageBean.isPagination()){
PageInfo pageInfo = new PageInfo((List) list);
pageBean.setTotal(pageInfo.getTotal()+"");
}
return list;
}
}
实体类:
package com.ps.ssm.model;
public class Clazz {
protected Integer cid;
protected String cname;
protected String cteacher;
protected 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;
}
}
ClazzController:
package com.ps.ssm.controller;
import com.ps.ssm.biz.ClazzBiz;
import com.ps.ssm.model.Clazz;
import com.ps.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 彭于晏
* @company 玉渊工作室
* @create 2022-08-18 16:23
*/
@Controller
@RequestMapping("/clz")
public class ClazzController {
@Autowired
private ClazzBiz clazzBiz;
@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";
}
@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("c",lst.get(0));
}
return "clzList";
}
@RequestMapping("/add")
public String add(Clazz clazz){
this.clazzBiz.insertSelective(clazz);
return "redirect:/clz/list";
}
@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";
}
}
前台界面
clzEdit.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
博客的编辑界面
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 }
修改
删除
上传图片
下载图片
运行前先设置一下 Tomcat
(没有Tomcat就点左上角的那个加号进行添加)
然后运行项目:
然后 我们测试一下增删改查:
查询:
接着我们新增一条数据:
现在多了一条数据了,接着我们修改一下:
最后我们再修改删除一下:
(上面给的代码已经加了,这里博主只展示一下是哪部分的代码,下面配置代码都是一样的)
commons-fileupload
commons-fileupload
1.3.3
前台:
clzUpload.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
在clzLIst界面加两个操作:
名词解释:
vo: view Object
Dto: 接收参数,参数不仅仅存在于实体类Model中
ClazzDto:
package com.ps.ssm.model.dto;
import com.ps.ssm.model.Clazz;
import org.springframework.web.multipart.MultipartFile;
/**
* @author 彭于晏
* @site www.pengyuyan.com
* @company 玉渊工作室
* @create 2022-08-21 20:35
*/
public class ClazzDto extends Clazz {
// multipartFile的属性名一定要跟form 中的表单属性名一致
private MultipartFile picFile;
public MultipartFile getPicFile() {
return picFile;
}
public void setPicFile(MultipartFile picFile) {
this.picFile = picFile;
}
}
文件上传的方法:加到ClazzController中
// 文件上传
@RequestMapping("/upload")
public String upload(ClazzDto clazzDto){
try {
// 前台上传文件
MultipartFile picFile = clazzDto.getPicFile();
// 实际应该配置到resource.properties 中
String diskPath ="E:/temp/T280/";// 图片的存放地址
// http://localhost:8080/upload/mvc/suibian.png
String requestPath="/upload/mvc/";// 数据库保存的地址,也是访问地址
// 拿到上传文件的名字
String filename = picFile.getOriginalFilename();//suibian.png
FileUtils.copyInputStreamToFile(picFile.getInputStream(),new File(diskPath+filename));
// 将图片上传之后,并且将图片地址更行到数据库中
Clazz clazz =new Clazz();
clazz.setCid(clazzDto.getCid());
clazz.setPic(requestPath+filename);
this.clazzBiz.updateByPrimaryKeySelective(clazz);
}catch (Exception e){
e.printStackTrace();
}
return "redirect:/clz/list";
}
注:multipartFile的属性名一定要跟form 中的表单属性名一致
如果想要图片上传成功,我们就得完成在IDEA中完成图片请求地址与硬盘中地址的映射关系
那么我们就进行映射:
然后找到tomcat点图下右边那个加
然后选择你用映射的硬盘的地址:
然后我们上传一下图片看看!
主界面直接点击8号的上传图片,来到这里
点击选择图片
提交后:
步骤:
- 点击下载传递文件的ID,通过文件的ID查询出文件的路径
- 通过文件的请求地址,转换成文件存放的硬盘地址
- 将硬盘中的文件下载下来->固定代码
一样在 ClazzController中加入下载的方法:
@RequestMapping("/download")
public ResponseEntity download(ClazzDto clazzDto){
try {
// 1.点击下载传递文件的ID,通过文件的ID查询出文件的路径
Clazz clazz = this.clazzBiz.selectByPrimaryKey(clazzDto.getCid());
String pic = clazz.getPic();// /upload/mvc/0314.png
//实际应该配置到resource.properties 中
String diskPath ="E:/temp/T280/";// 图片的存放地址
// http://localhost:8080/upload/mvc/suibian.png
String requestPath="/upload/mvc/";// 数据库保存的地址,也是访问地址
// 2.通过文件的请求地址,转换成文件存放的硬盘地址
String realPath=pic.replace(requestPath,diskPath);// E:/temp/T280/0314.png
String fileName= realPath.substring(realPath.lastIndexOf("/")+1);
// 3.将硬盘中的文件下载下来->固定代码
//下载关键代码
File file=new File(realPath);
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;
}
然后在clzList界面加入操作标签:
上传图片
下载图片
最后看看效果吧!:
下载成功了!
今天的分享就到这里啦!如果喜欢博主的话可以点赞加收藏支持博主哦!