触发默认控制器以获取所有汽车的普通uri只是"/ cars"
我希望能够搜索汽车以及uri,例如:"/ cars?model = xyz",它将返回匹配汽车列表.所有请求参数都应该是可选的.
问题是,即使使用查询字符串,默认控制器仍会触发,我总是得到"所有汽车:......"
有没有办法用Spring做这个没有单独的搜索uri(比如"/ cars/search?..")?
码:
@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();
}
}
Run Code Online (Sandbox Code Playgroud)
Sot*_*lis 11
您可以使用
@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
}
Run Code Online (Sandbox Code Playgroud)
即,@RequestMapping注释具有一个名为的属性params.如果您指定的所有参数都包含在您的请求中(并且所有其他RequestMapping要求都匹配),那么将调用该方法.