Introduction to SpringMVC

1.1 Introduction to SpringMVC

In order to provide Spring with pluggable MVC architecture,Spring Framework develops SpringMVC framework on the basis of Spring, so that Spring’s SpringMVC framework can be used as the controller framework for WEB development when using Spring for WEB development.

1.2. Advantages of SpringMVC

SpringMVC is a typical lightweight MVC framework that acts as a controller framework in the overall MVC architecture. Compared to the previous Struts2 framework,SpringMVC is faster and its annotated development is more efficient and flexible.

  1. Seamless integration with the Spring framework.
  2. Much more efficient than the Struts2 framework.
  3. Annotated development is more efficient.

Getting started with SpringMVC

2.1. Environment construction

2.1.1. Introduce dependencies

Rely on ignored, I put in the comments section!

2.1.2. Write configuration files

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

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

2.1.3. Configure 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>

<! Configure the core servlet of SpringMVC
  <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>
<! -- Intercept all requests -->
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>1.23.4.. 56.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23..
Copy the code

2.1.4. Write 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
 * @date 2021/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 classes and methods. It does the following: 1. 2. On a class, you can add a unified request path to all methods in the class, which must be preceded by */
  @RequestMapping("/hello")
  public String hello(String username,String password){
    System.out.println("hello");
    return "index"; }}1.23.4.. 56.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31..
Copy the code

2.2 detailed explanation of notes

2.2.1, @ Controller

This annotation identifies this as a controller component class on the class and creates an instance of this class, telling Spring I’m 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

There are two traditional Servlet development jumps:

  1. Forward: Indicates that the forward forward forward is a request within the server. The address bar remains unchanged. Jumps can carry data to pass (using the Request scope).
  2. Redirect: A redirect is a client redirect. Therefore, the address bar changes after multiple redirect requests. Data cannot be transferred during redirect requests.

2.3.1 Controller — > Foreground page

2.3.1.1, forward

By testing, we can find that SpringMVC by default uses request forwarding to jump to the foreground page;

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

  @RequestMapping("test")
  public String test(){
    System.out.println("test");
    return"index"; }}1.23.4.. 56.7.8.9.10..
Copy the code
2.3.1.2, redirect

If we want to redirect using a redirect, we need to use the SpringMVC keyword redirect: to do this.

Syntax: return “redirect:/ view full path name “;

** Note: ** is not the logical name that follows the redirect: page, it is the full path name. Because the redirect does not go through the view resolver.

2.3.1 Controller – > Controller

2.3.1.1, forward

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

Syntax: return:” Forward: / @requestMapping value of the class to be jumped / @requestMapping value of the method to be jumped;”

2.3.1.2, redirect

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

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

2.4 SpringMVC parameter reception

2.4.1. How the Servlet receives parameters

In traditional Servlet development, this is how we typically receive request parameters.

// Receive the parameter named name
request.getParameter(name)1.2.
Copy the code

He has a few caveats:

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

2.4.2 Receiving SpringMVC parameters

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

  1. Simplify the way parameters are received (no methods need to be called, just provide whatever parameters are needed in the controller method).
  2. Parameter types do not need to be converted by themselves. Date and time (default yyyy/MM/ DD) Note that the @datetimeFormat annotation is required to declare the format to be followed for date conversion, otherwise 400 is raised.
2.4.2.1 Basic data types

Automatic assignment can be completed only if the key of the passed parameter is the same as the parameter name of the corresponding method.

2.4.2.2 Object types

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

2.4.2.3 Array types

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

2.4.2.4. Set types

SpringMVC cannot receive arguments of a collection type directly as a formal argument list. To receive arguments of a collection type, SpringMVC must put the collection into an object and provide get/set methods. It is recommended to encapsulate it in a VO object and use the object type for receiving.

2.5. SpringMVC receives parameters with Chinese garbled characters

2.5.1 GET Request

Garbled characters in GET request mode need to be discussed according to Tomcat version:

  1. Before tomcat8.x: Use URIEncoding=”ISO-8859-1″ in server. XML by default, instead of “UTF-8”, resulting in Chinese garbled characters.
  2. Later versions of tomcat8.x: Use URIEncoding=”UTF-8″ in server. XML by default, so Chinese garbled characters will not occur.

2.5.2 POST Requests

By default, SpringMVC does not encode any POST requests, so any version receiving a POST request directly will have Chinese garbled characters.

2.5.2.1 User-defined Filters Resolve POST garbled requests

