Spring MVC continued

1. Interceptor

1.Introduction to interceptors

1. Interceptor (provided by springmvc)

2. Only intercept the control unit (the interceptor must be configured to take effect)

3. Static resources will be intercepted. When using interceptors, try to use local configuration and configure the intercepted control unit.

Note: The interceptor can only take effect if the URL matches the control unit.

4. The order of execution of the three methods implemented in the interceptor:

  • Before executing the control unit, execute the interceptor preHandle method. Process the request accordingly.
  • After the control unit is executed and before the view resolver resolves the rendered view, the interceptor postHandle method is executed. Perform related operations corresponding to modelandview.
  • Complete the response to the client and execute the interceptor afterCompletion method. The operations at the relevant end will be executed regardless of whether an exception occurs.

2. Use interceptors

2.1 Create interceptor class

Create a package under src with a random name, and create a java class to implement the HandlerInterceptor interface. And implement three methods: preHandle, postHandle, and afterCompletion.

public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle execution");
        //false interceptor does not release
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle execution");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion execution");
    }
}

2.2 Configuring interceptors

 <mvc:interceptors>
       
 <!--Static resources will be intercepted. When using interceptors, try to use local configuration and configure the intercepted control unit. -->
       
<!-- 1. Global configuration, all control units execute the interceptor -->
        
<!-- <bean class="com.zqwl.interceptor.MyInterceptor"/>-->

       

<!-- Local configuration, the control unit that conforms to the configured interception path, executes the interceptor -->
<!-- 2. Local interceptor configuration -->
        <mvc:interceptor>
<!--Intercepted control unit-->
            <mvc:mapping path="/demo/*"/>
<!-- Exclude intercepted control units -->
            <mvc:exclude-mapping path="/demo/bb"/>
<!--Interceptor used-->
            <bean class="com.zqwl.interceptor.MyInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>

2.3. Interceptor stack

An interceptor stack refers to multiple interceptors. When a control unit is intercepted by multiple interceptors, an interceptor stack is formed. The interceptors in the interceptor stack have a strict execution order. The execution order is according to the configuration order. The one configured first has higher priority.

For example: Interceptor A and Interceptor B, the higher priority means that the control unit (demo) is the core, the previous method with higher priority is executed first, and the later method with higher priority is executed later.

preHandle1 -> preHandle2 -> demo -> postHandle2 -> postHandle1 -> afterCompletion2 -> afterCompletion1.

Configuring the interceptor stack is divided into local configuration and global configuration (same as single).

Execution order:

2.4. The difference between interceptors and filters (interview questions)

  1. different sources

    Interceptors are a technology in SpringMVC, and filters are a technology in Java EE.

  2. Effective location is different

    The interceptor can only be executed after entering the DispatcherServlet, and the filter can be triggered after entering the Servlet container.

  3. different goals

    The target of the interceptor is HandlerMethod (control unit, controller method), and the filter can filter all URLs.

  4. Different operating mechanisms

    The interceptor is executed before and after the HandlerMethod is executed and after the view processing is completed, and is divided into three parts. Filters can only be executed before and after the target resource.

  5. Different method types in interfaces

    The methods in the interceptor are all default methods, which can be overridden or not. The methods in the filter are all abstract methods. If the current class is not an abstract class, they must be rewritten.

  6. The context is different

    The interceptor is managed by Spring MVC and can obtain the content in the Spring container. Filter is managed by Tomcat, so the Spring container content cannot be obtained.

2. Cross-domain

1. Cross-domain introduction

The project and the URL or ip:port visited before the project are called domains.

Cross-domain: If there is a difference between the protocol, IP, and port of the current project and the protocol, IP, and port of the accessed URL, this kind of access is called cross-domain.

For example: the current project http://localhost:8080 accesses http://127.0.0.1:8080, which is cross-domain access.

2. When does cross-domain occur?

Cross-domain only happens with Ajax requests.

In order to ensure security when Ajax was developed, cross-domain access was not allowed by default.

3. Solve the problem that Ajax cannot cross domains

Just add the @CrossOrigin annotation to the control unit method that needs to be accessed.

3. Spring MVC exception handling

1. Introduction

Exception handling is supported in Spring MVC. The 500 interface will not be presented to the user. Instead, it is handed over to a specific controller when an exception occurs.

If it is an online project and 500 interfaces are presented, it will greatly affect the user experience. At the same time, it also shows that the company’s strength is questionable and unprofessional.

2. Local configuration

Configured in the controller class of @Controller, it can only be executed when the control unit of the current controller class encounters an exception. Control units of other classes cannot be executed when exceptions occur.

Each controller class can have multiple methods for handling exceptions. Each method only needs to have @ExceptionHandler. Do not add @RequestMapping annotation. ,

 @ExceptionHandler(Exception.class) //Write specific exceptions in it. Written here can only handle exceptions that occur in the control unit in the controller class.
    public String MyException(){
        System.out.println("An exception occurred");
        return "/exception.jsp";
    }

3. Global configuration

Because @ControllerAdvice has inherited the @Component annotation, you only need to add this annotation to the class.

No need to add @Controller annotation.

hint:

If a local exception handler and a global exception handler are configured, the local exception handler will be matched first.

