This is the fourth day of my participation in the August More text Challenge. For details, see:August is more challenging

Introduction to SpringMVC

1.1 introduction to SpringMVC

In order to make Spring have pluggable MVC architecture,Spring Framework develops SpringMVC framework on the basis of Spring, so that when using Spring for WEB development, you can choose to use Spring’s SpringMVC framework as the controller framework of WEB development.

1.2 advantages of SpringMVC

SpringMVC is a typical lightweight MVC framework, which acts as the controller framework in the whole MVC architecture. Compared with the previous StrutS2 framework,SpringMVC runs faster and its annotated development is more efficient and flexible.

  1. Integrates seamlessly with the Spring framework.
  2. It is much more efficient than strutS2.
  3. Annotated development is more efficient.

Introduction to SpringMVC

2.1 Environment construction

2.1.1 Introducing dependencies

Dependency is ignored, I put in the comment section!

2.1.2. Write configuration files


      
<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">

<! -- 1. Enable annotation scan -->
  <context:component-scan base-package="com.lin.controller"/>
<! -- 2. Configure processor mapper -->
<! -- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />-->
<! -- 3. Turn on the processor adapter -->
<! -- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" />-->
<! -- The above two configuration paragraphs are replaced by the following sentence (encapsulation) -->
  <mvc:annotation-driven />
  <! -- 4. Enable view parser -->
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/"/>
    <property name="suffix" value=".jsp"/>
  </bean>
</beans>
Copy the code

2.1.3 Configure web.xml

<! DOCTYPEweb-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>

<! -- Configure springMVC's core servlet-->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
<! -- Tell SpringMVC where the configuration file is -->
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
<! -- Block all requests -->
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>
Copy the code

2.1.4 Write the controller

package com.lin.controller;

import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/ * * *@author XiaoLin
 * @date2021/2/17 17:09 * /
@Controller
public class HellowController {

  / * * *@Description: First SpringMVC test class *@author XiaoLin
      * @date 2021/2/17
      * @Param: [username, password]
      * @return java.lang.String
      */
     /* RequestMapping can be applied to both classes and methods. Its functions are as follows: 1. 2. For a class, you can add a uniform request path for all methods in the class. */ must be added before the method can be accessed
  @RequestMapping("/hello")
  public String hello(String username,String password){
    System.out.println("hello");
    return "index"; }}Copy the code

2.2. Detailed explanation of annotations

2.2.1,@Controller

This annotation is used on the class to identify this as a controller component class and to create an instance of this class, telling Spring THAT I am a controller.

2.2.2,@RequestMapping

This annotation can be applied to a method or class to specify the request path.

2.3 Jump mode of SpringMVC

Traditional Servlet development jump has two ways:

  1. Forward: Indicates a forward jump within the server. Therefore, it is a request and the address bar remains unchanged. A jump can be passed with data (using the request scope).
  2. Redirect: Indicates that a redirect is a request from a client. Therefore, the address bar changes when the request is repeated. Data cannot be transferred during the redirect.

2.3.1, Controller — > Foreground Page

2.3.1.1, forward

Through testing, we can find that SpringMVC default is to use the request forward way to jump to the front page;

@Controller
@RequestMapping("forwoartAndRedirect")
public class TestForwoartAndRedirect {

  @RequestMapping("test")
  public String test(a){
    System.out.println("test");
    return"index"; }}Copy the code

2.3.1.2, redirect

If we want to redirect, we need to do it using the keyword redirect: provided by SpringMVC.

Syntax: return “redirect:/ view full pathname “;

** Note: ** pages following redirect are not logical names, but full pathnames. Because redirect redirect doesn’t go through the view parser.

2.3.1 Controller – > Controller

2.3.1.1, forward

If we want to use the forward request to jump to different methods of the same (different)Controller, we also need to use the SpringMVC keyword forward:.

Syntax: return:”forward: / @requestMapping value on the class to jump to / @requestMapping value on the method to jump to;”

2.3.1.2, redirect

If we want to redirect to different methods of the same Controller, we also need to use the SpringMVC keyword redirect:.

Syntax: return:”redirect: / @requestMapping on the class to redirect to / @requestMapping on the method to redirect to;”

2.4 Receiving SpringMVC parameters

2.4.1 How servlets receive parameters

In traditional Servlet development, we usually use this method to receive request parameters.

// Accept a parameter named name
request.getParameter(name)
Copy the code

He has a few things to watch out for:

  1. The parameter must be the name attribute of the form field.
  2. The getParameter method is used to get a single value and the return type is String.
  3. The getParameterValues method is used to get a set of data and returns String[].
  4. Redundant code, cumbersome to use, the type needs to be converted.