In the Servlet phase, we learned about filters, and we can customize filters to do filtering encoding.

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(){}}1.23.4.. 56.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27..
Copy the code
<! Filter--><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>1.23.4.. 56.7.8.9.10.11.12.13.14..
Copy the code
2.5.2.2 Use CharacterEncodingFilter to resolve the POST garbled character request
<! Filter--><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>1.23.4.. 56.7.8.9.10.11.12.13.14.15..
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(){}}1.23.4.. 56.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27..
Copy the code

2.6 Data transfer mechanism in SpringMVC

2.6.1 What is the data transmission mechanism

The data transfer mechanism mainly contains three problems:

  1. How is data stored?
  2. How do I get data in a page?
  3. How should the data captured on the page be presented?

2.6.2 Data transmission mechanism of Servlet

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

Three, front-end controller

3.1. What is front-end controller

There is a front-end Controller in MVC framework. An entry Controller is set in the Front of WEB application to provide a centralized request processing mechanism. All requests are sent to the Controller for unified processing, and then the requests are distributed to their respective handlers. Generally used for a common process, such as permission checking, authorization, logging, etc. Because of the front-end control’s ability to centrally process requests, it improves reusability and extensibility.

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

With the front controller, we’re like this.

3.2 code implementation

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

<? xml version="1.0" encoding="UTF-8"? ><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>
    <! Spring container loaded configuration file -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:mvc.xml</param-value>
    </init-param>
    <! -- Tomcat startup initialization -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>1.23.4.. 56.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24..
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 when the application starts and calls its init method to initialize it (the smaller the non-negative value, the higher the priority for starting the Servlet). If the value is negative or not specified, the Servlet is loaded on the first request. When configured, SpringMVC initialization can be done at container startup time instead of leaving it to the user to request, improving user experience.

3.4. Mapping paths

The mapping path of a front-end controller can be configured in the following three modes:

  1. Configurations such as.do and.htm are the most traditional way to access static files (images, JS, CSS, etc.), but do not support RESTful style.
  2. If the value is set to /, the popular RESTful style can be supported, but static files (images, JS, CSS, etc.) cannot be accessed after being blocked.
  3. /* is the wrong way to request to Controller, but the jump to JSP is blocked, JSP view cannot render, and static resources cannot be accessed.

3.4.1 Why access to static resources and JSP are blocked

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 starting a project, load the container's web.xml first, and then load the web.xml in the project. If the interception path is configured the same in both files, the former will be overwritten later. So the front controller configuration intercepts the path of/and all the static resources go to the front controller and intercepts the path configuration/*, all static resources and JSPS are handled by the front-end controller. 1.2.3.Copy the code

3.4.2 How to solve the problem

3.4.2.1 Method 1

In web. XML, modify the mapping path of the front-end 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>	1.23.4..
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, the request is processed by the container’s default Servlet.

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

3.5. @modelAttribute Annotations

The object in the parameter (which must be a custom type) will be stored in the Model by default by SpringMVC. The name of the parameter will be lowercase. Sometimes the class will be very long, but we have a need for it, such as the echo of the query condition. We just need to prefix the custom class with @modelAttribute 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"; }}1.23.4.. 56.7.8..
Copy the code

Processing response

What SpringMVC does is it requests and handles responses, and response handling is how you write the handler in your controller to accept requests and respond to them, find view files and put data into scope. To process a method, you need to respond, and typically the method returns type ModelAndView and String.

4.1. Return to ModelAndView

Method, which sets the model data and specifies the view. The front end still uses JSTL+CgLib for value. He has two common methods:

  1. AddObject (String Key, Object Value) : Sets the key and value of shared data.
  2. AddObject (Object Value) : Sets the value of the shared data. The key is lowercase.
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 methods to handle requests, localhost/resp1
  @RequestMapping("/resp1")
  public ModelAndView resp1() {
// By creating this class object, tell Spring MVC what view file to look for and what data to put into the scope or model
    ModelAndView mv = new ModelAndView();
// Store data to scope or model
    mv.addObject("msg"."Method return type is ModelAndView");
/ / find the view
    mv.setViewName("/WEB-INF/views/resp.jsp");
    return mv;
  }1.23.4.. 56.7.8.9.10.11.12.13.14.15.16.17.18.19..
Copy the code

4.2. Mandatory String

Return String (widely used). In this case, if we need to share data, we need to use HttpServlet objects. Spring encapsulates an object for us: Model. Use it 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 methods to handle requests, localhost/resp2
  @RequestMapping("/resp2")
  public String resp2(Model model) {
// Store data to scope or model
    model.addAttribute("msg"."Method return type is String");
// Returns the view name
    return "/WEB-INF/views/resp.jsp"; }}1.23.4.. 56.7.8.9.10.11.12.13.14.15.16.17..
Copy the code

4.3, the improvement

We’ll find that if we need to write back to the interface we’ll need to keep writing prefixes and suffixes, and we’ll need to eliminate view prefixes and suffixes. We just need to configure the view parser in Spring.

<! Configure the path for Spring MVC to find a view: prefix + logical view name (handle method setting or return view name) + suffix name --><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>1.23.4.. 56.7.8.9..
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 Sharing 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. After the keyword is added, the configured view parser is useless. 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() {
		return "forward:/WEB-INF/views/welcome.jsp"; }}1.23.4.. 56.7.8.9..
Copy the code

5.3 redirection

Redirect(response.sendreDirect ()) : After the redirect, the browser address bar becomes the redirected address and the requested data is not shared.

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

5.4 Request path

When forwarding and redirecting requests, there are two ways to write the request path:

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

6. Parameter processing

6.1. Handle request parameters of simple types

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

6.1.1. The request parameter name has the same name as the controller method parameter list parameter

If the parameter name passed from the foreground is the same as the parameter name of the parameter list in 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; }}1.23.4.. 56.7.8.9.10.11..
Copy the code

6.1.2 Request parameter name and controller method parameter list parameter name are different

If the parameter name passed by the foreground is not the same as the parameter name in the controller method’s parameter list, we need to use an annotation @requestParam (” the parameter name carried by the foreground “) to tell SpringMVC that we are assigning any value to the data.

 // 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; }}1.23.4.. 56.7.8.9.10.11..
Copy the code

6.2. Handle request parameters of complex types

6.2.1. Array types

For array type parameters, we simply define an array type with 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; }}1.23.4.. 56.7.8.9.10..
Copy the code

6.2.2 custom types

Most of the time, 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}}1.23.4.. 56.7.8.9.10..
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 type User needs to be passed. SpringMVC creates the User object by reflection, and then finds the corresponding attribute by the request parameter name, and sets the corresponding parameter value for the attribute of the object.

6.3. Process request parameters of date type

6.3.1 The date is on the request parameters

If the Date is on the request parameter, we need to annotate the @datetimeFormat parameter of the Date type in the processing method.

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

6.3.2. On encapsulated objects

If the date encapsulates an object’s field, we need to annotate the field with @dateTimeFormat.

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
}1.23.4.. 56.7.8.9.10..
Copy the code
	package cn.linstudy.controller;
	@Controller
	public class RequestController {
		@RequestMapping("/req6")
		public ModelAndView resp6(User user) {
			System.out.println(user);
			return null; }}1.23.4.. 56.7.8.9..
Copy the code

7. File upload and download

7.1 File upload

Review previous use of Servlet3.0 to solve file upload problems, write upload forms (POST, multipart/form-data), and write code to parse uploaded files in doPost. But SpringMVC can help simplify the steps and code of file uploading.

7.1.1. Write a form

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> </head> <body> <form action="/upload" Method ="POST" encType ="multipart/form-data"> <input type="file" name=" PIC "><br> < / form > < / body > < / HTML > 1.2.3.4.5.6.7.8.9.10.11.12.13.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>1</load-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>1.23.4.. 56.7.8.9.10.11.12.13.14.15.16.17..
Copy the code

7.1.3. Configure an upload resolver

Configure the upload parser in mVC.xml. The file uploaded by the client using springMVC multipartFile must be configured with the file upload parser and the resolved ID must be multipartResolver

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <! -- Control file upload size unit of byte default no size limit here is2-->
  <property name="maxUploadSize" value="2097152"/>
</bean>1.23.4..
Copy the code

7.1.4. Configure the Upload Controller

package cn.linstudy.controller;
	@Controller
	public class UploadController {
	// The Spring container has objects of type ServletContext, so you can get them by defining a ServletContext field with the @autowired annotation
	@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 spring-provided copy method
		// Get the absolute path to the uploadDir directory under the project webApp directory
		System.out.println(servletContext.getRealPath("/uploadDir"));
		return null; }}1.23.4.. 56.7.8.9.10.11.12.13.14.15.16.17.18..
Copy the code

7.2 file Download

File download: The process of downloading files from the server to the computer accessed by the current user is called file download

7.2.1. Controller development

Download must set the response header information, specify how to save the file, in addition to the download file controller cannot have a return value, representing the response only to download file information ‘

copy

	/** * Test file download *@param FileName specifies the fileName to download@return* /
    @RequestMapping("download")
    public String download(String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
        // Get the absolute path to the file on the download server
        String realPath = request.getSession().getServletContext().getRealPath("/down");
        // Get the specified file on the service based on the file name
        FileInputStream is = new FileInputStream(new File(realPath, fileName));
        // Get the response header information for the response object
        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