The normal uri which triggers the default controller to get all cars is just "/cars"
I want to be able to search for cars aswell with an uri, for example: "/cars?model=xyz" which would return a list of matching cars. All the request parameters should be optional.
The problem is that even with the querystring the default controller triggers anyway and I always get "all cars: ..."
Is there a way to do this with Spring without a separate search uri (like "/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();
}
}
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
}
ie, the @RequestMapping
annotation has a property called params
. If all of the parameters that you specify are contained in your request (and all other RequestMapping
requirements match), then that method will be called.
Try a variation of this:
@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);
}
}
}
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