[英]Spring REST-ful uri with optional querystring
The normal uri which triggers the default controller to get all cars is just "/cars" 触发默认控制器以获取所有汽车的普通uri只是“/ 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. 我希望能够搜索汽车以及uri,例如:“/ cars?model = xyz”,它将返回匹配汽车列表。 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?..")? 有没有办法用Spring做这个没有单独的搜索uri(比如“/ 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
. 即,@ @RequestMapping
注释具有一个名为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. 如果您指定的所有参数都包含在您的请求中(并且所有其他RequestMapping
要求都匹配),那么将调用该方法。
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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.