Correct use of @RequestBody in Springboot
Recently received a job to leave a colleague, took over the project was built with Springboot, which saw this writing:
[Java]View PlainCopy
- @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 enter url:http://127.0.0.1:8080/test/dothis?id=1&back_url=url&json_data={"code" with the browser: 2, " Message ":" Test "}
In this method, use @requestparam to get the parameters and then use @requestbody to convert the JSON-formatted parameters to Java types
Error found at run time: Required request body is missing
The use of the @RequestBody needs to load Mappingjackson2httpmessageconverter, but Springboot's official documentation mentions that this is already loaded by default, And the JSON string and the JavaBean have no written errors.
So consider the question of requesting content-type because there is no way to define content-type by using a browser to enter a URL, so spring cannot find the request body
To prove the idea, write a request class yourself:
[Java]View PlainCopy
- 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 ();
Request or failure, after debugging, find that all @requestparam annotations need to be removed to succeed
Summarize:
1, @RequestBody need to parse all the request parameters as JSON, therefore, cannot contain key=value such a notation in the request URL, all request parameters are a JSON
2, directly through the browser input URL, @RequestBody get not JSON object, need to use Java programming or AJAX-based method request, set Content-type to Application/json
Correct use of @RequestBody in Springboot