Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@RequestParam spring MVC , make one of two request params mandatory

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.

like image 707
Nikhil Avatar asked Jan 08 '15 16:01

Nikhil


People also ask

Is request Param mandatory?

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.

What is the difference between @RequestParam and @ModelAttribute?

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.

What is difference between @RequestParam and @PathVariable?

1) The @RequestParam is used to extract query parameters while @PathVariable is used to extract data right from the URI.

What is the difference between @RequestParam and @RequestBody?

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.


1 Answers

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";
}
like image 133
f.khantsis Avatar answered Nov 12 '22 07:11

f.khantsis