Common annotations in the SpringMVC framework (all dry goods, dry to death!)

Common annotations in the SpringMVC framework

​Spring MVC is an annotation-based web framework that provides a large number of annotations to simplify the development and configuration of web applications. Currently (as of September 2021), there are nearly 70 annotations in Spring MVC. These annotations include commonly used annotations such as @Controller, @RequestMapping, @PathVariable, @RequestParam, @ResponseBody, @RequestBody, @ModelAttribute, @Valid, etc., as well as some uncommon annotations. The role and usage examples of each annotation will vary according to specific situations in actual development.

Common annotations, explanations, and use cases of Spring MVC

(1)@Controller

​ Function: To identify a controller whose class is SpringMVC, @Controller is an annotation used to identify the controller. Classes annotated with @Controller usually handle HTTP requests and return responses.

​ Use case:

@Controller
@RequestMapping("/hello")
public class HelloController {
    
    

    @RequestMapping(method = RequestMethod.GET)
    public String hello() {
    
    
        return "hello";
    }
}

(2)@RestController

Function: Identify a Rest-style controller with a class of SpringMVC, @RestController is an annotation used to identify a Rest-style controller. Unlike the @Controller annotation, all methods in the @RestController annotated class will return the response result in JSON or XML

Example:

@RestController
@RequestMapping("/api")
public class ApiController {

    @GetMapping("/hello")
    public String hello() {
        return "Hello, World!";
    }
}

(3)@RequestMapping

Function: Used to map requests to controller methods, @RequestMapping is an annotation used to map requests to controller methods, which is very commonly used in SpringMVC. It can be used at class level as well as method level. At the class level, the @RequestMapping annotation is used to specify the request path prefix processed by the controller, which will be applied to all methods in the class that process requests.

Example:

@Controller
@RequestMapping("/users")
public class UserController {
    
    

    @GetMapping("/{id}")
    public String getUser(@PathVariable Long id) {
    
    
        // ...
    }

    @PostMapping
    public String createUser(@ModelAttribute User user) {
    
    
        // ...
    }
}

(4)@GetMapping

Function: used to map GET requests to controller methods, @GetMapping is an annotation used to map HTTP GET requests to controller methods, which is very commonly used in SpringMVC. It can be used at the method level to specify the method to handle GET requests. For example:

Example:

@Controller
@RequestMapping("/users")
public class UserController {
    
    

    @GetMapping("/{id}")
    public String getUser(@PathVariable Long id) {
    
    
        // ...
    }
}

(5)@PostMapping

Function: used to map POST requests to controller methods, @PostMapping is an annotation used to map HTTP POST requests to controller methods, which is very commonly used in SpringMVC. It can be used at the method level to specify the method to handle POST requests

Example:

@Controller
@RequestMapping("/users")
public class UserController {
    
    

    @PostMapping
    public String createUser(@ModelAttribute User user) {
    
    
        // ...
    }
}

(6)@PutMapping

Function: used to map PUT requests to controller methods, @PutMapping is an annotation used to map HTTP PUT requests to controller methods, which is very commonly used in SpringMVC. It can be used at the method level to specify the method to handle PUT requests.

Example:

@Controller
@RequestMapping("/users")
public class UserController {
    
    

    @PutMapping("/{id}")
    public String updateUser(@PathVariable Long id, @ModelAttribute User user) {
    
    
        // ...
    }
}

(7)@DeleteMapping

Function: used to map DELETE requests to controller methods, @DeleteMapping is an annotation used to map HTTP DELETE requests to controller methods, which is very commonly used in SpringMVC. It can be used at the method level to specify the method to handle DELETE requests

Example:

@Controller
@RequestMapping("/users")
public class UserController {
    
    

    @DeleteMapping("/{id}")
    public String deleteUser(@PathVariable Long id) {
    
    
        // ...
    }
}

(8)@PatchMapping

Role: used to map PATCH requests to controller methods. @PatchMapping is an annotation for mapping HTTP PATCH requests to controller methods, which can also be used in SpringMVC. It can be used at the method level to specify the method for processing PATCH requests

Example:

@Controller
@RequestMapping("/users")
public class UserController {
    
    

    @PatchMapping("/{id}")
    public String updateUser(@PathVariable Long id, @RequestBody User user) {
    
    
        // ...
    }
}

(9)@RequestParam

