Read the correct way to use @RequestBody

  • 2020-12-22 17:38:28
  • OfStack

This paper mainly studies the proper use of @RequestBody, as follows.

Recently, I was accepting the work of a colleague who was going to leave, and the project I took over was built with SpringBoot. I saw the following writing:


@RequestMapping("doThis") 
public String doThis(HttpServletRequest request, 
    @RequestParam("id") Long id, //  The user ID 
    @RequestParam("back_url") String back_url, //  The callback address       
    @RequestBody TestEntity json_data // json Data, for java Entity class  
){//... 

This is a request mapping method, and then use the browser input url: http: / / 127.0.0.1:8080 / test/doThis & # 63; id=1 & back_url=url & json_data={"code":2,"message":"test"}

In this method, @RequestParam is used to get the arguments and then @RequestBody is used to convert the arguments in json format to the Java type

Error detected while running: Required request body is missing

Using @RequestBody requires loading MappingJackson2HttpMessageConverter, but the official documentation for SpringBoot mentions that this is loaded by default, and json string and javabean have no written errors

Therefore, considering that Content-ES41en should be requested, spring cannot find request body because there is no way to define ES43en-ES44en by typing url in the browser

To test this idea, write your own 1 request class:


String add_url = "http://127.0.0.1:8080/test/doThis"; 
  URL url = new URL(add_url); 
  HttpURLConnection connection = (HttpURLConnection)url.openConnection(); 
  connection.setDoInput(true); 
  connection.setDoOutput(true); 
  connection.setRequestMethod("POST"); 
  connection.setUseCaches(false); 
  connection.setInstanceFollowRedirects(true); 
  connection.setRequestProperty("Content-Type","application/json"); 
  connection.connect(); 
  DataOutputStream out = new DataOutputStream(connection.getOutputStream()); 
  JSONObject obj = new JSONObject(); 
   
  obj.put("code", -1002);    
  obj.put("message", "msg"); 
  out.writeBytes(obj.toString()); 
  out.flush(); 
  out.close(); 

The request still fails. After debugging, it is found that all @RequestParam annotations need to be removed to succeed

conclusion

1. @RequestBody needs to parse all request parameters as json, so it cannot include the writing of key=value. In request url, all request parameters are 1 json

2. When you enter url directly through the browser, the object of json cannot be obtained by @RequestBody. You need to use java programming or request based on ajax method, set ES71en-ES72en to application/json

That's all I have to say about the correct way to use @RequestBody in this article, and I hope it helps. Interested friends can continue to refer to other related topics in this site, if there is any deficiency, welcome to comment out. Thank you for your support!


Related articles: