For SpringMVC overview

SpringWebMVC is a Web end framework constructed on the basis of ServletAPI. It is used for presentation layer development. By separating Model, View and Controller layers, the more complex Web applications are divided into three logical parts, making Web development easier.

1. The MVC model

The full name of MVC is Model View Controller, which is the abbreviation of Model, View and Controller. It is a Model of software design. It organizes the code by separating the three modes of business logic, data and interface, and gathers the business logic into one Model. There is no need to rewrite business logic while improving and customizing interfaces and user interactions. MVC has been uniquely developed to map traditional input, processing, and output functions in a logical graphical user interface structure. — From Baidu Encyclopedia

  • view

    A view is an interface that users see and interact with. For older Web applications, a view was an interface composed of HTML elements. In modern Web applications, HTML still plays an important role in the view.

  • model

    A model represents an object that accesses data or a Java POJO class that encapsulates data related to the application’s business logic and how it is processed.

  • The controller

    The controller is used to receive input from the user and invoke models and views to fulfill the user’s requirements. When a hyperlink in a Web page is clicked and an HTML form is sent, the controller itself does nothing and does nothing. It is simply responsible for receiving the request, deciding which model artifact to call to process the request, and then deciding which view to use to display the returned data.

— Image from Google

2. Front-end controller idea

The Front Controller Pattern is used to provide a centralized request processing mechanism where all requests are handled by a single handler. The handler can do authentication/authorization/logging, or trace requests and pass them to the appropriate handler. The following are the entities of this design pattern.

  • A Front Controller handles a single handler for all types of requests from an application, which can be either web-based or desktop-based.
  • A front-end controller may use a Dispatcher object to schedule requests to specific handlers, responsible for jumping between pages.
  • A View is an object created for the request.

3.SpringMVC quick start

3.1 Code Implementation

The following is a quick demonstration project based on Hello,World program, through SpringMVC technology to achieve a simple web page output string function.

3.2 Creating a Maven project and importing dependencies

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.2.8. RELEASE</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.0</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>
</dependencies>
Copy the code

To configure a Web project, right-click the project and click Add FrameWork Support to Add webApplication Support