Function: Bind the request parameters to the parameters of the controller method. @RequestParam is an annotation for obtaining HTTP request parameters, which is very commonly used in SpringMVC. It can be used at the method parameter level to specify the method and name of getting request parameters.

Example:

@Controller
@RequestMapping("/users")
public class UserController {
    
    

    @GetMapping
    public String getUsers(@RequestParam("page") int page, @RequestParam("size") int size) {
    
    
        // ...
    }
}

(10)@PathVariable

Function: Use part of the URL as a parameter of the controller method. @PathVariable is an annotation used to obtain parameters in the HTTP request path, which is very commonly used in SpringMVC. It can be used at the method parameter level to specify the name of the get request path parameter.

Example:

@Controller
@RequestMapping("/users")
public class UserController {
    
    

    @GetMapping("/{id}")
    public String getUser(@PathVariable Long id) {
    
    
        // ...
    }
}

(11)@RequestBody

Function: Bind the content of the request body to the parameters of the controller method. @RequestBody is an annotation used to obtain parameters in the HTTP request body, which is very commonly used in SpringMVC. It can be used at the method parameter level to specify how to obtain request body parameters.

Example:

@Controller
@RequestMapping("/users")
public class UserController {
    
    

    @PostMapping
    public String createUser(@RequestBody User user) {
    
    
        // ...
    }
}

(12)@ResponseBody

Function: Write the return value of the controller method directly into the HTTP response body. @ResponseBody is an annotation used to convert the return value of a method into an HTTP response body, which is very commonly used in SpringMVC. It can be used at the method level to specify to convert the return value of the method into an HTTP response body and send it to the client.

Example:

@Controller
@RequestMapping("/users")
public class UserController {
    
    

    @GetMapping("/{id}")
    @ResponseBody
    public User getUser(@PathVariable Long id) {
    
    
        // ...
        return user;
    }
}

(13)@ModelAttribute

Function: Bind the request parameters to an object. @ModelAttribute is an annotation used to bind HTTP request parameters to method parameters or method return values, which is very commonly used in SpringMVC. It can be used at the method parameter level to specify the use of HTTP request parameters to bind property values ​​on method parameters.

Example:

@Controller
@RequestMapping("/users")
public class UserController {
    
    

    @PostMapping
    public String createUser(@ModelAttribute User user) {
    
    
        // ...
    }
}

(14)@SessionAttribute

Function: store an object in the session. @SessionAttribute is an annotation for storing model attributes in HTTP Session, which is very commonly used in SpringMVC. It can be used at method level or class level to specify to store model attributes into HTTP Session.

Example:

@Controller
@RequestMapping("/users")
@SessionAttributes("user")
public class UserController {
    
    

    @GetMapping("/{id}")
    public String getUser(@PathVariable Long id, Model model) {
    
    
        User user = userService.getUserById(id);
        model.addAttribute("user", user);
        return "user-details";
    }

    @PostMapping("/{id}")
    public String updateUser(@PathVariable Long id, @ModelAttribute("user") User user) {
    
    
        userService.updateUser(user);
        return "redirect:/users/" + id;
    }
}

(15)@InitBinder

Function: used to process annotations of WebDataBinder. @InitBinder is an annotation for customizing WebDataBinder, which is very commonly used in SpringMVC. It can be used at class level or method level, and is used to specify how to customize WebDataBinder.

Example:

@Controller
@RequestMapping("/users")
public class UserController {
    
    

    @InitBinder
    public void initBinder(WebDataBinder binder) {
    
    
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    @PostMapping
    public String createUser(@ModelAttribute User user) {
    
    
        // ...
    }
}

(16)@ExceptionHandler

Role: Annotation for handling exceptions. @ExceptionHandler is an annotation used to handle exceptions in controllers, which is very commonly used in SpringMVC. It can be used at the method level to specify how to handle exceptions that occur in the controller.

Example:

@ControllerAdvice
public class GlobalExceptionHandler {
    
    

    @ExceptionHandler(Exception.class)
    public ModelAndView handleException(Exception ex) {
    
    
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", ex);
        mav.setViewName("error");
        return mav;
    }
}

(17)@ResponseStatus

Role: Convert exceptions to HTTP response status codes. @ResponseStatus is an annotation used to specify the HTTP response status code when the controller method is successfully processed, which is very commonly used in SpringMVC. It can be used at the method level to specify the HTTP response status code when the controller method is successfully processed.

Example:

@Controller
@RequestMapping("/users")
public class UserController {
    
    

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public void createUser(@RequestBody User user) {
    
    
        userService.createUser(user);
    }
}

(18)@ControllerAdvice

Role: used to define the global controller exception handler. @ControllerAdvice is an annotation used to define global controller notifications, which is very commonly used in SpringMVC. It can be used at class level for defining global controller notifications.

Example:

@ControllerAdvice
public class GlobalControllerAdvice {
    
    

