Usage and differences of @RequestMapping, @ResponseBody and @RequestBody annotations

background:

    Help colleagues solve the file upload bug (the file upload is successful, but the page prompts that the upload interface is abnormal, and the data is indeed inserted), find the error from the front-end layui page, and then debug it in the browser. The code return of the layui file upload format is a numerical value, and the background return is success. Then try to start from the background return value and use map to return. Failed. Finally when I went back to the location to run my own project, I remembered that there may be no response body in the background. Sure enough, bingo solved it!

@RequestMapping @ResponseBody and @RequestBody We often use, what is the difference between them, the following is a brief introduction:

@RequestMapping

     @RequestMapping is an annotation for processing request address mapping, which can be used on classes or methods. For classes, it means that all methods in the class that respond to requests use this address as the parent path; for methods, it means that adding the address in the annotation on the method under the parent path of the class will access the method. E.g.:

/**
* 用于类上,可以没有
*/
@RequestMapping(value = "/controllerDemo")
public class ControllerDemo {
    // 用于方法上,必须有
    @RequestMapping(value = "/methodDemo")    
    public String methodDemo() {
        return "helloWorld";
    }
}

The RequestMapping annotation has six attributes. Let's divide it into three categories for description.

1value method

   value : Specify the actual address of the request, the specified address can be in URI Template mode (will be explained later)

   method : Specify the method type of the request, GET , POST , PUT , DELETE , etc.

2consumesproduces

   consumes : Specify the submitted content type ( Content-Type ) for processing requests, such as application/json, text/html;

   produces:    specifies the returned content type, which is only returned when the (Accept) type in the request header contains the specified type ;

3paramsheaders

   params : Specifies that the request must contain certain parameter values ​​for this method to process.

   headers : Specifies that the request must contain certain specified header values ​​in order for this method to process the request.

@ResponseeBody

      The @Responsebody annotation indicates that the result returned by the method is directly written into the HTTP response body (ResponseBody), which is generally used when acquiring data asynchronously, usually after @RequestMapping is used, and the return value is usually parsed as a jump path, plus @Responsebody The returned result will not be parsed as a jump path, but written directly into the HTTP response body.
Function: 
   This annotation is used to convert the object returned by the Controller method into the specified format through the appropriate HttpMessageConverter, and then write it to the body data area of ​​the Response object. 
Timing of use: When 
   the returned data is not a page of HTML tags, but data in some other format (such as json, xml, etc.);

When the page makes an asynchronous request:

function login(){
    var datas='{"username":"'+$('#username').val()+'","userid":"'+$('#userid').val()+'","status":"'+$('#status').val()+'"}';
    $.ajax({
        type:'POST',
        contentType:'application/json',
        url:"${pageContext.request.contextPath}/user/login",
        processData:false,
        dataType:'json',
        data:datas,
        success:function(data){
           alert("userid:"+data.userid+"username:"+data.username+"status:"+data.status);
        },
        error:function(XMLHttpRequest,textStatus,errorThrown){
           alert("出现异常,异常信息:"+textStatus,"error");
        }
    });
};

Backend code:

@RequestMapping(value="user/login")
@ResponseBody
//将ajax(datas)发出的请求写入User对象中,返回json对象响应回去
public User login(User user) {
       User user = new User();
    user.setUserid(1);
    user.setUsername("MrF");
    user.setStatus("1");    
    return user ;
}

The json data is obtained asynchronously, and after adding the @Responsebody annotation, the json data will be returned directly.

@RequestBody

   The @RequestBody annotation is to insert the HTTP request body into the method, and use the appropriate HttpMessageConverter to write the request body to an object.

effect:

1) 该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,然后把相应的数据绑定到要返回的对象上; 
2) 再把HttpMessageConverter返回的对象数据绑定到controller中方法的参数上。

When to use:

   A) When the GET and POST methods are used, it is judged according to the value of the request header Content-Type:

application/x-www-form-urlencoded,可选(即非必须,因为这种情况的数据@RequestParam,@ModelAttribute也可以处理,当然@RequestBody也能处理); 
multipart/form-data,不能处理(即使用@RequestBody不能处理这种格式的数据); 
其他格式,必须(其他格式包括application/json,application/xml等。这些格式的数据,必须使用@RequestBody来处理);

   B) When submitting in the PUT method, it is judged according to the value of the request header Content-Type:

application/x-www-form-urlencoded,必须;multipart/form-data,不能处理;其他格式,必须;

   Description: The data encoding format of the body part of the request is specified by the Content-Type of the header part;

E.g:

@RequestMapping(value = "user/login")
@ResponseBody
// 将ajax(datas)发出的请求写入User对象中
public User login(@RequestBody User user) {   
// 这样就不会再被解析为跳转路径,而是直接将user对象写入 HTTP 响应正文中
    return user;    
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325544887&siteId=291194637