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
- @RequestMapping(“doThis”)
- public String doThis(HttpServletRequest request,
- @requestParam (“id”) Long id, // user id
- @requestParam (” back_URL “) String back_URL, // Callback address
- @requestBody TestEntity jSON_data // JSON data, for Java entity classes
- {/ /…
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
- 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 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