    @ModelAttribute("currentUser")
    public User getCurrentUser() {
    
    
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
    
    
            return null;
        }
        return (User) authentication.getPrincipal();
    }

    @ExceptionHandler(Exception.class)
    public ModelAndView handleException(Exception ex) {
    
    
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", ex);
        mav.setViewName("error");
        return mav;
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
    
    
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
}

在这个例子中,@ControllerAdvice注解用于定义全局控制器通知,包括@ModelAttribute@ExceptionHandler@InitBinder三个方法。当控制器中的方法被调用时,将会自动调用这些方法,以实现全局控制器通知的功能。@ModelAttribute用于将当前登录的用户信息添加到模型中,@ExceptionHandler用于处理控制器方法中出现的异常,@InitBinder用于定制WebDataBinder的方式。

总之,@ControllerAdvice注解是一个用于定义全局控制器通知的注解,在SpringMVC中非常常用。它能够帮助我们实现全局控制器通知的功能,提高代码的可读性和可维护性。

(19)@RequestMappingHandlerMapping

Function: Parse the @RequestMapping annotation into a request mapping. @RequestMappingHandlerMapping is a HandlerMapping implementation class in Spring MVC for mapping requests to controller methods. It is one of the HandlerMapping implementation classes for processing @RequestMapping annotations, which is very commonly used in Spring MVC.

Example:

@Controller
@RequestMapping("/users")
public class UserController {
    
    

    @GetMapping("/{id}")
    @ResponseBody
    public User getUser(@PathVariable Long id) {
    
    
        return userService.getUserById(id);
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public void createUser(@RequestBody User user) {
    
    
        userService.createUser(user);
    }
}
在这个例子中,UserController类上使用了@RequestMapping注解,表示该控制器处理"/users"路径下的请求。getUser()方法上使用了@GetMapping注解,表示该方法处理HTTP GET请求。@GetMapping注解中的"{id}"表示该方法接受一个名为"id"的路径参数。@ResponseBody注解表示该方法返回的结果将会被序列化为HTTP响应的正文。createUser()方法上使用了@PostMapping注解,表示该方法处理HTTP POST请求。@ResponseStatus注解表示该方法处理成功时返回HTTP状态码为201Created)。

在DispatcherServlet初始化时,会注册RequestMappingHandlerMapping,并将其与所有使用了@Controller注解的类关联起来。当请求到达DispatcherServlet时,RequestMappingHandlerMapping会遍历所有已注册的控制器类和方法,找到与请求匹配的控制器方法,并返回对应的HandlerExecutionChain对象,该对象包含了控制器方法和一系列拦截器。

总之,RequestMappingHandlerMappingSpring MVC中的一个HandlerMapping实现类,用于将请求映射到控制器方法。它能够帮助我们实现请求映射和控制器方法的调度,提高代码的可读性和可维护性。

(20)@RequestMappingHandlerAdapter

Role: parse the @RequestMapping annotation into a request adapter

Example:

@RequestMappingHandlerAdapterSpring MVC中的一个HandlerAdapter实现类,用于将请求处理结果转换为HTTP响应。它是一个用于处理@RequestMapping注解的HandlerAdapter实现类之一,在Spring MVC中非常常用。

RequestMappingHandlerAdapter根据请求URL和请求方法(GET、POST等)将请求映射到对应的控制器方法,并调用该方法获取处理结果。然后,它会根据处理结果的类型选择对应的MessageConverter将其转换为HTTP响应的正文,并设置HTTP响应头部信息。最后,它会返回一个ModelAndView对象或void类型的结果,或直接将响应信息写入HTTP响应流中。

RequestMappingHandlerAdapter还支持使用HandlerMethodArgumentResolver解析控制器方法的参数,以及使用HandlerMethodReturnValueHandler处理控制器方法的返回值。它可以通过配置MessageConverterReturnValueHandler来实现。

总之,RequestMappingHandlerAdapterSpring MVC中的一个HandlerAdapter实现类,用于将请求处理结果转换为HTTP响应。它是Spring MVC中非常重要的组件之一,能够帮助我们实现请求处理和HTTP响应的转换,提高代码的可读性和可维护性。

(21)@RequestHeader

Function: Bind the value of the request header to the parameters of the controller method. @RequestHeader is an annotation in Spring MVC for obtaining HTTP request header information. It can be used on a method parameter, indicating that the specified HTTP request header information is bound to the parameter.

Example:

@GetMapping("/users")
@ResponseBody
public List<User> getUsers(@RequestHeader("Authorization") String authorization) {
    
    
    // 处理HTTP请求头部中的Authorization信息
    // ...
}

(22)@CookieValue

Function: Bind the value of the request cookie to the parameters of the controller method. @CookieValue is an annotation in Spring MVC, used to get the Cookie value in the HTTP request. It can be used on method parameters, indicating that the specified cookie value is bound to the parameter.

Example:

@GetMapping("/users")
@ResponseBody
public List<User> getUsers(@CookieValue("sessionId") String sessionId) {
    
    
    // 处理HTTP请求中的sessionId Cookie值
    // ...
}

(23)@RequestAttribute

Function: Bind the value of the request attribute to the parameter of the controller method. @RequestAttribute is an annotation in Spring MVC, which is used to obtain the attributes in the HTTP request (that is, the attributes set by the ServletRequest.setAttribute() method). It can be used on a method parameter, indicating that the specified HTTP request attribute is bound to the parameter.

Example:

@GetMapping("/users")
@ResponseBody
public List<User> getUsers(@RequestAttribute("userId") Long userId) {
    
    
    // 处理HTTP请求中的userId属性
    // ...
}

(24)@ResponseStatus

Function: convert the return value of the method into an HTTP response status code. @ResponseStatus is an annotation in Spring MVC that is used to specify the response status code and response message of the controller method. It can be used on a controller method to bind the specified response status code and response message to the method.

Example:

@PostMapping("/users")
@ResponseStatus(HttpStatus.CREATED)
public void createUser(@RequestBody User user) {
    
    
    // 创建用户
    // ...
}

(25)@ResponseBodyAdvice

Function: used to customize the processing of @ResponseBody. @ResponseBodyAdvice is an interface in Spring MVC, which is used to uniformly process the response data returned by the controller method. It can achieve unified processing of response data by implementing this interface.

Example:

@ControllerAdvice
public class MyResponseBodyAdvice implements ResponseBodyAdvice<Object> {
    
    

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
    
    
        // 判断是否需要对该返回类型进行处理
        // ...
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
                                  ServerHttpResponse response) {
    
    
        // 对响应数据进行统一处理
        // ...
        return processedBody;
    }
}

