前言:
学习B站UP狂神说视频笔记整理视频链接
相关代码已经上传至码云:码云链接
前期准备
项目介绍
demo项目是一个简单的图书管理系统,主要功能为表单数据的增删改查
Web端使用JSP+Bootstrap
后端使用SpringMVC+Spring+Mybatis
使用技术:
技术 | 说明 |
---|---|
Junit | 单元测试 |
MyBatis | ORM框架 |
SpringMVC | MVC框架 |
Lombok | 简化对象封装工具 |
c3p0 | 数据库连接池 |
Bootstrap | 前端开源工具包 |
项目预览:
展示页
新增页
修改页
环境要求
IDEA
MySQL 5.7.19
Tomcat 9
Maven 3.6
数据库环境
CREATE DATABASE `ssmbuild`;
USE `ssmbuild`;
DROP TABLE IF EXISTS `books`;
CREATE TABLE `books` (
`bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT '书id',
`bookName` VARCHAR(100) NOT NULL COMMENT '书名',
`bookCounts` INT(11) NOT NULL COMMENT '数量',
`detail` VARCHAR(200) NOT NULL COMMENT '描述',
KEY `bookID` (`bookID`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES
(1,'Java',1,'从入门到放弃'),
(2,'MySQL',10,'从删库到跑路'),
(3,'Linux',5,'从进门到进牢');
创建Maven项目导入依赖
在pom.xml中导入依赖
<dependencies>
<!--Junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!--Servlet - JSP -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--Mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<!--Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
</dependencies>
处理Maven资源过滤问题
<!--Maven资源过滤处理-->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
将项目变成一个Web项目
建立基本结构和配置框架
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--Mybatis原生配置文件-->
</configuration>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--spring配置文件-->
</beans>
database.properties
jdbc.driver=com.mysql.jdbc.Driver
#使用Mybatis8.0+ 必须要设置时区serverTimezone=UTC
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456
Mybatis层编写
编写Mybatis原生配置文件-mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--Mybatis原生配置文件-->
<!--日志-->
<settings>
<!--标准的日志工厂STDOUT_LOGGING-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!--别名映射-->
<typeAliases>
<package name="com.tony.pojo"/>
</typeAliases>
</configuration>
创建数据库实体类-Books
/**
* 数据库实体类
* @Author Tu_Yooo
* @create 2021/4/4 10:53
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Books {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
}
编写Mapper接口-BooksMapper
/**
* 数据库dao层Mapper接口
* @Author Tu_Yooo
* @create 2021/4/4 10:54
*/
public interface BooksMapper {
//增加一个Book
int addBook(Books book);
//根据id删除一个Book
int deleteBookById(int id);
//更新Book
int updateBook(Books books);
//根据id查询,返回一个Book
Books queryBookById(int id);
//如果不传参 则查询全部Book,返回list集合 如果传参 则查询具体内容
List<Books> queryAllBook(String bookName);
}
编写Mapper接口映射文件-BooksMapper.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">
<!--namespace 命名空间 指向 定义一个Dao接口-->
<mapper namespace="com.tony.dao.BooksMapper">
<!--增加一个Book-->
<insert id="addBook" parameterType="books">
insert into ssmbuild.books (bookName,bookCounts,detail) values
(#{bookName},#{bookCounts},#{detail})
</insert>
<!--根据id删除一个Book-->
<delete id="deleteBookById" parameterType="int">
delete from ssmbuild.books where bookID=#{id}
</delete>
<!--更新一个book-->
<update id="updateBook" parameterType="books">
update ssmbuild.books set bookName = #{bookName},bookCounts = #{bookCounts},detail = #{detail}
where bookID = #{bookID}
</update>
<!--根据id查询,返回一个Book-->
<select id="queryBookById" parameterType="int" resultType="com.tony.pojo.Books">
select * from ssmbuild.books where bookID=#{id}
</select>
<!--传参则模糊查询 不传参则查全量数据-->
<select id="queryAllBook" parameterType="string" resultType="books">
select * from ssmbuild.books
<where>
<if test="bookName != null">
bookName like concat('%',#{bookName},'%')
</if>
</where>
</select>
</mapper>
编写Service层的接口和实现类
Service接口-BooksService
/**
* Service层接口
* @Author Tu_Yooo
* @create 2021/4/4 11:05
*/
public interface BooksService {
//增加一个Book
int addBook(Books book);
//根据id删除一个Book
int deleteBookById(int id);
//更新Book
int updateBook(Books books);
//根据id查询,返回一个Book
Books queryBookById(int id);
//如果不传参 则查询全部Book,返回list集合 如果传参 则查询具体内容
List<Books> queryAllBook(String bookName);
}
Service接口实现类-BooksServiceImpl
/**
* Service层接口实现类
* @Author Tu_Yooo
* @create 2021/4/4 11:06
*/
@Service
public class BooksServiceImpl implements BooksService{
//调用dao层的操作,设置一个set接口,方便Spring管理
@Autowired
private BooksMapper bookMapper;
@Override
public int addBook(Books book) {
return bookMapper.addBook(book);
}
@Override
public int deleteBookById(int id) {
return bookMapper.deleteBookById(id);
}
@Override
public int updateBook(Books books) {
return bookMapper.updateBook(books);
}
@Override
public Books queryBookById(int id) {
return bookMapper.queryBookById(id);
}
@Override
public List<Books> queryAllBook(String bookName) {
List<Books> books = bookMapper.queryAllBook(bookName);
if (books.size()==0){
//判断是否查询到值 如果没查询到 则查全量
books= bookMapper.queryAllBook(null);
}
return books;
}
}
当前项目目录如下:
Spring层编写
配置Spring整合MyBatis,我们这里数据源使用c3p0连接池
Spring整合Mybatis
创建与编写mybatis-spring.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--关联数据库配置文件-->
<context:property-placeholder location="classpath:database.properties"/>
<!--数据库连接池 C3P0连接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!-- c3p0连接池的私有属性 -->
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<!-- 关闭连接后不自动commit -->
<property name="autoCommitOnClose" value="false"/>
<!-- 获取连接超时时间 -->
<property name="checkoutTimeout" value="10000"/>
<!-- 当获取连接失败重试次数 -->
<property name="acquireRetryAttempts" value="2"/>
</bean>
<!--SQLSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--绑定MyBatis配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!--注册映射器-->
<property name="mapperLocations" value="classpath:mapper/BooksMapper.xml"/>
</bean>
<!--获取SQLSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--SqlSessionTemplate 只能使用构造器注入 因为它没有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<!--配置dao层接口扫描 动态实现Dao层接口注入容器-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入SQLSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--要扫描的dao包-->
<property name="basePackage" value="com.tony.dao"/>
</bean>
</beans>
Spring整合service
创建与编写spring-service.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--配置要扫描的service包-->
<context:component-scan base-package="com.tony.service"/>
<!--配置注解支持-->
<context:annotation-config/>
<!--配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
SpringMVC层编写
Spring整合SpringMVC
编写spring-mvc.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--注解驱动-->
<mvc:annotation-driven/>
<!--静态资源过滤-->
<mvc:default-servlet-handler/>
<!--扫描包-->
<context:component-scan base-package="com.tony.controller"/>
<!--视图解析器:DispatcherServlet给他的ModelAndView-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
编写web.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<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_4_0.xsd"
version="4.0">
<!--DispatcherServlet-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!--一定要注意:我们这里加载的是总的配置文件,之前被这里坑了!-->
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--encodingFilter 乱码过滤器-->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<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>
<!--Session过期时间-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
汇总所有配置文件
编写applicationContext.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--spring配置文件-->
<!--整合mybatis-->
<import resource="mybatis-spring.xml"/>
<!--整合service层-->
<import resource="spring-service.xml"/>
<!--整合MVC层-->
<import resource="spring-mvc.xml"/>
</beans>
当前项目结构目录如下:
编写业务
页面相关
首页-index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
<style>
h3 a{
color: darkcyan;
text-decoration: none;
font-family: fantasy;
font-size: 20px;
text-decoration: none;
}
h3{
width: 300px;
height: 300px;
margin: 0 auto;
text-align: center;
line-height: 300px;
background: bisque;
border-radius: 10px;
}
a:hover{
color: steelblue;
font-size: 30px;
}
</style>
</head>
<body>
<h3>
<a href="${pageContext.request.contextPath}/book/allBook">点击进入列表页</a>
</h3>
</body>
</html>
展示页-allBook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>书籍列表</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>书籍列表 —— 显示所有书籍</small>
</h1>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4 column">
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">新增</a>
</div>
<div class="col-md-4 column"></div>
<div class="col-md-4 column">
<%--查询书籍--%>
<form class="form-inline" action="${pageContext.request.contextPath}/book/queryBookName" method="post" style="float: right">
<input type="text" name="queryBookName" class="form-control" placeholder="请输入要查询的书籍">
<input type="submit" value="查询" class="btn btn-primary">
</form>
</div>
</div>
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-hover table-striped">
<thead>
<tr>
<th>书籍编号</th>
<th>书籍名字</th>
<th>书籍数量</th>
<th>书籍详情</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<c:forEach var="book" items="${list}">
<tr>
<td>${book.getBookID()}</td>
<td>${book.getBookName()}</td>
<td>${book.getBookCounts()}</td>
<td>${book.getDetail()}</td>
<td>
<a href="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.getBookID()}">更改</a> |
<a href="${pageContext.request.contextPath}/book/del/${book.getBookID()}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
新增页-addBook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>新增书籍</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>新增书籍</small>
</h1>
</div>
</div>
</div>
<form action="${pageContext.request.contextPath}/book/addBook" method="post">
<div class="form-group">
<lable>书籍名称:</lable>
<input type="text" name="bookName" class="form-control" required>
</div>
<div class="form-group">
<lable>书籍数量:</lable>
<input type="text" name="bookCounts" class="form-control" required>
</div>
<div class="form-group">
<lable>书籍详情:</lable>
<input type="text" name="detail" class="form-control" required>
</div>
<div class="form-group">
<input type="submit" value="添加">
</div>
</form>
</div>
</body>
</html>
修改页-updateBook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>修改书籍</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>修改书籍</small>
</h1>
</div>
</div>
</div>
<form action="${pageContext.request.contextPath}/book/updateBook" method="post">
<div class="form-group">
<lable>书籍id:</lable>
<input type="text" name="bookID" class="form-control" value="${Qbooks.bookID}" readonly>
</div>
<div class="form-group">
<lable>书籍名称:</lable>
<input type="text" name="bookName" class="form-control" value="${Qbooks.bookName}" required>
</div>
<div class="form-group">
<lable>书籍数量:</lable>
<input type="text" name="bookCounts" class="form-control" value="${Qbooks.bookCounts}" required>
</div>
<div class="form-group">
<lable>书籍详情:</lable>
<input type="text" name="detail" class="form-control" value="${Qbooks.detail}" required>
</div>
<div class="form-group">
<input type="submit" value="修改">
</div>
</form>
</div>
</body>
</html>
Controller代码编写
编写BooksController
/**
* Controller层
* @Author Tu_Yooo
* @create 2021/4/4 11:33
*/
@Controller
@RequestMapping("/book")
public class BooksController {
//controller层调service层
@Autowired
private BooksService booksService;
/**
* 查询全部书籍
* @param model
* @return 返回书籍展示页面
*/
@RequestMapping("/allBook")
public String listall(Model model){
List<Books> books = booksService.queryAllBook(null);
model.addAttribute("list",books);
return "allBook";
}
/**
* 查询指定名字的书籍
* @param queryBookName 要查询的书籍
* @param model 封装查询到的数据
* @return 返回页面 注意:此处不能使用重定向
*/
@RequestMapping("/queryBookName")
public String listall(String queryBookName,Model model){
String trim = queryBookName.trim();
List<Books> books = booksService.queryAllBook(trim);
model.addAttribute("list",books);
return "allBook";
}
/**
* 新增页面
* @return 跳转到新增书籍页面
*/
@RequestMapping("/toAddBook")
public String toaddBook(Model model){
model.addAttribute("msg","成功跳转页面");
return "addBook";
}
/**
* 新增书籍数据
* @param books 添加表单值
* @return 重定向到查询页
*/
@RequestMapping("/addBook")
public String addBook(Books books){
booksService.addBook(books);
return "redirect:/book/allBook";
}
/**
* 基于id查询对应数据 返回修改页面
* @param id 修改数据的id
* @param modle 封装书籍id对应的数据
* @return 返回一个修改页面
*/
@RequestMapping("/toUpdateBook")
public String updateBook(int id,Model modle){
Books books = booksService.queryBookById(id);
modle.addAttribute("Qbooks",books);
return "updateBook";
}
/**
* 修改表单数据
* @param books 修改数据
* @return 重定向到查询页
*/
@RequestMapping("/updateBook")
public String updateBook(Books books){
int i = booksService.updateBook(books);
return "redirect:/book/allBook";
}
/**
* 删除书籍
* @param bookID 需要删除的书籍id
* @return 重定向到查询页
*/
@RequestMapping("/del/{bookID}")
public String delBook(@PathVariable int bookID){
booksService.deleteBookById(bookID);
return "redirect:/book/allBook";
}
}
测试运行
配置tomcat
发布项目
扩展功能-文件上传
概述
文件上传是项目开发中最常见的功能之一 ,springMVC 可以很好的支持文件上传,但是SpringMVC上下文中默认没有装配MultipartResolver,因此默认情况下其不能处理文件上传工作。如果想使用Spring的文件上传功能,则需要在上下文中配置MultipartResolver。
CommonsMultipartFile 的 常用方法:
-
String getOriginalFilename():获取上传文件的原名
-
InputStream getInputStream():获取文件流
-
void transferTo(File dest):将上传文件保存到一个目录文件中
前端要求
前端表单要求:为了能上传文件,必须将表单的method设置为POST,并将enctype设置为multipart/form-data。只有在这样的情况下,浏览器才会把用户选择的文件以二进制数据发送给服务器;
表单中的 enctype 属性做个详细的说明:
1.application/x-www=form-urlencoded:默认方式,只处理表单域中的 value 属性值,采用这种编码方式的表单会将表单域中的值处理成 URL 编码方式。
2.multipart/form-data:这种编码方式会以二进制流的方式来处理表单数据,这种编码方式会把文件域指定文件的内容也封装到请求参数中,不会对字符编码。
3.text/plain:除了把空格转换为 “+” 号外,其他字符都不做编码处理,这种方式适用直接通过表单发送邮件。
<form action="" enctype="multipart/form-data" method="post">
<input type="file" name="file"/>
<input type="submit">
</form>
文件上传
导入依赖
导入文件上传的jar包,commons-fileupload
<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<!--servlet-api导入高版本的-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
修改新增页-addBook.jsp
添加表单代码
<%--文件上传--%>
<form action="${pageContext.request.contextPath}/file/upload" enctype="multipart/form-data" method="post">
<div class="form-group">
<input type="file" name="file"/>
<span>${filename}</span>
</div>
<div class="form-group">
<input type="submit" id="importForm" value="提交">
</div>
</form>
配置bean-multipartResolver
在mvc配置文件spring-mvc.xml
配置bean
【注意!!!这个bena的id必须为:multipartResolver , 否则上传文件会报400的错误!在这里栽过坑,教训!】
<!--文件上传配置-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->
<property name="defaultEncoding" value="utf-8"/>
<!-- 上传文件大小上限,单位为字节(10485760=10M) -->
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="40960"/>
</bean>
编写FileController
/**
* 文件相关
* @author Tu_Yooo
* @Date 2021/4/8 9:56
*/
@Controller
@RequestMapping("/file")
public class FileController {
//图片存储路径
private String localDir="D:/Download/";
/**
* 文件上传
* @param file 传输过来的图片文件
* @param request 请求头
* @return 回显是否成功
*/
@RequestMapping("/upload")
public String upload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request, Model model){
//获取文件名
String filename = file.getOriginalFilename();
//将图片名称转换成小写字母
filename = filename.toLowerCase();
//如果文件名为空直接返回到首页
if("".equals(filename)){
model.addAttribute("filename","文件名为空!");
return "addBook";
}
System.out.println("上传文件名 : "+filename);
//正则表达式校验 是否为图片
if(!filename.matches("^.+\\.(png|jpg|gif)$")) {
model.addAttribute("filename","请上传图片");
return "addBook";
}
//校验是否为恶意程序
try {
BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
int width = bufferedImage .getWidth();
int height = bufferedImage.getHeight();
if(width == 0 || height ==0){
//说明 上传的不是图片,为恶意程序.
model.addAttribute("filename","请上传图片");
return "addBook";
}
//按照时间将目录进行划分 yyyy/MM/dd
String deteDir = new SimpleDateFormat("yyyy/MM/dd/").format(new Date());
String localFileDir = localDir+deteDir;
File file1 = new File(localFileDir);
if(!file1.exists()) {
//如果目录不存在则创建多级目录
file1.mkdirs();
}
//动态生成文件名
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
//abc.jpg
int index = filename.lastIndexOf(".");
String fileType = filename.substring(index);//截取文件后缀
String realFileName = uuid + fileType;
//文件上传
String realFilePath = localFileDir + realFileName;
File imageFile = new File(realFilePath);
//通过CommonsMultipartFile的方法直接写文件
file.transferTo(imageFile);
model.addAttribute("filename",realFilePath);
return "addBook";
} catch (IOException e) {
e.printStackTrace();
model.addAttribute("filename","未知异常!");
return "addBook";
}
}
}
常见问题解答
访问出现404
排查步骤:
1.查看jar依赖是否正确导入
2.如果jar包存在,显示无法输出,就在IDEA的项目发布中添加lib依赖!
3.重启Tomcat即可解决
ClassNotFoundException
原因:
lib目录下缺少相关依赖
解决: 补全依赖,重启项目