目录
一、CRUD
1.导入相关pom依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>ssm2</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>ssm2 Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.plugin.version>3.7.0</maven.compiler.plugin.version>
<!--添加jar包依赖-->
<!--1.spring 5.0.2.RELEASE相关-->
<spring.version>5.0.2.RELEASE</spring.version>
<!--2.mybatis相关-->
<mybatis.version>3.4.5</mybatis.version>
<!--mysql-->
<mysql.version>5.1.44</mysql.version>
<!--pagehelper分页jar依赖-->
<pagehelper.version>5.1.2</pagehelper.version>
<!--mybatis与spring集成jar依赖-->
<mybatis.spring.version>1.3.1</mybatis.spring.version>
<!--3.dbcp2连接池相关 druid-->
<commons.dbcp2.version>2.1.1</commons.dbcp2.version>
<commons.pool2.version>2.4.3</commons.pool2.version>
<!--4.log日志相关-->
<log4j2.version>2.9.1</log4j2.version>
<!--5.其他-->
<junit.version>4.12</junit.version>
<servlet.version>4.0.0</servlet.version>
<lombok.version>1.18.2</lombok.version>
</properties>
<dependencies>
<!--1.spring相关-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!--2.mybatis相关-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!--pagehelper分页插件jar包依赖-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>${pagehelper.version}</version>
</dependency>
<!--mybatis与spring集成jar包依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis.spring.version}</version>
</dependency>
<!--3.dbcp2连接池相关-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>${commons.dbcp2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>${commons.pool2.version}</version>
</dependency>
<!--4.log日志相关依赖-->
<!--核心log4j2jar包-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j2.version}</version>
</dependency>
<!--web工程需要包含log4j-web,非web工程不需要-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-web</artifactId>
<version>${log4j2.version}</version>
</dependency>
<!--5.其他-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- jsp依赖-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
</dependencies>
<build>
<finalName>ssm2</finalName>
<resources>
<!--解决mybatis-generator-maven-plugin运行时没有将XxxMapper.xml文件放入target文件夹的问题-->
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<!--解决mybatis-generator-maven-plugin运行时没有将jdbc.properites文件放入target文件夹的问题-->
<resource>
<directory>src/main/resources</directory>
<includes>
<include>jdbc.properties</include>
<include>*.xml</include>
</includes>
</resource>
</resources>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven.compiler.plugin.version}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<dependencies>
<!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
</dependencies>
<configuration>
<overwrite>true</overwrite>
</configuration>
</plugin>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
2.相关配置文件
applicationContext.xml
applicationContext-mybatis.xml
generatorConfig.xml
jdbc.properties
log4j2.xml
springmvc-servlet.xml
3.web.xml相关配置
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 读取Spring上下文的监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring MVC servlet -->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--此参数可以不配置,默认值为:/WEB-INF/springmvc-servlet.xml-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<!--web.xml 3.0的新特性,是否支持异步-->
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 中文乱码处理 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!--web.xml 3.0的新特性,是否支持异步-->
<async-supported>true</async-supported>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
4.逆向生成
将t_struts_class表逆向生成出Model、Mapper.xml、Mapper.java
①Clazz
package com.liaoxin.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;
}
}
②ClazzMapper.java
package com.liaoxin.ssm.mapper;
import com.liaoxin.ssm.model.Clazz;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Map;
@Repository
public interface ClazzMapper {
int deleteByPrimaryKey(Integer cid);
int insert(Clazz record);
int insertSelective(Clazz record);
Clazz selectByPrimaryKey(Integer cid);
List<Clazz> listPager(Clazz clazz);
int updateByPrimaryKeySelective(Clazz record);
int updateByPrimaryKey(Clazz record);
}
③ClazzMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.liaoxin.ssm.mapper.ClazzMapper" >
<resultMap id="BaseResultMap" type="com.liaoxin.ssm.model.Clazz" >
<constructor >
<idArg column="cid" jdbcType="INTEGER" javaType="java.lang.Integer" />
<arg column="cname" jdbcType="VARCHAR" javaType="java.lang.String" />
<arg column="cteacher" jdbcType="VARCHAR" javaType="java.lang.String" />
<arg column="pic" jdbcType="VARCHAR" javaType="java.lang.String" />
</constructor>
</resultMap>
<sql id="Base_Column_List" >
cid, cname, cteacher, pic
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from t_struts_class
where cid = #{cid,jdbcType=INTEGER}
</select>
<select id="listPager" resultType="com.liaoxin.ssm.model.Clazz" parameterType="com.liaoxin.ssm.model.Clazz" >
select
<include refid="Base_Column_List" />
from t_struts_class
<where>
<if test="cname != null and cname != ''">
and cname like concat('%',#{cname},'%')
</if>
<if test="cid != null and cid != ''">
and cid = #{cid}
</if>
</where>
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from t_struts_class
where cid = #{cid,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.liaoxin.ssm.model.Clazz" >
insert into t_struts_class (cid, cname, cteacher,
pic)
values (#{cid,jdbcType=INTEGER}, #{cname,jdbcType=VARCHAR}, #{cteacher,jdbcType=VARCHAR},
#{pic,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" parameterType="com.liaoxin.ssm.model.Clazz" >
insert into t_struts_class
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="cid != null" >
cid,
</if>
<if test="cname != null" >
cname,
</if>
<if test="cteacher != null" >
cteacher,
</if>
<if test="pic != null" >
pic,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="cid != null" >
#{cid,jdbcType=INTEGER},
</if>
<if test="cname != null" >
#{cname,jdbcType=VARCHAR},
</if>
<if test="cteacher != null" >
#{cteacher,jdbcType=VARCHAR},
</if>
<if test="pic != null" >
#{pic,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.liaoxin.ssm.model.Clazz" >
update t_struts_class
<set >
<if test="cname != null" >
cname = #{cname,jdbcType=VARCHAR},
</if>
<if test="cteacher != null" >
cteacher = #{cteacher,jdbcType=VARCHAR},
</if>
<if test="pic != null" >
pic = #{pic,jdbcType=VARCHAR},
</if>
</set>
where cid = #{cid,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.liaoxin.ssm.model.Clazz" >
update t_struts_class
set cname = #{cname,jdbcType=VARCHAR},
cteacher = #{cteacher,jdbcType=VARCHAR},
pic = #{pic,jdbcType=VARCHAR}
where cid = #{cid,jdbcType=INTEGER}
</update>
</mapper>
5.后端代码
5.1.ClazzBiz
package com.liaoxin.ssm.biz;
import com.liaoxin.ssm.model.Clazz;
import com.liaoxin.ssm.util.PageBean;
import java.util.List;
import java.util.Map;
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<Clazz> listPager(Clazz clazz, PageBean pageBean);
}
5.2.ClazzBizImpl
package com.liaoxin.ssm.biz.impl;
import com.liaoxin.ssm.biz.ClazzBiz;
import com.liaoxin.ssm.mapper.ClazzMapper;
import com.liaoxin.ssm.model.Clazz;
import com.liaoxin.ssm.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
@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<Clazz> listPager(Clazz clazz, PageBean pageBean) {
return clazzMapper.listPager(clazz);
}
}
5.3.ClazzController
@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<Clazz> 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<Clazz> 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";
}
6.前端代码
①clzEdit
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>编辑界面</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/clz/${empty b ? 'add' : 'edit'}" method="post">
cid:<input type="text" name="cid" value="${b.cid }"><br>
cname:<input type="text" name="cname" value="${b.cname }"><br>
cteacher:<input type="text" name="cteacher" value="${b.cteacher }"><br>
<input type="submit">
</form>
</body>
</html>
②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"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link
href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css"
rel="stylesheet">
<script
src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js"></script>
<title>博客列表</title>
<style type="text/css">
.page-item input {
padding: 0;
width: 40px;
height: 100%;
text-align: center;
margin: 0 6px;
}
.page-item input, .page-item b {
line-height: 38px;
float: left;
font-weight: 400;
}
.page-item.go-input {
margin: 0 10px;
}
</style>
</head>
<body>
<form class="form-inline"
action="${pageContext.request.contextPath }/clz/list" method="post">
<div class="form-group mb-2">
<input type="text" class="form-control-plaintext" name="cname"
placeholder="请输入班级名称">
</div>
<button type="submit" class="btn btn-primary mb-2">查询</button>
<a class="btn btn-primary mb-2" href="${pageContext.request.contextPath }/clz/toEdit">新增</a>
</form>
<table class="table table-striped bg-success">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">班级名称</th>
<th scope="col">指导老师</th>
<th scope="col">班级相册</th>
<th scope="col">操作</th>
</tr>
</thead>
<tbody>
<c:forEach var="b" items="${lst }">
<tr>
<td>${b.cid }</td>
<td>${b.cname }</td>
<td>${b.cteacher }</td>
<td>
<img src="${pageContext.request.contextPath }${b.pic }" style="height: 100px;width: 100px;" />
</td>
<td>
<a href="${pageContext.request.contextPath }/clz/toEdit?cid=${b.cid}">修改</a>
<a href="${pageContext.request.contextPath }/clz/del?cid=${b.cid}">删除</a>
<a href="${pageContext.request.contextPath }/clzUpload.jsp?cid=${b.cid}">上传图片</a>
<a href="${pageContext.request.contextPath }/clz/download?cid=${b.cid}">下载图片</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
<!-- 这一行代码就相当于前面分页需求前端的几十行了 -->
<z:page pageBean="${pageBean }"></z:page>
</body>
</html>
二、文件上传和下载
1.后端
①、ClazzDto
package com.liaoxin.ssm.model.dto;
import com.liaoxin.ssm.model.Clazz;
import org.springframework.web.multipart.MultipartFile;
/**
* @author liaoxin
* @create 2022-08-18 21:13
*/
public class ClazzDto extends Clazz {
// MultipartFile的属性名一定要跟form中的表单属性名一致
private MultipartFile picFile;
public MultipartFile getPicFile() {
return picFile;
}
public void setPicFile(MultipartFile picFile) {
this.picFile = picFile;
}
}
②、ClazzController
package com.liaoxin.ssm.web;
import com.liaoxin.ssm.biz.ClazzBiz;
import com.liaoxin.ssm.model.Clazz;
import com.liaoxin.ssm.model.dto.ClazzDto;
import com.liaoxin.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.FileOutputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
@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<Clazz> 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<Clazz> 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";
}
// 文件上传
@RequestMapping("/upload")
public String upload(ClazzDto clazzDto){
try{
// 前台上传的文件
MultipartFile picFile = clazzDto.getPicFile();
// InputStream inputStream = picFile.getInputStream();
/*FileOutputStream fout = new FileOutputStream(new File("D/temp/1.png"));
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;
}
}*/
// 实际应该配置到resource.properties中
String dispath="E:/temp/images";//图片的存放地址
// http://localhost:8080/upload/mvc/**.png
String requestPath="/upload/mvc";//数据库保存的地址,也是访问地址
// 拿到上传文件的名字
String fileName = picFile.getOriginalFilename();//**.png
FileUtils.copyInputStreamToFile(picFile.getInputStream(),new File(dispath+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";
}
// 文件下载
@RequestMapping("/download")
public ResponseEntity download(ClazzDto clazzDto){
try{
// 1.点击下载传递文件的ID,通过文件的ID查询出文件的路径
Clazz clazz = this.clazzBiz.selectByPrimaryKey(clazzDto.getCid());
String pic=clazz.getPic();// /upload/mvc/**.png
// 实际应该配置到resource.properties中
String diskPath="E:/temp/images/";//图片的存放地址
// http://localhost:8080/upload/mvc/图片.png
String requestPath="/upload/mvc/";//数据库保存的地址,也是访问地址
// 2.通过文件的请求地址,转换成文件存放的硬盘地
String realPath=pic.replace(requestPath,diskPath);// E:/temp/images
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<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
2.前端
clzUpload
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2022/8/18
Time: 21:09
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/clz/upload" method="post" enctype="multipart/form-data">
<input type="text" value="${param.cid}" name="cid"/>
<input type="file" name="picFile"/>
<input type="submit"/>
</form>
</body>
</html>