哈喽~大家好~~又是我~~~~上期带大家入门了我们的Springmvc这次给大家备一点干货!!!!
目录
一、增删改查环境搭建
2)框架配置文件
3)web.xml配置
4)导入工具类 PageBean、tag助手类、tld文件
二、增删改查测试
三、文件上传
Springmvc.xml配置:
四、文件下载
首先我们先导入我们的pom依赖!
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
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
applicationContext.xml:
applicationContext-mybatis.xml:
helperDialect=mysql
jdbc.properties:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/yjy?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=1234
generatorConfig.xml:
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:
dispatcherServlet
ContextLoadListener
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.zking.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.zking.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.zking.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 1.1 core library
zking core
1.1
zking
http://jsp.veryedu.cn
page
com.zking.ssm.tag.PageTag
JSP
pageBean
true
true
先写我们的实体类:
package com.zking.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;
}
}
ClazzMapper
package com.zking.mapper;
import com.zking.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);
}
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}
PagerAspect :
package com.zking.ssm.aspect;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zking.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;
@Component
@Aspect
public class PagerAspect {
/**
* *:返回值类型
* *..:无线包
* *Service:以Service结尾接口名
* *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;
}
}
ClazzController
package com.zking.controller;
import com.zking.model.Clazz;
import com.zking.ssm.biz.ClazzBiz;
import com.zking.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;
@Controller
@RequestMapping("/clz")
public class ClazzController {
@Autowired
private ClazzBiz clazzBiz;
// list——>clzlist
// toList——>重定向list——>"redirect:/clz/list"
// toEdit——>跳转到编辑界面——>clzEdit
// 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";
}
@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("/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";
}
}
ClazzBiz
package com.zking.ssm.biz;
import com.zking.model.Clazz;
import com.zking.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.zking.ssm.biz.impl;
import com.zking.mapper.ClazzMapper;
import com.zking.model.Clazz;
import com.zking.ssm.biz.ClazzBiz;
import com.zking.ssm.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.security.provider.certpath.CertId;
import java.util.List;
@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);
}
}
前端页面代码:
<%@ 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 }
修改
删除
上传图片
下载图片
clzEdit:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
编辑界面
查询
其他功能有误, 正在努力中.....
我们先导入我们的pom依赖
commons-fileupload
commons-fileupload
1.3.3
ClazzDto :
package com.zking.model.dto;
import com.zking.model.Clazz;
import org.springframework.web.multipart.MultipartFile;
public class ClazzDto extends Clazz {
// multipartFile的属性名一定要跟form中的表单属性名一致
private MultipartFile picFile;
public MultipartFile getPicFile() {
return picFile;
}
public void setPicFile(MultipartFile picFile) {
this.picFile = picFile;
}
}
注意我们的实体类
// 文件上传
@RequestMapping("/upload")
public String upload(ClazzDto clazzDto){
try {
// 前台上传的文件
MultipartFile picFile = clazzDto.getPicFile();
// 实际应该配置到resource.properties中
String diskPath="G:/temp";//图片存放地址
// http://localhost:8080/upload/mvc/...png
String requestPath="/upload/mvc/";//数据库保存地址,也是访问地址
//拿到上传文件的名字
String filename = picFile.getOriginalFilename();
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";
}
1、点击下载传递文件的ID,通过文件的ID查询出文件的路径
2、通过文件的请求地址,转换成文件存放的硬盘地址
3、将硬盘中文件下载下来——>固定代码
ClazzController:
//文件下载
@RequestMapping("/download")
public ResponseEntity download(ClazzDto clazzDto){
try {
//1、点击下载传递文件的ID,通过文件的ID查询出文件的路径
Clazz clazz = this.clazzBiz.selectByPrimaryKey(clazzDto.getCid());
String pic=clazz.getPic();//
String diskPath = "G:/temp/";
String requestPath = "/upload/mvc/";
//2、通过文件的请求地址,转换成文件存放的硬盘地址
String realPath = pic.replace(requestPath, diskPath);
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;
}
因为一些报错还没解决,今天给大家分享就到这啦~等待博主后续改进!!!
有发现更好方法的宝宝们可以联系博主进入探讨,为博主指条明路!!!!!