18 SpringMVC 文件上传和异常处理
1.文件上传的必要前提
(1)form 表单的 enctype 取值必须是:multipart/form-data
(默认值是:application/x-www-form-urlencoded) enctype:是表单请求正文的类型
(2)method 属性取值必须是 Post
(3)提供一个文件选择域<input type=”file” />
2.文件上传环境搭建
(1)项目结构

(2)部分重要代码
<1>web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app>
<display-name>Archetype Created Web Application</display-name>
<!--配置前端控制器,让前端控制器去加载resources包下的springmvc.xml配置文件-->
<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:springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> <!--配置解决中文乱码的过滤器-->
<filter>
<filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> </web-app>
<2>spirngmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 开启注解扫描 -->
<context:component-scan base-package="lucky"/> <!-- 视图解析器对象 -->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--配置控制器方法中return返回的字符串对应的同名文件所在目录-->
<property name="prefix" value="/WEB-INF/pages/"/>
<!--配置文件的后缀名-->
<property name="suffix" value=".jsp"/>
</bean> <!-- 开启SpringMVC框架注解的支持 -->
<mvc:annotation-driven/> </beans>
<3>index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>文件上传</h3>
<form action="/day19_fileupload/user/fileUploadTest01" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload"><br>
<input type="submit" value="上传">
</form>
</body>
</html>
3.传统方式上传文件
package lucky.controller; import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;
import java.util.UUID; @Controller
@RequestMapping(path = "/user")
public class UserController {
//传统方式上传文件
@RequestMapping(path = "/fileUploadTest01")
public String fileUploadTest01(HttpServletRequest request, HttpServletResponse response) throws Exception{
System.out.println("文件上传");
// 使用fileupload组件完成文件上传
// 上传的位置
String path = request.getSession().getServletContext().getRealPath("/uploads/");
System.out.println(path); //查看文件上传的路径
// 判断,该路径是否存在
File file = new File(path);
if(!file.exists()){
// 创建该文件夹
file.mkdirs();
} // 解析request对象,获取上传文件项
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
// 解析request
List<FileItem> items = upload.parseRequest(request);
// 遍历
for(FileItem item:items){
// 进行判断,当前item对象是否是上传文件项
if(item.isFormField()){
// 说明普通表单向
}else{
// 说明上传文件项
// 获取上传文件的名称
String filename = item.getName();
// 把文件的名称设置唯一值,uuid
String uuid = UUID.randomUUID().toString().replace("-", "");
filename = uuid+"_"+filename;
// 完成文件上传
item.write(new File(path,filename));
// 删除临时文件
item.delete();
}
}
return "success";
}
}
4.Springmvc方式文件上传
原理分析图:

package lucky.controller; import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;
import java.util.UUID; @Controller
@RequestMapping(path = "/user")
public class UserController { /**
* springmvc方式上传文件
* 注意:请求参数MultipartFile upload 的名称upload必须与index.jsp中input标签的属性名一致,否则会造成空指针异常
* @return
*/
@RequestMapping(path = "/fileUploadTest02")
public String fileUploadTest02(HttpServletRequest request, MultipartFile upload) throws Exception{
System.out.println("springmvc文件上传");
// 使用fileupload组件完成文件上传
// 上传的位置
String path = request.getSession().getServletContext().getRealPath("/uploads/");
System.out.println(path); //查看文件上传的路径
// 判断,该路径是否存在
File file = new File(path);
if(!file.exists()){
// 创建该文件夹
file.mkdirs();
} // 说明上传文件项
// 获取上传文件的名称
String filename = upload.getOriginalFilename();
// 把文件的名称设置唯一值,uuid
String uuid = UUID.randomUUID().toString().replace("-", "");
filename = uuid+"_"+filename;
// 完成文件上传
upload.transferTo(new File(path,filename));
return "success";
}
}
5.Springmvc异常处理
原理分析图:

(1)项目结构

(2)部分重要代码
<1>控制器类:UserController.java
package lucky.controller; import lucky.exception.CustomException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; @Controller
@RequestMapping(path = "/user")
public class UserController {
@RequestMapping(path = "/testException")
public String testException() throws CustomException {
System.out.println("testException执行了");
try {
//模拟异常
int a=10/0;
} catch (Exception e) {
//抛出自定义异常
throw new CustomException("被除数有问题");
}
return "success";
}
}
<2>自定义异常类
package lucky.exception; /**
* 自定义异常类
*/
public class CustomException extends Exception{
//存储提示信息
private String message; public String getMessage() {
return message;
} public void setMessage(String message) {
this.message = message;
} public CustomException(String message) {
this.message = message;
}
}
<3>异常处理器:CustomExceptionResolver.java
package lucky.exception; import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* 异常处理器
*/
public class CustomExceptionResolver implements HandlerExceptionResolver { /**
*处理异常的业务逻辑
*/
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
//获取异常对象
CustomException customException=null;
if(e instanceof CustomException){
customException= (CustomException) e;
}else {
customException=new CustomException("系统正在维护。。。");
}
//创建ModelAndView
ModelAndView mv=new ModelAndView();
mv.addObject("errormsg",e.getMessage());
mv.setViewName("error");
return mv;
}
}
<4>springmvc.xml文件中配置异常处理器
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 开启注解扫描 -->
<context:component-scan base-package="lucky"/> <!-- 视图解析器对象 -->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--配置控制器方法中return返回的字符串对应的同名文件所在目录-->
<property name="prefix" value="/WEB-INF/pages/"/>
<!--配置文件的后缀名-->
<property name="suffix" value=".jsp"/>
</bean> <!--配置异常处理器-->
<bean id="customExceptionResolver" class="lucky.exception.CustomExceptionResolver"/> <!-- 开启SpringMVC框架注解的支持 -->
<mvc:annotation-driven/> </beans>
<6>相关jsp页面
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>异常处理</h3>
<a href="/day19_exception/user/testException">异常处理</a>
</body>
</html>
error.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>error.jsp</h3>
${errormsg}
</body>
</html>
(3)执行效果图

