This article mainly studies the relevant content about the correct use of @RequestBody, as follows.
Recently, I was taking over a job with a colleague who was about to leave. The project I took over was built with SpringBoot. I saw this writing method:
@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 class){//...This is a request mapping method, and then enter url with the browser: http://127.0.0.1:8080/test/doThis?id=1&back_url=url&json_data={"code":2,"message":"test"}
In this method, use @RequestParam to get the parameters, and then use @RequestBody to convert the parameters in json format to Java type
When running, the error was found: Required request body is missing
@RequestBody requires the use of MappingJackson2HttpMessageConverter to load, but SpringBoot's official documentation mentions that this is already loaded by default, and there are no errors in writing json strings and javabeans.
Therefore, considering that it should be a problem of requesting Content-Type, because there is no way to define Content-Type by using the browser to enter the URL, spring cannot find the request body
To confirm this idea, write a request class yourself:
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. After debugging, I found that all @RequestParam annotations need to be removed to succeed.
Summarize
1. @RequestBody needs to parse all request parameters as json. Therefore, the key=value cannot be included in the request url. All request parameters are a json
2. When entering url directly through the browser, @RequestBody cannot get the json object. You need to use Java programming or ajax-based method request, and set Content-Type to application/json
The above is all about interpreting the correct usage of @RequestBody, and I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!