Learn spring MVC notes

configuration file
mvc:default-servlet-handler/
mvc:annotation-driven/

<?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:aop="http://www.springframework.org/schema/aop"
       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-3.0.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
 http://www.springframework.org/schema/mvc
  http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
    <context:component-scan base-package="text"/>
<!--    Filter static pages-->
    <mvc:default-servlet-handler/>
<!--    Automatically configure mappers and adapters-->
    <mvc:annotation-driven/>

<!--   Try parser-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          id="internalResourceViewResolver">
        <property name="prefix" value="/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

1, Common notes

@RequestMapping:

@RequestMapping(value = "save",method = RequestMethod.GET,consumes = "application/x-www-form-urlencoded",produces = "application/json",params = "name",headers = "asd"
//@GetMapping("save")

  • Value: access address of URL

  • Method: limit request method

  • Consumers: the type that the server allows to receive (in the form of form)

  • Products: types allowed by the browser (in the form of json)

  • params: the access address must contain this parameter (the url must contain this parameter)

  • headers: the request header must contain this request header in order to access (the request header carries asd)
    @RequestParam: use @ RequestParam at the processing method input parameter to pass the request parameter to the request method

public String cc(@RequestParam(value="use",defaultValue = "123",required = false) Integer userId,String name){

        System.out.println("name"+name+"id"+userId);
       return name;

Browser access
http://localhost:8080/SpringMVC_war_exploded/cc?use=147&name=lihi

  • @RequestParam(required = false) is set to non mandatory. The default value is required
  • @RequestParam("use") specifies the parameter name, which should be used when the browser passes parameters.
  • @RequestParam(defaultValue = "123") specifies the default value of the parameter.

@RequestHeader: get the parameters of the request header

@Cookie value: get cookie value

@PathVariable: binding URL placeholder to input parameter is spring 3 0 new features (RestFul style)

@RequestBody: this annotation is used to read the data of the body part of the Request, parse it using the HttpMessageConverter configured by default, bind the corresponding data to the object to be returned, and then bind the object data returned by HttpMessageConverter to the parameters of the method in the controller

@ResponseBody: this annotation is used to convert the object returned by the Controller method into the specified format through the appropriate HttpMessageConverter and write it to the body data area of the Response object

@RequestMapping(value = "/userlist")
    public Resp userList(@RequestBody User user) {
    	return user;
    }

My current understanding is the conversion between json

forward: "pathname": request forwarding

@RequestMapping(value="text")

    public String mvc(String name){
        return "forward:/user/tt";
    }

Redirect: "pathname": redirect

    @RequestMapping(value="tt")
    public String mvc(String name,String age){
        return "redirect:/user/text";
    }

2, Model and ModelAndView

 @RequestMapping("/get")
    public String get(Model model){
   		// Both Model and ModelAndView can be passed to the front-end value
        //model.addAttribute("cname","name");
        ModelAndView view = new ModelAndView("view");
        view.addObject("cname","name");
        return "get";
    }

3, Interceptor

1. Introduction

Interceptor s in Spring MVC are similar to filters in Servlet development
Filter, which is mainly used to intercept user requests and process them accordingly. It is also the embodiment of AOP programming idea. The bottom layer is completed through dynamic agent mode.

2. Define implementation classes

Interceptors can be implemented in two ways:
1. Implement HandlerInterceptor interface
2. Inherit the abstract class of HandlerInterceptorAdapter (see that the lowest layer of the source code is also implemented through the HandlerInterceptor interface)

3. Difference from Filter

1. The interceptor is based on java reflection mechanism, while the filter is based on function callback.
2. The interceptor does not depend on the servlet container, while the filter depends on the servlet container.
3. Interceptors can only work on Controller requests, while filters can work on almost all requests.
4. The interceptor can access the objects in the action context and value stack, but the filter cannot.
5. In the life cycle of the Controller, the interceptor can be called multiple times, while the filter can only be called once when the container is initialized.
6. The interceptor can obtain each bean in the IOC container, but the filter cannot. This is very important. Inject a service into the interceptor to call the business logic.
Author: morning fog light cold
Link: https://juejin.im/post/6844903975469203469
Source: Nuggets

3. Implementation of interceptor
3.1 Java part
First interceptor

public class LoginIntercepter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle");
        return true;
    }

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

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

Second interceptor

public class LoginIntercepter2 implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle2");
        return true;
    }

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

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

  • preHandle method: executed before entering the Handler method. It can be used for identity authentication and identity authorization. For example, if the authentication fails, it means that the user has not logged in. This method needs to be intercepted and will not be executed further (return false), otherwise it will be released (return true).
  • postHandle method: after entering the Handler method, execute it before returning modelandview. You can see that there is a formal parameter of modelandview in this method. Application scenario: starting from modelandview: transfer common model data (such as menu navigation) to the view here, or specify the same view here.
  • afterCompletion method: execute after the Handler is completed. Application scenario: unified exception handling, unified log processing, etc.

3.2 spring MVC configuration

<!--    Configuring Interceptors -->
<mvc:interceptors>
<!-- Configure a global interceptor to intercept all requests -->
<!--<bean class="text2.LoginIntercepter"></bean>-->
    <!-- Multiple interceptors, executed in sequence -->
    <mvc:interceptor>
    <!-- Means to intercept all url Including sub url route -->
        <mvc:mapping path="/**"/>
        <bean class="text2.LoginIntercepter"></bean>
    </mvc:interceptor>
    
    <mvc:interceptor>
        <mvc:mapping path="/**"/>
        <bean class="text2.LoginIntercepter2"></bean>
    </mvc:interceptor>
</mvc:interceptors>

3.3 implementation results
When setting multiple interceptors, first call the preHandle method in order, and then call the postHandle and afterCompletion methods of each interceptor in reverse order

preHandle
preHandle2
postHandle2
postHandle
afterCompletion2
afterCompletion

4, Unified exception handling

java code

@ControllerAdvice
public class MyException {
    @ResponseBody
    @ExceptionHandler(value=Exception.class)
    public ResponseEntity<Resp> errorHandler(Exception ex){
        Resp resp = new Resp();
        resp.setMsg(ex.getMessage());
        return new ResponseEntity<Resp>(resp, HttpStatus.OK);
    }
}

Tags: Java Spring servlet filter

Posted by SteveMT on Tue, 10 May 2022 15:08:48 +0300