I am writing a service wherein I take in either an id or a location and I want to enforce the constraint that either the id or the location must be specified in my @Controller
@Controller
public class HelloController {
@RequestMapping(value="/loc.json",method = RequestMethod.GET)
public @ResponseBody String localiaztionRequest(@RequestParam(value = "location", required = false) String callback
,@RequestParam(value = "id", required = false) String uuid
,@RequestParam(value = "callback", required = false) String callback) {
//model.addAttribute("message", "Hello world!");
return "hello";
}
For clarity, I want each request to send either the location parameter or the id parameter. How do I enforce such a constraint on a pair of input parameters? Also as an aside could someone please explain to me the use of ModelMap , what is the effect of model.addAttribute("message","Hello World!") ? Sorry if the questions seem rather naive, I'm extremely new to the spring framework.
Thanks in advance.
Method parameters annotated with @RequestParam are required by default. will correctly invoke the method. When the parameter isn't specified, the method parameter is bound to null.
When you have a method annotated with @ModelAttribute , it is being called every time code hits that servlet. When you have @ModelAttribute as one of the method's parameters, we are talking about incoming Http form data-binding. Calling @RequestParam is a shortcut for saying request.
1) The @RequestParam is used to extract query parameters while @PathVariable is used to extract data right from the URI.
So basically, while @RequestBody maps entire user request (even for POST) to a String variable, @RequestParam does so with one (or more - but it is more complicated) request param to your method argument.
I think you should split it into two different controller methods
@RequestMapping(value="/loc.json",method = RequestMethod.GET, params={"location"})
public @ResponseBody String localizationRequestByLoc(@RequestParam String location, @RequestParam String callback) {
//model.addAttribute("message", "Hello world!");
return "hello";
}
@RequestMapping(value="/loc.json",method = RequestMethod.GET, params={"id"})
public @ResponseBody String localizationRequestById(@RequestParam String id, @RequestParam String callback) {
//model.addAttribute("message", "Hello world!");
return "hello";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With