Spring REST-ful uri with optional request

The usual uri that starts the default controller to get all the cars is just "/ cars"

I want to be able to search for cars, as well as uri, for example: "/ cars? Model = xyz", which will return a list of suitable cars. All query parameters must be optional.

The problem is that even when requesting a request, the controller starts up by default anyway, and I always get "all cars: ..."

Is there any way to do this using Spring without a separate search uri (for example, "/ cars / search? ..")?

code:

@Controller @RequestMapping("/cars") public class CarController { @Autowired private CarDao carDao; @RequestMapping(method = RequestMethod.GET, value = "?") public final @ResponseBody String find( @RequestParam(value = "reg", required = false) String reg, @RequestParam(value = "model", required = false) String model ) { Car searchForCar = new Car(); searchForCar.setModel(model); searchForCar.setReg(reg); return "found: " + carDao.findCar(searchForCar).toString(); } @RequestMapping(method = RequestMethod.GET) public final @ResponseBody String getAll() { return "all cars: " + carDao.getAllCars().toString(); } } 
+4
source share
2 answers

Try the option:

  @Controller @RequestMapping("/cars") public clas CarController { @RequestMapping(method = RequestMethod.get) public final @ResponseBody String carsHandler( final WebRequest webRequest) { String parameter = webRequest.getParameter("blammy"); if (parameter == null) { return getAll(); } else { return findCar(webRequest); } } } 
+1
source

you can use

 @RequestMapping(method = RequestMethod.GET, params = {/* string array of params required */}) public final @ResponseBody String find(@RequestParam(value = "reg") String reg, @RequestParam(value = "model") String model) // logic } 

those. @RequestMapping annotation has a property called params . If all of the specified parameters are contained in the request (and all other RequestMapping requirements are the same), then this method will be called.

+11
source

Source: https://habr.com/ru/post/1469292/


All Articles