In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "how to use SpringBoot parameter passing and @ RequestBody annotations". In daily operation, I believe many people have doubts about how to use SpringBoot parameter passing and @ RequestBody annotations. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "how to use SpringBoot parameter passing and @ RequestBody annotations". Next, please follow the editor to study!
Note that the correct js writing format for the foreground is / / Click query, execute the following function $("# searchByCriteria") .click (function () {/ / var paramdata = $("# bck_qry_criteria_form") .serializeJson () / / serializeJson () is a custom form formatted as the json function var paramdata = {type:$ ("# bck_type"). Val (), title:$ ("# bck_title"). Val (), start:$ ("# bck_start"). Val (), end:$ ("# bck_end"). Val ()}; paramdata = JSON.stringify (paramdata) $.ajax ({type: "post", data: paramdata, url: "/ getNews", cache:false, headers: {"Content-Type": "application/json;charset=utf-8"}, success: function (data) {var code = data.code; var t = data.t If (code = = 200) {alert (JSON.stringify ("submitted successfully! We will contact you as soon as possible! ");} if (code = = 500) {alert (JSON.stringify (t));} / $(" # input_phone ") .val ("); / / clear the input box}})
The parameters passed above must use JSON.stringify (paramdata); the method converts the parameters to a string in json format; because the @ RequestBody annotation in SpringBoot requires a string in json format to inject parameters, and the second is Tai Keng. The request header must be included in the request, otherwise the following error will be reported.
Org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported
The correct Controller writing format in the background is
Where consumes = "application/json", the specification is to be added, it is standardized, the foreground to pass parameters in json format. But if you don't have to add it, you can encapsulate it into the parameter .NewsParamsMap.
@ PostMapping (value = "/ getNews", consumes = "application/json") @ ResponseBodypublic PageInfo getNewsList (@ RequestBody NewsParamsMap map) {System.out.println ("this is the correct usage"); return null;}
In NewsParamsMap, there are Integer and Date, and all the strings passed from the foreground, springboot, will convert the data to the corresponding type according to the one-to-one correspondence of names.
Public class NewsParamsMap {private Integer type; private String title; private Date start; private Date end;... Set get method.}
RequestBody is used as a parameter
Recently, I was receiving a job from a former colleague. The project I took over was built in SpringBoot, and I saw the following words:
View the code chip derived from my code chip on CODE
@ 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 to enter url:
Http://127.0.0.1:8080/test/doThis?id=1&back_url=url&json_data={"code":2,"message":"test"}
In this method, you use @ RequestParam to get parameters, and then use @ RequestBody to convert parameters in json format to Java types
Found an error at run time: Required request body is missing
The use of @ RequestBody requires loading MappingJackson2HttpMessageConverter, but the official documentation of SpringBoot mentions that this has been loaded by default, and there are no writing errors in the json string and javabean
Therefore, considering that it should be the problem of requesting Content-Type, because there is no way to define Content-Type in the way you enter url in a browser, spring cannot discover request body
To prove this idea, write a request class yourself
View the code chip derived from my code chip on CODE
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, it was found that all @ RequestParam annotations needed to be removed in order to succeed.
Make a brief summary
1. @ RequestBody needs to parse all request parameters as json, so it cannot be written like key=value. 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 to request, and set Content-Type to application/json.
At this point, the study on "how to use SpringBoot parameter passing and @ RequestBody annotations" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.