3.3 configuration web. XML

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <display-name>Archetype Created Web Application</display-name>

    <servlet>
        <! -- Configure front-end controller Servlet -->
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <! -- Map spring configuration file under resources path -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        
        <! The object that configured the servlet was created when the application was loaded. The value must be a non-0 positive integer, indicating the boot sequence ->
        <load-on-startup>1</load-on-startup>
    </servlet>
    
    <! -- servlet-name needs to correspond to the name of the front-end controller configured above, / means match all requests (excluding.jsp files) /* means match all requests (including.jsp files) -->
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>
Copy the code

When configuring the web. XML file, you need to import the header file first. When configuring the DispatcherServlet of the front-end controller, you need to map the name and matching path, that is, the content in
. The
parameter represents the contents of the mapping Spring configuration file.

3.4 Creating a Controller A Controller

In the Web phase, servlets are usually used as the controller of web pages, but in SpringMVC, it is only necessary to write simple Java classes with a few simple annotations or configurations to complete the function of request and forward.

public class IndexController implements Controller {

    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        // Create model and view objects and add a view named Hello to the constructor
        ModelAndView mv = new ModelAndView("hello");
        // Add attribute values by key
        mv.addObject("message"."Hello,World");
        returnmv; }}Copy the code

The Controller interface overrides the handleRequest method to make an interaction with the web page, using the ModelAndView object to set the forward view and attribute values, and returns this object.

3.5 Configuring the Spring File

In order to truly use SpringMVC technology to implement the operation of web pages, we also need the support of springIOC technology. The components in SpringMVC are registered in the Spring bean container. While the InternalResourceViewResolver object is implemented page jump support functions.

<beans xmlns="http://www.springframework.org/schema/beans"
       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">

    <! The bean that registers the view parser object must have the support of the view parser to jump to the page.
    <bean id="ViewResolver" 	class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <! -- prefix indicates the mapping packet prefix name -->
        <property name="prefix" value="/WEB-INF/pages/"/>
        <! -- suffix stands for mapping suffix names, configure.jsp files -->
        <property name="suffix" value=".jsp"/>
    </bean>
    <! Register the IndexController class into the container with the id of the hello path for page access -->
    <bean id="/hello" class="com.springmvc.controller.IndexController"/>
</beans>
Copy the code

3.6 Creating a JSP view page

Since the view file path was specified in the Spring configuration file above, you need to create the Pages package in web-INF to create JSP view files that can be parsed by the view parser. Create the hello.jsp file

<%@ page contentType="text/html; charset=UTF-8" language="java"%> <html> <head> <title>Title</title> </head> <body> <! -- Prints the key set in the model view object, and gets the value of the object based on the key. --> ${message} </body> </html>Copy the code

3.7 configurationTomcatStart project testing

Click Edit Configurations to enter the configuration screen, and then specify the Local Tomcat path by clicking the + Tomcat Server > Local >Application Server. Then click on the Depolyment add Artifacts module.

Run Tomcat visit http://localhost:8080/hello to see the results

The above quick start code is to set the view and property values through ModelAndView and register the bean’s components in the Spring container. This method is a bit more cumbersome than the annotation method because the Controller interface is implemented every time. And register a bean component for each method in the Spring container. The following is a way to improve this phenomenon through annotations.

3.7.1 Modifying the Spring Configuration File

Using annotations requires importing additional XML header support, so let’s add the MVC context property.

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       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">
      <! Turn on support for annotations -->
    <mvc:annotation-driven/>

    <! -- Automatic scan Controller package -->
    <context:component-scan base-package="com.springmvc.controller"/>

    <! Register the bean of the view parser object -->
    <bean id="InternalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <! -- prefix indicates the package prefix name -->
        <property name="prefix" value="/WEB-INF/pages/"/>
        <! -- suffix stands for suffix name, configure.jsp file -->
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>
Copy the code

3.7.2 Creating a Controller Class

HelloController uses @Controller to indicate that this is a component of the control layer and inject it into the Spring container, and @requestMapping to set the access path. Comment these two annotations to the class and method respectively. Request forwarding and attribute setting can be realized between web pages.

@Controller
public class HelloController {

    @RequestMapping("/hello") // Set the access path to /hello
    public String hello(Model model) {
        model.addAttribute("hello"."Hello,World");

        return "hello"; // Return to the hello.jsp view}}Copy the code

3.7.3 Output hello. JSP file test

Use the EL expression to output the property key set by the Controller layer to get the value of the property set.

<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${hello}
</body>
</html>
Copy the code

Start the Tomcat server to http://localhost:8080/hello

Test results:

@ RequestMapping annotations

The request path configured in the second way above is implemented through the @RequestMapping annotation, which can be used to map the request path to controller methods, as well as above the class.

Source:

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping {
	/** Assign a name */ to the mapping path
	String name(a) default "";

	/** Map url paths. You can fill in batches. The function is the same as that of path */
	@AliasFor("path")
	String[] value() default {};

	/** Map url path. You can batch fill in the url path. The function is the same as value */
	@AliasFor("value")
	String[] path() default {};

	/** Specifies the HTTP request method. By default, there are 8 */ methods
	RequestMethod[] method() default {};

	/** Mapping request parameters */
	String[] params() default {};

	/** The mapping request header */
	String[] headers() default {};

	/** Narrow down the mapping */
	String[] consumes() default {};

	/** Narrow the request mapping */
	String[] produces() default {};

}
Copy the code

RequestMapping has a core enumeration class. RequestMethod defines eight types of HTTP requests: GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, and TRACE. You can use this class to indicate what type of request to send.

4. For SpringMVC components

4.1 DisPatcherServlet: Front-end controller

DispatcherServlet is a Java class designed and implemented by SpringMVC around the front-end controller. Its main function is to use Spring configuration to control the flow between Web development, such as request mapping, view resolution, exception handling and so on… The main functions are as follows:

  1. multipartResolver: file parsing, used to process the file upload service
  2. localeResolver: Region resolution to handle application internationalization
  3. themeResolver: Topic resolution, defining topics that Web applications can use – for example, providing personalized layouts
  4. handlerMapping: Is used to handle the relationship between the application’s request and mapping
  5. handlerAdapter: Processing adapter, definitionDispatcherServletRequest processing rules for
  6. handlerExceptionResolver: a policy for resolving exceptions and exporting errors to logs
  7. viewNameTranslator: specifies the view name according to the definition of RequestToViewNameTranslators replaced with the specified format.
  8. viewResolver: View parsing, parsing logicString– The view-based name returned from the handler to the actual view nameViewFor rendering to the response
  9. Storage and retrievalFlashMapIt can be used to pass attributes from one request to another, usually across redirects.

