目录
一、SpringMVC实现CRUD
二、SpringMVC实现上传文件
三、SpringMVC实现文件下载
这次我们从头到尾,一步一步来实现一次搭建环境+基本配置+后端编码+前端编码的。基于SpringMVC的CRUD
这里我是Idea创建Maven的模块(就是项目,只是Idea中成为模块而已,最外面的文件才叫项目)
这是我们就初步创建完毕Maven项目但是还需要细微调整(必须要确保自己的网络OK!!!)
到这里我们还需修改一下,因为我们刚创建的模块是没有完整的文件的,我们需要手动添加
然后我们就可以开始下一步了,这一步是之后所有的开始!
我都准备好了大家直接copy即可
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
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
因为我们在正式的项目开发肯定使用框架进行开发工作,也就意味着我们的对应的框架的配置文件也少不了!
我已经整理如下了,然后我们导入的时候建议一个个检查,因为有些是需要改变中间的文件路径啊等等一下小细节的,这个不改就会对应的报错!
我们看一下配置文件的载入位置:(和我保持一样即可)
接下来是直接准备好,大家copy即可,文件有点多大家注意别搞错!!!
helperDialect=mysql
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
OK这些是我们使用到的框架的所有配置文件,包括日志框架、mybatis、SpringMVC、Spring
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
/*
完成好上述我们就是搭建好maven项目开发的环境了接下来正式进入编码工作
我们做CRUD肯定要分页,那么我们就使用我们的工具类配合实现分页:
zking 1.1 core library
zking core
1.1
zking
http://jsp.veryedu.cn
page
com.zq.ssm.tag.PageTag
JSP
pageBean
true
true
还有我们们的工具类util以及tage我们将它们分别放入不同的包,以及上次我们处理分页时所用的切面aspect
package com.zq.ssm.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.zq.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);
}
}
package com.zq.ssm.tag;
import com.zq.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();
}
}
package com.zq.ssm.aspect;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zq.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张强
* @site www.zq.com
* @create 2022-08-16 11:45
*/
@Component
@Aspect
public class PagerAspect {
@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;
}
}
我们可以使用mybatis的逆向生成功能初步完成实体类以及方法的开发
关于逆向生成的步骤在之前已经介绍了,这里直接实践:
我们使用到的数据库为:t_struts_class
然后在配置文件中我已经写好了,我们直接运行我们创建的maven命令进行逆向生成
结果:我们想要实现的就是如图的效果:
这里是因为我是写完在做博客的所以有些下面才会实现对应的包和类!
我们需要分页的话还需要自己写一个分页查询的方法在对应的文件中添加:
package com.zq.ssm.mapper;
import com.zq.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);
}
package com.zq.ssm.biz;
import com.zq.ssm.model.Clazz;
import com.zq.ssm.util.PageBean;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
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.zq.ssm.biz.impl;
import com.zq.ssm.biz.ClazzBiz;
import com.zq.ssm.mapper.ClazzMapper;
import com.zq.ssm.model.Clazz;
import com.zq.ssm.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author张强
* @site www.zq.com
* @create 2022-08-17 18:25
*/
@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);
}
}
package com.zq.ssm.controller;
import com.zq.ssm.biz.ClazzBiz;
import com.zq.ssm.model.Clazz;
import com.zq.ssm.model.dto.ClazzDto;
import com.zq.ssm.util.PageBean;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
/**
* @author张强
* @site www.zq.com
* @create 2022-08-17 18:35
*/
@Controller
@RequestMapping("/clz")
public class ClazzController {
@Autowired
private ClazzBiz clazzBiz;
@RequestMapping("/list")
public String list(HttpServletRequest req, Clazz clazz){
PageBean pageBean = new PageBean();
pageBean.setRequest(req);
List lst = this.clazzBiz.listPager(clazz, pageBean);
req.setAttribute("lst",lst);
req.setAttribute("pageBean",pageBean);
return "list";
}
@RequestMapping("/add")
public String add(HttpServletRequest req, Clazz clazz){
this.clazzBiz.insertSelective(clazz);
return "redirect:/clz/list";
}
@RequestMapping("/edit")
public String edit(HttpServletRequest req, Clazz clazz){
this.clazzBiz.updateByPrimaryKeySelective(clazz);
return "redirect:/clz/list";
}
@RequestMapping("/del")
public String del(HttpServletRequest req, Clazz clazz){
this.clazzBiz.deleteByPrimaryKey(clazz.getCid());
return "redirect:/clz/list";
}
@RequestMapping("/toEdit")
public String toEdit(HttpServletRequest req, Clazz clazz){
if(clazz.getCid() != null){
List lst = this.clazzBiz.listPager(clazz, null);
req.setAttribute("b",lst.get(0));
}
return "clzEdit";
}
}
<%@ 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 }
修改
删除
上传
下载
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
玉渊工作室
我们完成前后端编码后只需最后一步就是配置Tomcat了
commons-fileupload
commons-fileupload
1.3.3
<%--
Created by IntelliJ IDEA.
User: zjjt
Date: 2022/8/17
Time: 23:41
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
玉渊工作室
这里要注意的是multipartFile的属性名一定要和form表单中的属性名一致
package com.zq.ssm.model.dto;
import com.zq.ssm.model.Clazz;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;
/**
* @author张强
* @site www.zq.com
* @create 2022-08-17 23:45
*/
@Data
public class ClazzDto extends Clazz {
private MultipartFile picFile;
public MultipartFile getPicFile() {
return picFile;
}
public void setPicFile(MultipartFile picFile) {
this.picFile = picFile;
}
}
在我们刚才创建的Controller类中加入文件上传的方法
//文件上传
@RequestMapping("/upload")
public String upload(ClazzDto clazzDto){
try {
String diskPath = "E:/temp/T280/";
String reqPath = "/upload/mvc/";
MultipartFile picFile = clazzDto.getPicFile();
// 完成文件上传
FileUtils.copyInputStreamToFile(picFile.getInputStream(),new File(diskPath+picFile.getOriginalFilename()));
// 保存到数据库中
Clazz clz = new Clazz();
clz.setCid(clazzDto.getCid());
clz.setPic(reqPath + picFile.getOriginalFilename());
this.clazzBiz.updateByPrimaryKeySelective(clz);
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/clz/list";
}
选择配置Tomcat,然后进行配置
1、点击下载传递文件的ID,通过文件的ID查询出对应的数据库中的的文件路径
2、通过文件的请求地址,转换成文件存放的硬盘地址
3、将硬盘中文件下载下来
@RequestMapping(value="/download")
public ResponseEntity download(Clazz clazz, HttpServletRequest req){
try {
//先根据文件id查询对应图片信息
Clazz clz = this.clazzBiz.selectByPrimaryKey(clazz.getCid());
String diskPath = "E:/temp/T280/";
String reqPath = "/upload/mvc/";
String realPath = clz.getPic().replace(reqPath,diskPath);
String fileName = realPath.substring(realPath.lastIndexOf("/")+1);
//下载关键代码
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;
}