//Globally configure exception handling (write a separate class and let SpringMvc manage it), which can be handled when exceptions occur in other controller classes
@ControllerAdvice
public class MyExceptionController {
    @ExceptionHandler(value = ArithmeticException.class)
    public String myexception(){
        System.out.println("MyException-1");
        return "forward:/exception.jsp";
    }
    @ExceptionHandler(value = Exception.class)
    public String myexception2(){
        System.out.println("MyException-2");
        return "forward:/exception.jsp";
    }
}

4. Use configuration file configuration

Spring MVC contains the HandlerExceptionResolver component, which is specifically responsible for handling exceptions. The interface contains only one resolveException method.

Configured in spring mvc.xml:

//xml configuration to solve exceptions: the exception parser has a higher priority than the status code exception: because it is encountered first when an exception occurs, and the status code is encountered only when it is returned to the client
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="java.lang.NullPointerException">/error1.jsp</prop>
                <prop key="java.lang.Exception">/exception.jsp</prop>
            </props>
        </property>
    </bean>

5. Jump to the specified page according to the status code

There is no provision in the Spring MVC framework to jump to a specific view based on the status code. If you want to jump to a specified page based on the status code, you can use the implementation solution provided in Java EE.

Configured in web.xml.

 <error-page>
    <error-code>404</error-code>
    <location>/error.jsp</location>
  </error-page>
  <error-page>
    <error-code>500</error-code>
    <location>/error1.jsp</location>
  </error-page>

4. Spring MVC data verification

1. Introduction to data verification

2. Based on annotation method

Required dependencies:

<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.1.7.Final</version>
</dependency>
Add annotations to entity class attributes

Annotations are placed on the attributes of the entity class. Each entity class attribute supports the configuration of multiple annotations, and these annotations take effect at the same time.

Entity class:

public class People {
    @NotNull(message = "Name cannot be null")
    @Length(min = 2,max = 6,message = "The length should be 2-6 digits")
    private String name;
    private String age;
    // Omit Getter and Setter
}
Control unit:

The @Valid annotation must be added to the control unit, otherwise the verification will not take effect.

If a log file is configured, the log level needs to be set to WARN.

@RequestMapping("/valid")
public String testValid(@Valid People peo){
    System.out.println(peo);
    return "/abc.jsp";
}

5. What components are included in Spring MVC

1. Introduction

SpringMVC encapsulates the entire Servlet access process. After the browser initiates a request, it calls the unit method to process the request. The entire process from receiving the request, to finding the unit method and calling the execution, to the response result to the browser is composed of different It is realized by the collaboration of components, including the following components:

The specific manifestations of different components in the entire running process are actually different objects, that is, the mutual calls between different objects complete the request processing. The initialization of the components should be completed before the request comes. When the server starts, it will First complete the initialization and creation of DispactherServlet. When DispatcherServlet is initialized, the initialization of the second to tenth components will also be completed internally, and its initStrategies method will be called to complete.

2. Description of common components

DispatcherServlet: Front-end controller. The entrance to Spring MVC is also the entire process control center. Other components are dispatched uniformly by DispatcherServlet, which reduces the coupling between components.

MultipartResovler:MultipartResovler. Required when uploading files.

LocaleResolver: Resolve client-side region and time zone issues.

ThemeResolver: Theme resolver. Provides custom layout.

HandlerMapping: Mapping handler. Mainly responsible for processing URLs and finding the corresponding HandlerMethod. Simply put, it is to find whether the mapping path in the @RequestMapping annotation matches the URL.

HandlerAdapter: Adapter. Responsible for calling specific HandlerMethod.

HandlerExceptionResovler:Exception handler. Exception handling, returning views according to different exceptions.

RequestToViewNameTranslator: Get the view name from the request.

ViewResovler: View parser, responsible for parsing string view names and physical view files.

FlashMapManager: Mainly used to store attributes, essentially a Map. Mostly used in redirection. FlashMap is stored before redirection and deleted after redirection.

ModelAndView: Model and view. Model and view interfaces provided in Spring MVC.

HandlerInterceptor: Interceptor. Intercept controller resources.

6. SpringMVC operating principle (common interview questions)

  1. The client initiates a request to the server, and the Spring MVC overall portal central dispatcher DispatcherServlet distributes the request.

  2. The central dispatcher DispatcherServlet hands the URL to the mapping processor HandlerMapping to parse the URL.

  3. Mapping processor HandlerMapping maps requests to HandlerExecutionChain processor execution chain

    1. HandlerInterceptor can be used for multiple processor interceptors

    2. Processor Handler object (processing Controller).

  4. Returns the processor execution chain HandlerExecutionChain to the central dispatcher DispatcherServlet.

  5. DispatcherServlet selects the processor adapter HandlerAdapter based on the processor Handler obtained by the returned processor execution chain HandlerExecutionChain.

    1. Execute the preHandle() method of the interceptor.

    2. Call the specific Handler processor (processing Controller), perform data conversion, data formatting, data verification during the process of filling in the Handler’s input parameters, call the specific Controller to complete the processing function, and create the ModelAndView object.

    3. Execute the postHandle() method of the interceptor.

  6. Return the ModelAndView object to the handler adapter HandlerAdapter.

  7. The handler adapter HandlerAdapter returns the ModelAndView object to the central dispatcher DispatcherServlet.

  8. The central dispatcher DispatcherServlet calls the view resolver ViewResolver to resolve the view.

  9. Returns the parsed View object to the central dispatcher DispatcherServlet.

  10. Render the view, return the view to the central dispatcher DispatcherServlet, and execute the interceptor afterCompletion() method.

  11. The central dispatcher DispatcherServlet responds back to the browser.