2.4.2 Receiving parameters of SpringMVC

SpringMVC uses the method parameter list in the controller to receive the request parameters from the client. It can perform automatic type conversion and requires that the key of the passed parameter be the same as the name of the corresponding method parameter to complete automatic assignment. His advantages are clear:

  1. Simplified form of receiving parameters (no method is called, and whatever parameters are needed are provided in the controller method).
  2. The parameter types do not need to be converted themselves. Date time (default: YYYY /MM/ DD) Note that you need to use the @dateTimeFormat annotation to declare the format to be followed by the date conversion, otherwise 400 is thrown.

2.4.2.1 Basic data types

To complete automatic assignment, the key of the passed parameter must be the same as the name of the corresponding method parameter.

2.4.2.2 Object types

If we need to receive an object type, we simply declare the object as a controller method parameter. SpringMVC will automatically encapsulate the object, if the passed parameter key is the same as the property name in the object, it will be automatically encapsulated as an object.

2.4.2.3 Array types

If we want to receive an array type, we simply declare the array type as a formal parameter to the method.

2.4.2.4 Collection type

SpringMVC cannot directly receive parameters of a collection type through a formal parameter list. To receive parameters of a collection type, SpringMVC must put the collection into an object and provide a get/set method. It is recommended to encapsulate it in VO objects and use the object type to receive it.

2.5. Garbled Chinese characters in SpringMVC receiving parameters

2.5.1 GET request

Garbled characters in the GET request mode need to be discussed in different Tomcat versions:

  1. Before Tomcat8.x: Defaults to server.xmlURIEncoding="ISO-8859-1"Encoding, rather than “UTF-8” encoding, which causes garbled Chinese characters.
  2. After Tomcat8.x: Defaults to server.xmlURIEncoding="UTF-8", so there will be no Chinese garbled problem.

2.5.2 POST request

By default, SpringMVC does not encode any POST requests, so Chinese garbled characters will appear no matter what version directly receives POST requests.

2.5.2.1 Customizing filters to resolve garbled POST requests

In the Servlet phase, we learned about filters, which we can customize to encode the filter.

package com.filter;

import javax.servlet.*;
import java.io.IOException;

// Customize the encoding filter
public class CharacterEncodingFilter  implements Filter {

    private String encoding;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.encoding = filterConfig.getInitParameter("encoding");
        System.out.println(encoding);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding(encoding);
        response.setCharacterEncoding(encoding);
        chain.doFilter(request,response);
    }

    @Override
    public void destroy(a) {}}Copy the code
 <! -- Configure a garbled Filter for the POST request mode -->
  <filter>
    <filter-name>charset</filter-name>
    <filter-class>com.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>

  <filter-mapping>
    <filter-name>charset</filter-name>
    <url-pattern>/ *</url-pattern>
  </filter-mapping>
Copy the code

2.5.2.2. Use CharacterEncodingFilter to resolve POST Garbled requests


  <! -- Configure a garbled Filter for the POST request mode -->
  <filter>
    <filter-name>charset</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>charset</filter-name>
    <url-pattern>/ *</url-pattern>
  </filter-mapping>
Copy the code
package com.filter;

import javax.servlet.*;
import java.io.IOException;

// Customize the encoding filter
public class CharacterEncodingFilter  implements Filter {

    private String encoding;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.encoding = filterConfig.getInitParameter("encoding");
        System.out.println(encoding);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding(encoding);
        response.setCharacterEncoding(encoding);
        chain.doFilter(request,response);
    }

    @Override
    public void destroy(a) {}}Copy the code

2.6 data transfer mechanism in SpringMVC

2.6.1 What is the data transmission mechanism

The data transfer mechanism mainly includes three problems:

  1. How is the data stored?
  2. How do I get data from a page?
  3. How should the data retrieved from the page be presented?

2.6.2 Data transfer mechanism of Servlets

In the previous Servlet development, we generally put the data into the scope (Request, session, Application), if the data is a single directly using EL expression in front of the display, if it is a collection or array, can use EL expression ➕JSTL tag after traversal in front of the display.

Three, front controller

3.1. What is the front Controller

There is a Front Controller in the MVC framework, and an entry Controller is set in the Front of the WEB application, which is used to provide a centralized request processing mechanism. All requests are sent to the Controller for unified processing, and then the request is distributed to the corresponding handler. Generally used to do a common process, such as permission checking, authorization, logging, etc. Improved reusability and scalability because of the ability to centrally process requests controlled by the front end.