5. Request data binding

Request.getparameter () is used to retrieve object request parameters in native servlets; Method, whereas in SpringMVC you only need to define a method and specify that the name of the method form parameter is the same as the name of the request parameter.

5.1 Data Types to be Bound

5.1.1 Basic Parameter Types

Basic data types correspond to eight Java data types: byte, short, int, Long, float, double, and Boolean. These can be used as parameters for data binding between web pages, but the parameter name passed in must be the same as the parameter name in the method, otherwise it will be null.

Let’s create a new RequestController to demonstrate.

Skip the web. XML and Spring configuration file steps configured above.

@Controller
public class RequestController {

    // Send a get request with the path set to user
    @GetMapping("/user")
    public void request(String name, int age, double money,boolean boo) { System.out.println(name); System.out.println(age); System.out.println(money); System.out.println(boo); }}Copy the code

We just created a normal no-return method, passing in four different data types of parameters in parentheses, and sending a Get request to set the access path to /user. We just need to print the corresponding parameter name in the browser address bar as a key-value pair to Get the bound value, and output it in the console.

Test: start the project at http://localhost:8080/user? Name =Trump&age=3& Money =1.2&boo=false, the path is followed by a question mark, the key is the attribute name, the value is added according to the data type, and multiple key-value pairs are separated by ampersand

The reason for 404 is that the method controller is of a type with no return value and does not specify the view to return, just prints the output on the console.

5.1.2 POJO Type Parameters

An object class is passed in parentheses, depending on the name of the field in the object, but the attribute name is specified and assigned, otherwise null.

Create User ↓

@Data
public class User {
    private Long userId;
    private String username;
    private String password;
}
Copy the code

Create a new method in the RequestController and pass in the User object

@Controller
public class RequestController {
    
