目录
- <web-app
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns="http://xmlns.jcp.org/xml/ns/javaee"
- xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
- http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
- id="WebApp_ID" version="3.1">
- <display-name>Archetype Created Web Application</display-name>
- </web-app>
并把上个子模块的pom.xml里的依赖和插件复制到这个子模块中。
pom.xml:
- <?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>com.first</groupId>
- <artifactId>mvc_demo2</artifactId>
- <version>1.0-SNAPSHOT</version>
- <packaging>war</packaging>
-
- <name>mvc_demo2 Maven Webapp</name>
- <!-- FIXME change it to the project's website -->
- <url>http://www.example.com</url>
-
- <dependencies>
- <!-- Spring核心模块 -->
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context</artifactId>
- <version>5.2.12.RELEASE</version>
- </dependency>
- <!-- SpringWeb模块 -->
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-web</artifactId>
- <version>5.2.12.RELEASE</version>
- </dependency>
- <!-- SpringMVC模块 -->
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- <version>5.2.12.RELEASE</version>
- </dependency>
- <!-- Servlet -->
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>servlet-api</artifactId>
- <version>2.5</version>
- <!--设为provided使运行时使用tomcat自带的servlet,下面的jsp也是一样-->
- <scope>provided</scope>
- </dependency>
- <!-- JSP -->
- <dependency>
- <groupId>javax.servlet.jsp</groupId>
- <artifactId>jsp-api</artifactId>
- <version>2.0</version>
- <scope>provided</scope>
- </dependency>
- <!-- jackson -->
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-core</artifactId>
- <version>2.9.0</version>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-databind</artifactId>
- <version>2.9.0</version>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-annotations</artifactId>
- <version>2.9.0</version>
- </dependency>
- </dependencies>
- <build>
- <plugins>
- <!-- tomcat插件 -->
- <plugin>
- <groupId>org.apache.tomcat.maven</groupId>
- <artifactId>tomcat7-maven-plugin</artifactId>
- <version>2.1</version>
- <configuration>
- <port>8080</port>
- <path>/</path>
- <uriEncoding>UTF-8</uriEncoding>
- <server>tomcat7</server>
- <systemProperties>
- <java.util.logging.SimpleFormatter.format>%1$tH:%1$tM:%1$tS %2$s%n%4$s: %5$s%6$s%n
- </java.util.logging.SimpleFormatter.format>
- </systemProperties>
- </configuration>
- </plugin>
- </plugins>
- </build>
- </project>
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="com.first"/>
- <!-- 开启SpringMVC注解的支持 -->
- <mvc:annotation-driven ></mvc:annotation-driven>
-
- <!-- 视图解析器 -->
- <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <!-- 视图前缀 ,因为我放在webapp下,所以前缀是/,如果放在WEB-INF下,value就是/WEB-INF-->
- <property name="prefix" value="/" />
- <!-- 视图后缀 -->
- <property name="suffix" value=".jsp" />
- </bean>
-
- <!-- 放行静态资源 -->
- <mvc:default-servlet-handler />
-
- </beans>
然后web.xml再添加一些上个子工程的一些配置 ,
- <web-app
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns="http://xmlns.jcp.org/xml/ns/javaee"
- xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
- http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
- id="WebApp_ID" version="3.1">
- <display-name>Archetype Created Web Application</display-name>
-
- <!--SpringMVC中提供的字符编码过滤器,放在所有过滤器的最上方-->
- <filter>
- <filter-name>encFilter</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>encFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
-
- <!-- 请求方式过滤器 -->
- <filter>
- <filter-name>httpMethodFilter</filter-name>
- <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>httpMethodFilter</filter-name>
- <!--所有路径都过滤-->
- <url-pattern>/*</url-pattern>
- </filter-mapping>
-
- <!--SpringMVC前端控制器,本质是一个Servlet,接收所有请求,再分发到相应路径中,在容器启动时就会加载-->
- <servlet>
- <servlet-name>dispatcherServlet</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <init-param>
- <param-name>contextConfigLocation</param-name>
- <!--springMVC配置文件的位置-->
- <param-value>classpath:springmvc.xml</param-value>
- </init-param>
- <!--在web容器创建时,servlet就会被创建好-->
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>dispatcherServlet</servlet-name>
- <!--接收所有的请求-->
- <url-pattern>/</url-pattern>
- </servlet-mapping>
- </web-app>
(2)编写上传表单
upload.jsp:
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <html>
- <head>
- <title>上传</title>
- </head>
- <body>
- <h3>文件上传</h3>
- <form action="/fileUpload" method="post" enctype="multipart/form-data">
- <%-- 文件上传控件,类型是file --%>
- 选择文件:<input type="file" name="upload">
- <input type="submit" value="上传">
- </form>
- </body>
- </html>
然后如下创建:
- package com.first.controller;
-
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
-
- import javax.servlet.ServletInputStream;
- import javax.servlet.http.HttpServletRequest;
-
- @Controller
- public class UploadController {
- @RequestMapping("/fileUpload")
- public String upload(HttpServletRequest request) throws Exception {
- // 获取输入流
- ServletInputStream is = request.getInputStream();
- // 从输入流获取请求体数据
- int i = 0;
- while ((i=is.read())!=-1){
- System.out.print((char)i);
- }
- return "index";
- }
- }
访问 http://localhost:8080/upload.jsp
控制台部分输出如下:
(3)接收请求体数据:
- <!-- 文件上传 -->
- <dependency>
- <groupId>commons-fileupload</groupId>
- <artifactId>commonsfileupload</artifactId>
- <version>1.3.1</version>
- </dependency> <dependency>
- <groupId>commons-io</groupId>
- <artifactId>commons-io</artifactId>
- <version>2.4</version>
- </dependency>
- package com.first.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 java.io.File;
- import java.util.List;
-
- @Controller
- public class UploadController {
- //原生上传方式
- @RequestMapping("/fileUpload")
- public String upload(HttpServletRequest request) throws Exception {
- // 创建文件夹,存放上传文件
- // 1.设置上传文件夹的真实路径
- String realPath = request.getSession().getServletContext().getRealPath("/upload");
-
- // 2.判断该目录是否存在,如果不存在,创建该目录
- File file = new File(realPath);
- if(!file.exists()){
- file.mkdirs();
- }
-
- // 分析请求体,找到上传文件数据
- // 1.创建磁盘文件工厂
- DiskFileItemFactory factory = new DiskFileItemFactory();
- // 2.创建上传数据分析器对象
- ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
- // 3.利用分析器对象解析请求体,返回所有数据项
- List<FileItem> fileItems = servletFileUpload.parseRequest(request);
- // 4.遍历所有数据,找到文件项(非表单项)
- for (FileItem fileItem:fileItems){
- if(!fileItem.isFormField()){
- // 将文件数据写入文件夹
- // 1.获取文件名
- String name = fileItem.getName();
- // 2.将文件写入磁盘
- fileItem.write(new File(file,name));
- // 3.删除内存中的临时文件
- fileItem.delete();
- }
- }
- return "index";
- }
- }
访问http://localhost:8080/upload.jsp
- <!-- 文件解析器对象,id名称必须是multipartResolver -->
- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
- <!-- 支持一次上传文件的总容量。单位:字节 100M = 100*1024*1024-->
- <property name="maxUploadSize" value="104857600"/>
- <!-- 文件名的编码方式-->
- <property name="defaultEncoding" value="utf-8"/>
- </bean>
2.创建JSP表单upload2.jsp
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
-
- <html>
- <head>
- <title>上传</title>
- </head>
- <body>
- <h3>文件上传</h3>
- <form action="/fileUpload2" method="post" enctype="multipart/form-data">
- <%-- 文件上传控件,类型是file --%>
- 选择文件:<input type="file" name="file">
- <input type="submit" value="上传">
- </form>
- </body>
- </html>
3.编写控制器接收上传请求
- // MultipartFile参数名必须和JSP文件空间的name属性一致
- @RequestMapping("/fileUpload2")
- public String upload2(MultipartFile file, HttpServletRequest request) throws IOException {
- // 创建文件夹,存放上传文件
- String realPath = request.getSession().getServletContext().getRealPath("/upload");
- File dir = new File(realPath);
- if(!dir.exists()){
- dir.mkdirs();
- }
-
- // 将上传的数据写到文件夹的文件中
- // 1.拿到上传的文件名
- String filename = file.getOriginalFilename();
- filename = UUID.randomUUID()+"_"+filename;
- // 2.创建空文件
- File newFile = new File(dir,filename);
- // 3.将数据写入空文件中
- file.transferTo(newFile);
- //视图解析器,跳转到index.jsp页面
- return "index";
- }
选择一个文件上传,比如一张图片,然后自动跳转到index.jsp页面中
然后查看webapp目录下,自动创建了upload文件夹,且此文件夹下有上传的图片。
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
-
- <html>
- <head>
- <title>上传</title>
- </head>
- <body>
- <h3>文件上传</h3>
- <form action="/fileUpload3" method="post" enctype="multipart/form-data">
- <%-- 文件上传控件,类型是file --%>
- 用户名:<input name="username">
- 选择文件:<input type="file" name="files">
- 选择文件:<input type="file" name="files">
- <input type="submit" value="上传">
- </form>
- </body>
- </html>
2.编写控制器接收上传请求
- @RequestMapping("/fileUpload3")
- public String upload3(String username,MultipartFile[] files,HttpServletRequest request) throws IOException {
- System.out.println(username);
-
- // 创建文件夹,存放上传文件
- String realPath = request.getSession().getServletContext().getRealPath("/upload");
- File dir = new File(realPath);
- if(!dir.exists()){
- dir.mkdirs();
- }
- // 遍历数组,将上传的文件保存到文件夹
- for (MultipartFile file : files) {
- String filename = file.getOriginalFilename();
- filename = UUID.randomUUID()+"_"+filename;
- File newFile = new File(dir, filename);
- file.transferTo(newFile);
- }
- return "index";
- }
访问:http://localhost:8080/upload3.jsp
点击上传
控制台输出:
查看webapp下upload文件夹