In the absence of a front controller, this is how we pass and process requests.

With the front controller, this is what we became.

3.2 Code implementation

Spring MVC already provides a DispatcherServlet class as the front-end controller, so to use Spring MVC you must configure the front-end controller in web.xml.


      
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0">
  <! -- Spring MVC Front-end Controller -->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-
      class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <! -- specify the configuration file that the Spring container starts loading -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:mvc.xml</param-value>
    </init-param>
    <! -- Initialization of Tomcat startup -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>
Copy the code

3.3, pay attention to

The load-on-startup element is optional: a value of 0 or greater means that the container builds the Servlet and calls its init method when the application starts (the smaller the non-negative value, the higher the priority for starting the Servlet). If the value is a negative number or is not specified, the Servlet is loaded on the first request. This allows SpringMVC initialization to be done when the container starts, rather than being left to a user request, improving user experience.

3.4 mapping path

The mapping path of the front controller can be configured in the following three ways:

  1. Configurations such as.do and.htm are the most traditional and allow access to static files (images, JS, CSS, etc.), but do not support RESTful styles.
  2. If/is configured, the popular RESTful style is supported, but static files (such as images, JS, and CSS) are blocked and cannot be accessed.
  3. /* is the wrong way to make a request to the Controller, but the jump to the JSP will be blocked, the JSP view will not be rendered, and the static resources will not be accessed.

3.4.1 Why static resources and JSPS are intercepted

Tomcat container handling static resource is assigned to the built-in DefaultServlet (intercepted) path is/processing, processing JSP resources are processed by the built-in JspServlet (intercept path is *. JSP | *. JSPX). When you start the project, you load the container's web.xml first and then the project's web.xml. When the interception path is the same in both files, the former will be overwritten. So all static resources with the interception path/configured by the front controller are processed by the front controller, and all static resources and JSPS with the interception path /* configured by the front controller are processed by the front controller.Copy the code

3.4.2 How to Solve the problem

3.4.2.1 Method 1

In web.xml, change the mapping path of the front controller to *.do, but note that the request path must carry.do when accessing the processing method in the controller.

<servlet-mapping>
	<servlet-name>dispatcherServlet</servlet-name>
	<url-pattern>*.do</url-pattern>
</servlet-mapping>	
Copy the code

3.4.2.2 Method 2

In MVC. Add a XML configuration, the configuration will be deposit in Spring MVC context to create a DefaultServletHttpRequestHandler bean, it will enter the DispatcherServlet request for screening, If it is not a mapped request, it is referred to the container’s default Servlet.

<mvc:default-servlet-handler/>
Copy the code

3.5,@ModelAttributeannotations

The object in the parameter (which must be a custom type) will be stored in the Model by default with the name of the argument’s class in lowercase. Sometimes this class is too long, but we need it, for example: the echo of the query condition. We just add @ModelAttribute to the front of our custom class and write the name of the key we want to change.

package cn.wolfcode.web.controller;
	@Controller
	public class RequestController {
		@RequestMapping("/req7")
			public String resp7(@ModelAttribute("u") User user) {
			return "m"; }}Copy the code

Fourth, processing response

The purpose of SpringMVC is to request and process the response. Response processing refers to how to write the processing method in the controller to accept the request and respond, find the view file and store the data into the scope. To process the method to do the response, typically the type returned by the processing method is ModelAndView and String.

4.1. Return ModelAndView

Method returns a ModelAndView object that sets the model data and specifies the view. The front end is still using JSTL+CgLib for the value. He has two common methods:

  1. addObject(String key, Object value): Sets the key and value of the shared data.
  2. addObject(Object value): Sets the value of the shared data. The key must start with a lowercase letter of the value type.
package cn.linstudy.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class ResponseController {
  // Provide the method to handle the request, localhost/resp1
  @RequestMapping("/resp1")
  public ModelAndView resp1(a) {
// By creating this class object, we tell Spring MVC what view file to look for and what data to store in the scope or model
    ModelAndView mv = new ModelAndView();
// Store data to the scope or model
    mv.addObject("msg"."Method return type is ModelAndView");
/ / find the view
    mv.setViewName("/WEB-INF/views/resp.jsp");
    return mv;
  }
Copy the code

4.2. Mandatory String

Mandatory String (widely used). If we need to share data, we need to use an HttpServlet object. Spring encapsulates an object: Model. Used in combination to store data into a scope or model.

package cn.instudy.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ResponseController {
  // Provide the method to handle the request, localhost/resp2
  @RequestMapping("/resp2")
  public String resp2(Model model) {
// Store data to the scope or model
    model.addAttribute("msg"."Method return type is String");
// Return the name of the view
    return "/WEB-INF/views/resp.jsp"; }}Copy the code

4.3, the improvement

We will find that if we need to write back to the interface and we need to write prefixes and suffixes, we need to eliminate the prefixes and suffixes of the view, we just need to configure the view resolver in Spring.

<! The path to the Spring MVC view is: prefix + logical view name (handle method Settings or return view name) + suffix -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	<! -- View prefix -->
	<property name="prefix" value="/WEB-INF/views/"/>
	<! -- View suffix -->
	<property name="suffix" value=".jsp"/>
</bean>
Copy the code

Request forwarding and redirection

5.1 The difference between request forwarding and redirection

A few times requests The address bar WEB resources – INF Share request data Whether the form is submitted repeatedly
Forward requests 1 time Don’t change You can visit Can be Shared There are
redirect Many times change inaccessible Do not share There is no

5.2 Request forwarding

Combined with forward keywords, said forward requests, be equivalent to the request. GetRequestDispatcher (). The forward (request, response), forwarding the browser address bar is changeless, after before sharing data in a request. With the keyword added, the configured view resolver does not work. The full path must be written if the view is returned

package cn.linstudy.web.controller;
@Controller
public class ResponseController {

	@RequestMapping("/TestForward")
	public String forward(a) {
		return "forward:/WEB-INF/views/welcome.jsp"; }}Copy the code

5.3 redirection

The keyword “redirect” is added to indicate redirection, which is equivalent to Response.sendredirect (). After redirection, the browser address bar changes to the redirected address, and the data previously requested is not shared.

package cn.linstudy.web.controller;
@Controller
public class ResponseController {
	// localhost/r
	@RequestMapping("/TestRedirect")
	public String redirect(a) {
		return "redirect:/static/demo.html"; }}Copy the code

5.4. Request path

For request forwarding and redirection, there are two ways to write the request path:

  1. add/: The use of the absolute path (recommended), from the project root path. (/response/test6 —> “redirect:/hello.html” —> localhost:/hello.html)
  2. Do not add/: Use a relative path, one level above the last accessed context path. (/response/test6 —> “redirect:hello.html” —> localhost:/response/hello.html)

Vi. Parameter processing

Handle simple type request parameters

How do we get the parameters of the simple data type in the request in the controller? Simple data types contain the basic data types and their wrapper classes, as well as parameter receptances such as String and BigDecimal.

6.1.1 The request parameter name is the same as the controller method parameter list parameter

If the name of the argument passed by the foreground is the same as the name of the parameter in the parameter list of the controller method, there is no need to do anything, SpringMVC will automatically do the assignment for us.

 // The request path is: /req1? username=zs&age=18
package cn.linstudy.web.controller;
	@Controller
	public class RequestController {
		@RequestMapping("/req1")
		public ModelAndView resp1(String username, int age) {
			System.out.println(username);
			System.out.println(age);
			return null; }}Copy the code

6.1.2 Request parameter name and controller method parameter list parameter have different names

We need to use an annotation @requestparam (” parameter names carried in the foreground “) to tell SpringMVC to assign any value to the data if the parameter names passed in the foreground are different from the parameter names in the parameter list in the controller method.

 // The request path is: /req1? username=zs&age=18
package cn.linstudy.web.controller;
	@Controller
	public class RequestController {
		@RequestMapping("/req1")
		public ModelAndView resp1(@RequestParam("username") String username1, @RequestParam("age") int age1) {
			System.out.println(username);
			System.out.println(age);
			return null; }}Copy the code

Handle complex type request parameters

6.2.1 Array types

For array type parameters, we simply define an array type of the same name in the parameter list of the method parameter to receive.

// Request path /req3? ids=1&ids=2&ids=3
package cn.linstudy.web.controller;
	@Controller
	public class RequestController {
		@RequestMapping("/req3")
		public ModelAndView resp3(Long[] ids) {
			System.out.println(Arrays.toString(ids));
			return null; }}Copy the code

6.2.2 Custom Type

Many times, we need to receive an object of a custom type. We, for example, have a need to transfer at the front desk to save the user’s data is encapsulated into a custom user type, so this time, only need to make sure that the type of the custom field and pass the front field in the same (note the transfer parameter, consistent with the attributes of the object encapsulation name), for SpringMVC can encapsulate automatically.

// /req4? username=hehe&password=666
package cn.linstudy.web.controller;	
	@Controller
	public class RequestController {
		@RequestMapping("/req4")
		public ModelAndView resp4(User user) {
			System.out.println(user);
			return null}}Copy the code

The underlying SpringMVC calls the processing method according to the request address. When the method is called, it finds that the argument of User type needs to be passed. SpringMVC creates the User object by reflection, then finds the corresponding property by the request parameter name, and sets the corresponding parameter value for the property of the object.

6.3 Processing date type request parameters

6.3.1 Date on the request parameter

If the Date is on the request parameter, then we need to attach the @dateTimeFormat annotation to the parameter of type Date of the processing method.

package cn.linstudy.controller;
	@Controller
	public class RequestController {
		@RequestMapping("/req5")
		// Note that the parameter is of type java.util.date
		public ModelAndView resp5(@DateTimeFormat(pattern="yyyy-MM-dd")Date date) {
			System.out.println(date.toLocaleString());
			return null; }}Copy the code

6.3.2. On encapsulated objects

If the date is in a field of the enclosing object, then we need to post a @dateTimeFormat annotation on the field.

package cn.linstudy.domain;
	public class User {
	private Long id;
	private String Username;
	private String password;
	// Add the following field and annotate it
	@DateTimeFormat(pattern="yyyy-MM-dd")
	private Date date;
	// Omit the setter, getter toString
}
Copy the code
	package cn.linstudy.controller;
	@Controller
	public class RequestController {
		@RequestMapping("/req6")
		public ModelAndView resp6(User user) {
			System.out.println(user);
			return null; }}Copy the code

7. File upload and download

7.1 File upload

Go back to using Servlet3.0 to solve the file upload problem, write upload forms (POST, multipart/form-data), and write the code to parse the uploaded file in the doPost processing method. But in SpringMVC can help us simplify the file upload steps and code.

7.1.1. Write forms

Notice The request data type must be Multipart /form-data and the request mode must be POST.

<! DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> File upload </title> </head> <body> <form action="/upload" method="POST" enctype="multipart/form-data"> File :<input type="file" name="pic"><br>
		<input type="submit" value="Submit"/>
	</form>
</body>
</html>
Copy the code

7.1.2. Modify web.xml

We can specify the size of the uploaded file in web.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:mvc.xml</param-value>
	</init-param>
	<load-on-startup< / a > 1load-on-startup>
	<multipart-config>
		<max-file-size> 52428800 < /max-file-size>
		<max-request-size> 52428800 < /max-request-size>
	</multipart-config>
</servlet>
<servlet-mapping>
	<servlet-name>dispatcherServlet</servlet-name>
	<url-pattern>/</url-pattern>
</servlet-mapping>
Copy the code

7.1.3. Configure the upload parser

Configure the upload parser in mVC.xml. To receive a client upload file using springMVC’s multipartFile, you must configure the file upload parser and parse the file id to be multipartResolver

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  <! -- control file upload size in bytes
  <property name="maxUploadSize" value="2097152"/>
</bean>
Copy the code

7.1.4 Configuring the upload controller

package cn.linstudy.controller;
	@Controller
	public class UploadController {
	// The Spring container has an object of type ServletContext, so define a field of type ServletContext and post the @autowired annotation to get it
	@Autowired
	private ServletContext servletContext;
	@RequestMapping("/upload")
	public ModelAndView upload(Part pic) throws Exception {
		System.out.println(pic.getContentType()); // File type
		System.out.println(pic.getName()); // File parameter name
		System.out.println(pic.getSize()); // File size
		System.out.println(pic.getInputStream()); // File input stream
		// Filecopyutils.copy (in, out), a copy method provided by Spring
		// Obtain the absolute path of the uploadDir directory under the webapp directory of the project
		System.out.println(servletContext.getRealPath("/uploadDir"));
		return null; }}Copy the code

7.2 File download

File download: The process of downloading a file from the server to the computer that the current user is accessing is called file download

7.2.1 Develop controller

The response header must be set when downloading, specifying how the file will be saved, and the controller for downloading the file must not have a return value, indicating that the response is only for downloading the file information

	/** * test file download *@paramFileName Indicates the name of the file to be downloaded@return* /
    @RequestMapping("download")
    public String download(String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
        // Obtain the absolute path of the file on the download server
        String realPath = request.getSession().getServletContext().getRealPath("/down");
        // Obtain the specified file name from the service
        FileInputStream is = new FileInputStream(new File(realPath, fileName));
        // Get the response object and set the response header
        response.setHeader("content-disposition"."attachment; fileName="+ URLEncoder.encode(fileName,"UTF-8"));
        ServletOutputStream os = response.getOutputStream();
        IOUtils.copy(is,os);
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
        return null;
    }
Copy the code