SpringMvc common annotation usage

There are two Controller annotations in Spring, one is the new @RestController in the spring 4.0 series, and the other is the @Controller annotation in spring 3. First of all, we need to understand the difference between them.
The official documentation explains @RestController:
@RestController is a stereotype annotation that combines @ResponseBody and @Controller.
Translation: @RestController annotation is used in combination by @Controller and @ResponseBody.
Differences:
1. If you use the @RestController annotation on your custom Controller class, the view resolver will not work, and the JSP page cannot be returned. The returned content is the content defined by return.
2. If you need to return to the specified page, you need to use @Controller and use the view resolver.
3. If returning data in Json format, @RestController has natural advantages, and returning other formats needs to set the value of the produces attribute. If you use @Controller, you need to use it with @ResponseBody.


The following annotations are introduced based on @RestController.

    @RequestMapping

RequestMapping is an annotation for processing request address mapping, which can be used on classes or methods. Used on a class, indicating that all methods in the class that respond to requests use this address as the parent path.
For example:

    @RestController
    @RequestMapping("/version1.0")
    public class SomtingDemoController{
       
        @RequestMapping("/one")
        public ResponseEntity<String> doSomthingOne(){
            return new ResponseEntity<String>("GET /version1.0/one Success",HttpStatus.OK);
        }
    }


Request to doSomtingOne method The URL is http://ip:port/version1.0/one The
@RequestMapping annotation has six attributes:
1, value: Set the mapping relationship between the method and the URL path.
2, method: Specify the method of Http request, corresponding to the four methods of Http, GET, POST, PUT, DELETE.
3, consumes: Specify the type of requested content (Content-Type), such as application/json, text/html, and the default is application/json.
4, produces: Specify the type of returned content, application/json by default.
5, params: The specified request must contain certain parameter values ​​before this method can process it.
8, headers: The specified request must contain certain specified header values ​​in order for this method to process the request.

Other annotations:

    @PathVariable

Description: @PathVariable is used to obtain the dynamic parameters in the request url. The dynamic parameters are presented in the form of {variable name}. In the @RequestMapping mapping binding method parameters, use @PathVariable to bind the dynamic parameters. The binding is divided into two cases. :
 1) If the dynamic parameter variable name is inconsistent with the method parameter name, you need to use @PathVariable(variable name) String parameter name binding.
 2) If the dynamic parameter variable name is the same as the method parameter name, use @PathVariable String variable name.
Example:
     @RestController
        @RequestMapping("/version1.0")
        public class SomtingDemoController{
           
            @RequestMapping("/one/{var1}/{var2}/{var3}")
            public ResponseEntity<String> doSomthingOne(@PathVariable("var1 ") String v1,@PathVariable("var2") String v2,@PathVariable String var3){
                System.out.println("path var1="+var1);
                System.out.println("path var2="+var2) ;
                return new ResponseEntity<String>("GET /version1.0/one Success",HttpStatus.OK);
            }
        }
 

    @RequestParam

Description: To obtain parameter values ​​from Request, the traditional way is to obtain parameter values ​​from HttpServletRequest, written as request. getParameter(parameter name). In SpringMVC, you can use the @RequestParam annotation to more elegantly bind the parameters in the request to the method parameters.
Note:
1) If you directly write @RequestParam String Request parameter name or `@RequestParam("Request parameter name") String binding parameter`, then if the front end does not pass or there is no Request parameter name, an error will be reported, and the error message "HTTP Status 400 - Required String parameter 'aa' is not present".
2) If you need to configure parameters that can be passed or not, you can write
  @RequestParam (value="Request parameter name", required=false) String Binding parameter name
At this time, the assignment of the binding parameter name is null.
Where
  a.required=true means that parameters must be passed, the default is true
  b. If the bound parameter is of type int, such as @RequestParam(value="intVal",required=false) int val, at this time required=false, if the front end does not pass the intVal parameter, then @RequestParam assigns null to int , this will report an error "Consider declaring it as object wrapper for the corresponding primitive type", when the int type is bound, the wrapper class Integer needs to be used.

     @RestController
            @RequestMapping("/version1.0")
            public class SomtingDemoController{
                @RequestMapping("/one")
                public ResponseEntity<String> doSomthingOne(
                @RequestParam("param1") String p1,
                @RequestParam String param2,
                @RequestParam(value ="intVal",reqired=false) Integer val){
                
                }
            }

@RequestBody
    This annotation is used to read part of the data in the Request body, use the HttpMessageConverter configured by default for parsing, bind the response data to the object to be returned, and then bind the returned data object to the parameter object annotated by @RequestBody .
    Usage scenarios:
    1) When GET and POST are submitted, judge according to the Content-Type of the request header:
     a.application/x-www-form-urlencoded @RequestParam, @ModelAttribute, @RequestBody can all handle
     b.multipart/form-data Cannot handle
     c.application/json, application/xml must be handled with @RequestBody.
    2) When PUT is submitted, it is also judged according to the Content-Type of the request header:
     a.application/x-www-form-urlencoded must be processed with @RequestBody
     b. multipart/form-data cannot be processed
     c. application/json, application/ xml must use @requestBody to handle
    
        @RestController
        @RequestMapping("/version1.0")
        public class SomtingDemoController{
           @RequestMapping("/one",method=RequestMethod.POST | GET | PUT)
            public ResponseEntity<String> doSomthingOne(
            @RequestBody UObject obj){
            
            }
        }

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326989777&siteId=291194637