Detailed Explanation of Spring Web (Spring MVC)

Overview of Spring Web

SpringWeb is a module of the spring framework, which seamlessly integrates with spring, and is an MVC- based web framework, which facilitates the transmission of front-end and back-end data.
Have a controller, receive external requests, parse parameters and pass them to the service layer.

SpringMVC running process

The MVC architecture is the back-end architecture, which is the name of the jsp era. The concept of mvc does not exist in the era of front-end and back-end separation.

 

 

1. The user sends a request to the server, and the request is captured by the Spring front-end control Servlet and DispatcherServlet. The bottom layer of springWeb uses servlet to receive all user requests
2. After the front controller DispatcherServlet receives the request, it calls the processor mapping HandlerMapping.
The processor mapper HandlerMapping finds the processor Handler (that is, Controller) that handles the request according to the requested url, and returns the processor Handler to the front controller DispatcherServlet. If there is an interceptor for this request, the corresponding interceptor will be executed
3. DispatcherServlet selects an appropriate Handler according to the obtained Handler
HandlerAdapter (adapter). In the process of filling Handler's input parameters, according to your configuration, Spring will
Do some extra work for you (encapsulation parameters):
HttpMessageConveter: convert the request message (such as Json, xml, etc.) into an object, and convert the object into the specified response information
Data conversion: perform data conversion on the request message. Such as String converted to Integer, Double, etc.
Data formatting: data formatting for request messages. Such as converting a string to a formatted number or formatted date, etc.
4. Arrive at the Handler controller defined by yourself, receive parameters, process, and respond

The controller class receives the request

@RestController is used to mark on a class, and the class marked with it is a SpringMVC Controller object.
After specifying the automatically scanned basepackage in the Spring configuration, Spring will scan these packages and
Use the class identified by @RestController in the subpackage, and then add the class to the Spring IOC container to inject dependencies
The @RequestMapping annotation is an annotation used to process request address mapping, which can be used on classes or methods.
 
                                  Used on the class, the entire project must be unique and cannot be repeated
                                   
                                  When defined on a method, the address must also be unique within the same class
                
                                   You can use path/value to define the address (requested path)
                                   
                                   You can use method to define the request method. We know that the request methods of the HTTP protocol include GET and POST. We can use @GetMapping and @PostMapping respectively.
When @RequestMapping does not specify the request method, any method can be used by default
         

                                 Specify the request method: @RequestMapping(value = "/login", method = RequestMethod.GET)

1. Define formal parameter reception in the parameter list

Request method: corresponding to the method in @RequestMapping

The "/students/create" in the request URI: corresponds to the value or path in @RequestMapping
Request header: For example, to get the value in User-Agent, use @RequestHeader("User-Agent") to get it
Request parameters: For example, to obtain the value of the name parameter, use @RequestParam("name") to obtain it.


   

 @RestController
 @RequestMapping("/students")
 public class StudentController {
  @RequestMapping(value="/create",method=RequestMethod.POST)
  public String create(
      @RequestParam("name") String name,
      @RequestParam("age") Integer age,
      @RequestHeader("User-Agent") String userAgent){
  return null;
 }
}

Note: The key in the request is consistent with the name of the formal parameter and received directly. If it is inconsistent, it needs to be received through the annotation tag

2. Use the object directly to receive

 

Chinese garbled

When submitting the request, if the input is Chinese, the processor method will be garbled after getting it. The solution is to add a filter that sets the encoding set for the request object. SpringMVC has provided us with this filter, just need to configure it in web.xml:
<filter>
<filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

Return result in controller ( Ajax returns JSON )

Since @RequestMapping contains the @RequestBody tag, the result returned by the method is in json format by default, and when writing the json string into the response body and returning an object, a third-party component that converts to json must be added

 <!--转json需要的组件-->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.6</version>
        </dependency>

cross domain processing

1. Add a cross-domain filter
<dependency>
<groupId>com.thetransactioncompany</groupId>
<artifactId>cors-filter</artifactId>
<version>2.5</version>
</dependency>

2. Configure in web.xml

<filter>
<filter-name>CORS</filter-name>
<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CORS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

interceptor

SpringMVC defines the interceptor interface HandlerInterceptor, which defines three methods. The calls of these three methods are completed within the SpringMVC framework. When these three methods are called, the values ​​​​of their parameters are also passed in from within the framework. . The boolean preHandle preprocessing method implements the preprocessing of the processor method, that is, this method will be executed before the processor method is executed, which is equivalent to intercepting the processor method, and the framework will pass the request and response objects to the method. The third parameter is the intercepted handler method. If the preHandle method returns true to continue the process (such as calling the next interceptor or processor method), returning false indicates that the process is interrupted and will not continue to call other interceptors or processor methods
Implementation of the interceptor:
1. Write a class that inherits HandlerInterceptorAdapter

 2. Register interceptor

 <!--配置拦截器-->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/><!--配置那些请求可以进入到拦截器-->
            <mvc:exclude-mapping path="/loginCtl/login"/><!--配置那些请求不可以进入拦截器-->
            <bean class="com.ffyc.ssm.common.TokenInterceptor"></bean><!--配置实现类的拦截器-->
        </mvc:interceptor>
    </mvc:interceptors>

Guess you like

Origin blog.csdn.net/weixin_71243923/article/details/128285808