The correct use of @requestBody in SpringBoot

 

Recently, I received a job from a colleague who was leaving the company. The project I took over was built by SpringBoot, and I saw the following in it:

 

[java]
view plain
copy

  1. @RequestMapping(“doThis”)  
  2. public String doThis(HttpServletRequest request,  
  3. @requestParam (“id”) Long id, // user id
  4. @requestParam (” back_URL “) String back_URL, // Callback address
  5. @requestBody TestEntity jSON_data // JSON data, for Java entity classes
  6. {/ /…

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

 

In this method, @RequestParam is used to get the parameters, and @RequestBody is used to convert the JSON-formatted parameters to Java types

 

Error found at runtime: Required Request body is missing

 

@ RequestBody use needs to be loaded MappingJackson2HttpMessageConverter, but SpringBoot official documentation mentioned, this is the default has been loaded, and json string and javabean also not writing errors

 

Therefore, spring cannot find the Request body because there is no way to define the Content-Type using the way the browser typed the URL

 

To verify this idea, write your own request class:

 

[java]
view plain
copy

  1. String add_url = “http://127.0.0.1:8080/test/doThis”;  
  2.    URL url = new URL(add_url);  
  3.    HttpURLConnection connection = (HttpURLConnection)url.openConnection();  
  4.    connection.setDoInput(true);  
  5.    connection.setDoOutput(true);  
  6.    connection.setRequestMethod(“POST”);  
  7.    connection.setUseCaches(false);  
  8.    connection.setInstanceFollowRedirects(true);  
  9.    connection.setRequestProperty(“Content-Type”,”application/json”);  
  10.    connection.connect();  
  11.    DataOutputStream out = new DataOutputStream(connection.getOutputStream());  
  12.    JSONObject obj = new JSONObject();  
  13.       
  14.    obj.put(“code”, -1002);       
  15.    obj.put(“message”, “msg”);  
  16.    out.writeBytes(obj.toString());  
  17.    out.flush();  
  18.    out.close();  

The request still failed, and after debugging it was found that all @requestParam annotations needed to be removed to succeed

 

Conclusion:

1. @requestBody needs to parse all request parameters as JSON, so you can’t include key=value in the request URL. All request parameters are json

2. If you input the URL directly from the browser, @requestBody will not get the JSON object, so you need to use Java programming or Ajax-based method to request, and set the content-type to Application/JSON