    @GetMapping("/user")
    public void requestUser(User user) { // Pass in the User objectSystem.out.println(user); }}Copy the code

Open a browser in the address bar to access the test at http://localhost:8080/user? userId=1&username=Bear&password=123456

The test results

5.1.3 Array & Collection type parameters

Parameters are passed through array [] and collection types, which are available only in objects.

Modify the User class

@Data
public class User {
    private Long userId;
    private String username;
    private String password;

    private String arr[];

    List<String> list;
}
Copy the code

Add an array type and a List collection type to the User class, passing values by variable names.

The Controller test method remains the same

@GetMapping("/user")
public void requestUser(User user) {
    System.out.println(user);
}
Copy the code

Testing:

Start the project to set parameters and visit http://localhost:8080/user? List =list1,list2&arr= arR1, ARR2, collection and array multiple parameter value Settings are comma separated into multiple values.

Console print results

5.1.4 ensuring @ RequestParam annotation

You can use this annotation to bind parameters in a method by specifying a new name as the parameter’s name, and the annotation can be annotated into method parameters.

Example: Create a new Get request method that binds two parameters

@GetMapping("/binding") // The request path is /binding
public void binding(@RequestParam(value = "name") String username,
                    @RequestParam("age") Integer age) {
    System.out.println(username); // Print output at the console
    System.out.println(age);
}
Copy the code

Start the project at this time to visit: http://localhost:8080/binding? Name =Bear&age=18 You can view the result on the path

If the @requestParam annotation is used to specify the name of the binding, the path must match the name of the binding, otherwise the following error will be reported.

If you want to specify one of the corresponding parameters, you can use the required = false parameter, which means that the path does not have to contain this parameter.

@GetMapping("/binding")
public void binding(@RequestParam(value = "name",required = false) 
                    String username,
                    @RequestParam("age") Integer age) {
Copy the code

Can visit http://localhost:8080/binding? at this time Age =12 path, missing a String argument but still successful output, but username will be empty

5.2 Header annotations

5.2.1 RequestHeader

This annotation is used to map the information in the request header part to the parameters processed in the method.

The optional parameters for getting are as follows:

Host localhost:8080 Accept text/html,application/xhtml+xml,application/xml; Q = 0.9 Accept - Language fr, en - gb; Q = 0.7, en. Q =0.3 Accept-encoding gzip, Deflate Accept-Charset ISO-8859-1, UTF-8; Q = 0.7 *; Q = 0.7 Keep Alive - 300Copy the code

Example: Create a method that specifies two String parameters and binds the specified HTTP information parameters.

@GetMapping("/header")
public void RequestHeader(@RequestHeader(value = "host") String host,
                          @RequestHeader(value = "Accept") String accept) {
    System.out.println(host);
    System.out.println(accept);
}
Copy the code

Test: start the project at http://localhost:8080/header? Host&accept obtains the local address port number and the data type accepted by the browser

5.2.2 CookieValue

Binds the value of the HTTPcookie to the method parameter in the controller.

@GetMapping("/requestCookie")
public void handle(@CookieValue("JSESSIONID") String cookie) {
    System.out.println(cookie);
}
Copy the code

Go to http://localhost:8080/requestCookie? Cookie Address Displays the output cookie value.

The JSESSIONID attribute is obtained according to the Cookie name in the browser. You can press F12 in the browser to view all Cookies in the browser

5.3 ModelAttribute

The @modelAttribute annotation can be annotated within a method or method’s parameters to access other attributes, used for methods before controller execution, and used for parameters to call the contents of the specified method.

Modification methods

Example: Create two methods, one decorated with @ModelAttribute as a data provider and one for a normal GET request.

@ModelAttribute
public void model(String param){
    System.out.println(param);
}

@GetMapping(value = "/requestAttr")
public void attribute(a) {}
Copy the code

Test to http://localhost:8080/requestAttr? The param=hello,world address successfully assigns a value to the parameter param in the model method, which is called before the controller executes because of the @modelAttribute annotation.

Modify parameters

Modify the annotation invocation inside the parameter by using the @ModelAttribute annotation in both methods and specifying its name

@ModelAttribute(name = "attr")
public void model(a) {
    System.out.println("hello,world");
}

@GetMapping(value = "/requestAttr") // This annotation specifies the name of the annotation modified by the above method
public void attribute(@ModelAttribute(name = "addr") String param) {}
Copy the code

Next by visiting http://localhost:8080/requestAttr? Param address, which calls the content in the method modified by the @modelAttribute annotation.

5.4 SessionAttribute

The @sessionAttribute attribute can only be used in method parameters. The attribute is used to bind a specified parameter to the session field, and you can output the original parameter to obtain the stored session value.

Example: Create a method that uses the @sessionAttribute annotation to specify the name of the parameter and uses HttpSession to store the value in the parameter

@GetMapping("/session")
public void session(@SessionAttribute("name") String session, HttpSession httpSession) {
    httpSession.setAttribute("name"."hello,world");
    System.out.println(session); // Prints the parameters after binding the session value
}
Copy the code

Test visit: http://localhost:8080/session? The name address

The @sessionAttribute is used to bind a session string variable named name, and then add a session value to the name attribute using the HttpSession interface. And finally prints its string variable to output the bound session value.

5.5 a Restful request

5.5.1 Restful overview

Representational State Transfer is short for REST. An architectural style of software design designed to facilitate the communication between different software and programs over a network such as the Internet.

5.5.2 Restful Design Standards

REST is a design style, not a standard. REST is typically based on existing widely popular protocols and standards such as HTTP, URI, XML, and HTML.

  • Resources are specified by URIs.
  • Operations on resources include obtaining, creating, modifying, and deleting resources, which correspond to THE HTTP GET, POST, PUT, and DELETE methods respectively.
  • Manipulate a resource by manipulating its representation.
  • Resources are represented as XML or HTML, depending on whether the reader is a machine or a human, a client software consuming a Web service or a Web browser. Of course, it could be any other format, such as JSON. — From Wikipedia

5.5.3 @ PathVaribale

A RESTful program or design should satisfy the following conditions and constraints:

  • The requested URL needs to be normalized to make sure that no verbs appear in the URL, for example:get,add“, using nouns instead
  • Make full use of HTTP methods, including GET, POST, PUT, PATCH, and DELETE

@PathVaribale is an annotation provided by SpringMVC that can be used to bind parameters and make Restful requests

The following is a restful request based on simulated user parameter query.

Add a method to the Controller and add the @pathVariable annotation to map to the {} parameters in the path

@GetMapping("/users/{userId}")
public void requestQuery(@PathVariable(value = "userId") String uid) {
    System.out.println("Checked" + uid + "User number");
}
Copy the code

Visit http://localhost:8080/users/3 simulation testing path, said access to the users under the path of no. 3, the user

View console results:

5.6 @ ResponseBody

The @responseBody annotation is used to display data as a JSON string on a web page. This annotation can be added to types and methods

Example:

@GetMapping("/get")
@ResponseBody
public String response(a) {

    return "Hello,World";
}
Copy the code

Visit http://localhost:8080/get to see the results

6. Response data

Because the data needs to interact with the web page, it needs to access the data into a container, and then return the response to the web page to display the data. There are several ways to echo data in SpringMVC.

  1. useMapA collection of
  2. ModelInterface objects
  3. ModelMapInterface objects
  4. ModelAndViewobject
  5. session&requestThe domain

6.1 Return Value type

Different return value types have different functions. The following three types are different operations on controllers.

6.1.1 string

The string type can be returned as a view, or as a JSON string that can be changed according to business requirements.

The following is illustrated by returning to the view and using five data echo objects.

Add a method to the controller class.

@GetMapping("/data")
public String map(Map<String,String> map, Model model, ModelMap modelMap, HttpServletRequest request,HttpSession session) {
    map.put("map"."hello,world");
    model.addAttribute("model"."hello,fuckerTrump");
    modelMap.addAttribute("modelMap"."hello,teddy");
    request.setAttribute("request"."hello,bear");
    session.setAttribute("session"."hello,ted");
    return "hello";
}
Copy the code

Create a hello.jsp and use the $sign to render the data on the web page

<%@ page contentType="text/html; charset=UTF-8" language="java"%> < HTML > <head> <title> </title> </head> <body> ${ModelMap} request: ${requestScope. Request} <! Session render data: ${sessionscope.session} <! </body> </ HTML >Copy the code

Start the project visit: http://localhost:8080/data

It should be noted that Model and ModelMap objects have basically the same functions. The difference is that ModelMap object inherits LinkedHashMap, so it has all the right to use its methods, and has more operation space than Model object.

6.1.2 void Keyword

Void does not return any value and cannot return views or JSON strings.

@GetMapping("/void")
public void result(a) {
    System.out.println("this is void method");
}
Copy the code

Visit http://localhost:8080/void to see in the console print effect.

Also 6.1.3 ModelAndView

ModelAndView is an object provided by SpringMVC that sets property values and views.

@GetMapping("/model")
public ModelAndView modelAndView(a) {
    ModelAndView mv = new ModelAndView(); // Create an object
    mv.setViewName("hello"); // Set the return view to the name of Hello
    
    mv.addObject("msg"."ModelAndView"); // Set the property value
    return mv;
}
Copy the code

Use the key to render the value for display in the Hello.jsp page.

<%@ page contentType="text/html; charset=UTF-8" language="java"${MSG} </body> </ HTML > <head> <title> </title> </head> <body>Copy the code

6.2 Forwarding and Redirection

In request forwarding, the browser sends a request to the server and obtains a response once, also known as intra-server redirect. In addition, the request can only be forwarded to the internal resources of the current Web application, but not to other connections, such as www.baidu.com.

Redirection is to get several requests as many times as you send them to the server. It is called an external hop of the server, that is, a hop between pages, and no hop to pages carrying resources.

Bind a parameter with the Model object and send it to the specified page to display the data.

@GetMapping("/request")
public String request2(Model model) {
    model.addAttribute("message"."request2");
    return "hello";
}
Copy the code

The JSP page

<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${message}
</body>
</html>
Copy the code

The redirection method is to redirect the current page resources to other URL resources, such as the request to the http://www.baidu.com address.

@GetMapping("/redirect")
public String redirect(a) {

    return "redirect:http://www.baidu.com";
}
Copy the code

At this point to http://localhost:8080/redirect path will be turned to the baidu page

7. Upload files

Use the SpringMVC framework to achieve file upload function.

7.1 Code Implementation

Create a new project import dependency

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.2.9. RELEASE</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.3</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.0</version>
        <scope>provided</scope>
    </dependency>
</dependencies>
Copy the code

Configure the Web and Spring XML files

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       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">

    <! -- Enable annotation support -->
    <mvc:annotation-driven/>
    <context:component-scan base-package="com.springmvc.controller"/>

    <! Register the bean of the view parser object -->
    <bean id="InternalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <! -- prefix indicates the package prefix name -->
        <property name="prefix" value="/WEB-INF/pages/"/>
        <! -- suffix stands for suffix name, configure.jsp file -->
        <property name="suffix" value=".jsp"/>
    </bean>

    <! -- File upload configuration -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <! -- Set encoding format -->
        <property name="defaultEncoding" value="UTF-8"/>
        <! -- Upload file size limit, 10485760=10MB -->
        <property name="maxUploadSize" value="10485760"/>
        
        <property name="maxInMemorySize" value="40960"/>
    </bean>
</beans>

<! -- Web.xml configuration -->
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <display-name>Archetype Created Web Application</display-name>

    <servlet>
        <! -- Configure front-end controller 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>

        <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

Write the Controller file upload function

@RestController
public class FileController {

    @PostMapping("/upload")
    public String upload(@RequestParam(value = "file")CommonsMultipartFile file) throws IOException {
        String path = "D:\\upload"; // Define the directory to upload files to, under drive D
        File realPath = new File(path);
        if(! realPath.exists()) {// If no file exists
            // Create a folder
            realPath.mkdirs();
        }

        System.out.println(realPath); // Prints the upload path
		// Write directly to the file through the CommonsMultipartFile class
        file.transferTo(new File(realPath + "/" + file.getOriginalFilename()));
        return "Upload successful"; }}Copy the code

Upload the form page.

<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<html>
    <head>
        <title>fileUpload</title>
    </head>
    <body>
        <form action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data" method="post">
            <input type="file" name="file">
            <input type="submit" value="upload">
        </form>
    </body>
</html>
Copy the code

Multipart /form-data processes form data as a binary stream. This encoding encapsulates the contents of the file domain specified file in the request parameters without encoding characters.

Start the project click the Upload File button to upload the file, but you need to select the file size according to the parameters configured in Spring.

8. The interceptor

Interceptors in SpringMVC are similar to Filter filters in servlets. The idea is implemented based on SpringAOP and mainly used for pre-processing and post-processing of certain paths and resources, which means that the request can only perform its real function after passing the interceptor.

Implement interceptor function

Create a New Web project import dependency

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.2.9. RELEASE</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.0</version>
        <scope>provided</scope>
    </dependency>
</dependencies>
Copy the code

Web.xml and Spring configuration files

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <display-name>Archetype Created Web Application</display-name>

    <servlet>
        <! -- Configure front-end controller 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>

        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

<! -- Spring configuration file -->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       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">

    <! -- Enable annotation support -->
    <mvc:annotation-driven/>
   
    <context:component-scan base-package="com.springmvc.controller"/>

    <! -- Register the view parser bean -->
    <bean id="InternalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <! -- prefix indicates the package prefix name -->
        <property name="prefix" value="/WEB-INF/pages/"/>
        <! -- suffix stands for suffix name, configure.jsp file -->
        <property name="suffix" value=".jsp"/>
    </bean>

    <! Interceptor configuration -->
    <mvc:interceptors>
        <mvc:interceptor>
            <! -- /** intercepts all requests -->
            <mvc:mapping path="/ * *"/>
            <! Inject the interceptor class into the bean container
            <bean class="com.springmvc.config.MyInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>
</beans>
Copy the code

Write interceptor class to implement the HandlerInterceptor interface

@Configuration
public class MyInterceptor  implements HandlerInterceptor {

    //return true; Cleared to execute the next interceptor
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("Before the preHandle method executes");
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("After processing by postHandle method.");
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("AfterCompletion method processing"); }}Copy the code

Write a test Controller class

@RestController
public class TestController {

    @GetMapping("/test")
    public String interceptor(a) {
        System.out.println("Test interceptor method executed...");
        return "ok"; }}Copy the code

The custom interceptor method is implemented and injected into Spring. The request path executes the interceptor method before executing its request.

Visit http://localhost:8080/test start the project path.