18 SpringMVC 文件上传和异常处理

1.文件上传的必要前提

(1)form 表单的 enctype 取值必须是:multipart/form-data
(默认值是:application/x-www-form-urlencoded) enctype:是表单请求正文的类型
(2)method 属性取值必须是 Post
(3)提供一个文件选择域<input type=”file” />

2.文件上传环境搭建

(1)项目结构

18 SpringMVC 文件上传和异常处理

(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方式文件上传

原理分析图:

18 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异常处理

原理分析图:

18 SpringMVC 文件上传和异常处理

(1)项目结构

18 SpringMVC 文件上传和异常处理

(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 文件上传和异常处理

上一篇:[PHP知识点乱炖]四、全局变量——小偷从良记


下一篇:最长回文子序列/最长回文子串(DP,马拉车)