An argument to a Spring MVC method can be declared as RequestBody or RequestParam. Is there a way to say, "Take this value from either the body, if provided, or the URL parameter, if not"? That is, give the user flexibility to pass it either way which is convenient for them.
2 Answers
Answers 1
You can make both variables and check them both for null later on in your code like this :
@RequestMapping(value = GET_SOMETHING, params = {"page"}, method = RequestMethod.GET) public @ResponseBody JSONObject getPromoByBusinessId( @PathVariable("businessId") String businessId, @RequestParam("page") int page, @RequestParam("valid") Boolean valid, @RequestParam("q") String promoName) throws Exception {}
and then use a series if if-else to react to requests. I wrote it to work with any of the three params be null or empty, react to all different scenarios.
To make them optional, see : Spring Web MVC: Use same request mapping for request parameter and path variable
Answers 2
HttpServletRequest interface should help solve this problem
@RequestMapping(value="/getInfo",method=RequestMethod.POST) @ResponseBody public String getInfo(HttpServletRequest request) { String name=request.getParameter("name"); return name; }
Now, based on request data coming from body or parameter the value will be picked up
C:\Users\sushil λ curl http://localhost:8080/getInfo?name=sushil-testing-parameter sushil-testing-parameter C:\Users\sushil λ curl -d "name=sushil-testing-requestbody" http://localhost:8080/getInfo sushil-testing-requestbody C:\Users\sushil λ
0 comments:
Post a Comment