(26)@RequestBodyAdvice

Function: used to customize the processing of @RequestBody. @RequestBodyAdvice is an interface in Spring MVC, which is used to uniformly process the request data received by the controller method. It can achieve unified processing of request data by implementing this interface

Example:

@ControllerAdvice
public class MyRequestBodyAdvice implements RequestBodyAdvice {
    
    

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
    
    
        // 判断是否需要对该请求类型进行处理
        // ...
    }

    @Override
    public Object beforeBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
                                 Class<? extends HttpMessageConverter<?>> converterType) {
    
    
        // 对请求数据进行统一处理
        // ...
        return processedBody;
    }
}

(27)@ModelAttributeAdvice

Function: used to customize the processing of @ModelAttribute. @ModelAttributeAdvice is an interface in Spring MVC, which is used to uniformly process method parameters annotated with @ModelAttribute in controller methods. It can realize the unified processing of method parameters annotated by @ModelAttribute by implementing this interface.

Example:

@ControllerAdvice
public class MyModelAttributeAdvice {
    
    

    @ModelAttribute
    public void handleModelAttributes(Model model) {
    
    
        // 对Model中的属性进行统一处理
        // ...
    }
}

(28)@SessionAttributes

Role: Specify which model attributes are stored in the session. @SessionAttributes is an annotation in Spring MVC, which is used to store model data in the session (session), so that data can be shared between multiple requests. It can be used on controller classes to store the specified model attributes in the session.

Example:

@Controller
@SessionAttributes("user")
public class UserController {
    
    
    
    @GetMapping("/user")
    public String getUser(Model model) {
    
    
        User user = userService.getUser();
        model.addAttribute("user", user);
        return "user";
    }
    
    // 其他控制器方法
}

If you have anything to add, please leave a message!

Guess you like

Origin blog.csdn.net/qq_46138492/article/details/129471296