18 SpringMVC 文件上传和异常处理的更多相关文章
- 05 SpringMVC:02.参数绑定及自定义类型转换&&04.SpringMVC返回值类型及响应数据类型&&05.文件上传&&06.异常处理及拦截器
springMVC共三天 第一天: 01.SpringMVC概述及入门案例 02.参数绑定及自定义类型转换 03.SpringMVC常用注解 第二天: 04.SpringMVC返回值类型及响应数据类型 ...
- SpringMVC文件上传 Excle文件 Poi解析 验证 去重 并批量导入 MYSQL数据库
SpringMVC文件上传 Excle文件 Poi解析并批量导入 MYSQL数据库 /** * 业务需求说明: * 1 批量导入成员 并且 自主创建账号 * 2 校验数据格式 且 重复导入提示 已被 ...
- springMVC文件上传大小超过限制的问题
[转自]https://my.oschina.net/ironwill/blog/646762 springMVC是一个非常方便的web层框架,我们使用它的文件上传也非常的方便. 我们通过下面的配置来 ...
- springmvc文件上传AND jwt身份验证
SpringMVC文件上传 思路:1.首先定义页面,定义多功能表单(enctype=“multipart/form-data”)2.在Controller里面定义一个方法,用参数(MultipartF ...
- springmvc文件上传下载简单实现案例(ssm框架使用)
springmvc文件上传下载实现起来非常简单,此springmvc上传下载案例适合已经搭建好的ssm框架(spring+springmvc+mybatis)使用,ssm框架项目的搭建我相信你们已经搭 ...
- 解决springMVC文件上传报错: The current request is not a multipart request
转自:https://blog.csdn.net/HaHa_Sir/article/details/79131607 解决springMVC文件上传报错: The current request is ...
- TZ_06_SpringMVC_传统文件上传和SpringMVC文件上传方式
1.传统文件上传方式 <!-- 文件上传需要的jar --> <dependency> <groupId>commons-fileupload</groupI ...
- SpringMVC文件上传下载(单文件、多文件)
前言 大家好,我是bigsai,今天我们学习Springmvc的文件上传下载. 文件上传和下载是互联网web应用非常重要的组成部分,它是信息交互传输的重要渠道之一.你可能经常在网页上传下载文件,你可能 ...
- SpringMVC 文件上传&拦截器&异常处理
文件上传 Spring MVC 为文件上传提供了直接的支持,这种支持是通过即插即用的 MultipartResolver 实现的.Spring 用 Jakarta Commons FileUpload ...
随机推荐
- js字符串转换为JSON
1. json字符串 jsStr = “{"a":'xxx', "b":'yyy'}” JSON.parse(jsStr); //可以将json字符串转换成j ...
- kuma 学习四 策略
通过策略我们可以构建灵活的service mesh 应用策略 我们可以通过kumactl 以及kubectl 应用策略 kumactl 格式 echo " type: .. spec: .. ...
- ABP 03 解决 编辑User报错
1.编辑用户时,报错.后面有跟解决方案. 解决方案1: 2.导致出错的原因是这样的,这里的功能是请求服务端的html页面,渲染后显示编辑页面. 关键点是默认参数那儿 路径:\aspnet-core\s ...
- Mysql8.0 创建远程登陆账户
mysql8和原来的版本有点不一样,8的安全级别更高,所以在创建远程连接用户的时候, 不能用原来的命令(同时创建用户和赋权): mysql>grant all PRIVILEGES on *.* ...
- A*G/C011
A*G/C011 A Airport Bus 不会zbl/kk B Colorful Creatures 枚举每个开始的点直接倍增 我好像sb了,可行的是一段前缀所以可以直接2分 C Squared ...
- 第04组alpha冲刺(3/4)
队名:斗地组 组长博客:地址 作业博客:Alpha冲刺(3/4) 各组员情况 林涛(组长) 过去两天完成了哪些任务: 1.收集各个组员的进度 2.写博客 展示GitHub当日代码/文档签入记录: 接下 ...
- javascript优先级注意点
javascript 优先级 注意一下 && 和 == 号之间的优先级关系 请首先看如下代码, 判断下 && 和 == 的优先级 const emptyObj = {n ...
- 【技术博客】MySQL和Django常用操作
MySQL和Django是搭建网站常用的配置之一,在此记录一下在Windows系统搭建网站时MySQL以及Django常用的操作. MySQL MySQL的SQL语句不区分大小写,推荐将保留字大写,数 ...
- leetcode 85. 最大矩形
题目描述: 给定一个仅包含 0 和 1 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积. 思路分析: 这题是之前那道最大正方形的进阶,同样是利用dp来求解.通过逐行去计算最大矩形,即优化的 ...
- linux中SIGHUP与nohup的关系
SIGHUP信号与控制终端 UNIX中进程组织结构为 session (会话)包含一个前台进程组及一个或多个后台进程组,一个进程组包含多个进程.一个session可能会有一个session首进程, ...