Spring MVC回顾–上传案例
配置SringMVC组件
- 创建spring mvc需要导入的依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
- 配置web.xml时,需要优先配置DispatcherServlet
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--初始化时,一并加载springMVC的配置文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC-config.xml</param-value>
</init-param>
<!--加载优先级 设置成1-->
<load-on-startup>1</load-on-startup>
</servlet>
<!--从这里接收用户请求,请求路径为“/”,意思就是可以拦截任何请求,然后映射到上面dispatcherServlet,创建
dispatcherServlet对象
-->
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
- jsp页面的头信息
<!--处理乱码-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
- SpringMVC的配置文件中需要导入的约束空间
<?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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
</bean>
- 在SpringMVC配置文件中配置如下这个信息时,它会自动加载处理器映射器(RequestMappingHandlerMapping),处理器适配器(RequestMappingHandlerAdapter)
<mvc:annotation-driven>
-
Spring MVC的各个组件中,处理器映射器、处理器适配器、视图解析器并称三大组件
- 核心是前端控制器DispatcherServlet
-
处理请求编码乱码
//配置解决中文乱码的过滤器,任何请求都可以拦截
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
//找到这个MVC提供的设置编码类,初始化参数
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
//拦截请求 拦截到请求后根据名字找到上面的filter
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/星号</url-pattern>
</filter-mapping>
相关注解
- @RequestMapping:建立请求URL和处理请求方法之间的对应关系
- 如何获取请求,传入参数即可
- HttpServletRequest request,HttpServletResponse response
- request.getSession()
加载响应
-
archetypeCatalog internal
-
ModelAndView实际上跟String一样
-
web.xml配置的前端控制器会拦截所有的请求,在spring配置中解决这个问题
- 问题:所有请求都给拦截,因此静态资源也给拦截,不能访问
- springmvc配置文件中配置
//js不拦截拦截
<mvc:resources mapping="/js/**" location="/js/**"/>
//样式不拦截
<mvc:resources mapping="/css/**" location="/css/**"/>
//图片资源不拦截
<mvc:resources mapping="/images/**" location="/images/**"/>
Spring mvc的文件上传
文件上传前提
-
form表单的enctype取值必须是:multipart/form-data
- 默认是:application/x-www-form-urlencoded
- enctype:是表单请求正文的类型
-
method属性取值必须是post
-
提供一个文件选择域
借助第三方组件实现文件上传
- 使用commons-fileupload组件实现文件上传
- 还需要导入commons-io,这个包不属于上传组件开发包,但是他是上传包的依赖包
传统方法上传文件
- 页面写form表单
<h3>文件上传</h3>
<form action="/fileupload1" method="post" enctype="multipart/form-data">
<input type="file" name="upload"><br>
<input type="submit" value="上传">
</form>
- Controller
/**
* 文件上传
表单提交文件,所有的数据都会被封装到request对象中。
解析request,然后拿到文件。直接加参数HttpServletRequest request
request.getSession()拿到最大的session对象
request.getSession().getServletContext()拿到最大的域对象
request.getRealPath() 这个表示的是web内容里的路径,参数具体到路径
* @return
*/
@RequestMapping("/fileupload1")
public String fileupload1(HttpServletRequest request) throws Exception{
//1. 从request中获取信息
String path = request.getSession().getServletContext().getRealPath("/uploads/");
//2. 判断文件夹是否存在,如果不存在,创建文件夹
File file = new File(path);
if(!file.exists()){
file.mkdir();
}
//3. 解析request对象,获取上传的文件,组件中的类
/**
创建一个磁盘临时空间,暂时存放从request中取到的数据
创建文件上传对象,用于存储文件的操作
*/
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
//4. 解析request
List<FileItem> fileItems = upload.parseRequest(request);
//遍历
for (FileItem fileItem : fileItems) {
//判断当前文件是否是上传文件
if(fileItem.isFormField()){
System.out.println("不是上传文件");
}else{
//是上传文件
//1. 获取文件名
String fileName = fileItem.getName();
//2. 使用UUID替换成乱码
String uuid = UUID.randomUUID().toString().replace("-","");
String fileName2 = uuid + "_" + fileName;
//写入
fileItem.write(new File(path,fileName2));
//删除临时文件
fileItem.delete();
}
}
return "success";
}
Spring MVC的提供的上传方式
-
commons-fileupload和commons-io
-
spring配置文件中配置文件解析器对象
//配置文件解析器对象
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760"/>
</bean>
- controller中写方法,参数两个一个request,一个MultipartFile upload
@RequestMapping("/fileupload2")
public String fileupload2(HttpServletRequest request, MultipartFile upload) throws Exception {
//1. 配置好了文件解析对象,不需要对request取出的文件进行解析
String path = request.getSession().getServletContext().getRealPath("/uploads/");
//2. 判断目录是否存在
File file = new File(path);
if(!file.exists()){
file.mkdir();
}
//3. 设置好名字
String originalFilename = upload.getOriginalFilename();
String uuid = UUID.randomUUID().toString().replace("-","");
originalFilename = uuid + "-" + originalFilename;
//4. 使用upload完成上传
upload.transferTo(new File(path,originalFilename));
return "success";
}
Spring MVC跨服务器上传
- 上传资源一般是上传到另一个专门存放数据的服务器上,因此需要再导入两个jar包
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.18.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.18.1</version>
</dependency>
- 配置文件解析器对象
- 前端不可少的form表单
- controller方法
@RequestMapping("/fileupload3")
public String fileuoload3(MultipartFile upload) throws Exception {
System.out.println("跨服务器文件上传...");
// 定义上传文件服务器路径
String path = "http://localhost:9090/uploads/";
// 说明上传文件项
// 获取上传文件的名称
String filename = upload.getOriginalFilename();
// 把文件的名称设置唯一值,uuid
String uuid = UUID.randomUUID().toString().replace("-", "");
filename = uuid+"_"+filename;
// 创建客户端的对象
Client client = Client.create();
// 和图片服务器进行连接
WebResource webResource = client.resource(path + filename);
// 上传文件
webResource.put(upload.getBytes());
return "success";
}