使用 Spring 3.0,我可以有一个可选的路径变量吗?
例如
@RequestMapping(value = "/json/{type}", method = RequestMethod.GET) public @ResponseBody TestBean testAjax( HttpServletRequest req, @PathVariable String type, @RequestParam("track") String track) { return new TestBean(); }
这里我想/json/abc还是/json调用同样的方法。 一种明显的解决方法声明type为请求参数:
/json/abc
/json
type
@RequestMapping(value = "/json", method = RequestMethod.GET) public @ResponseBody TestBean testAjax( HttpServletRequest req, @RequestParam(value = "type", required = false) String type, @RequestParam("track") String track) { return new TestBean(); }
然后/json?type=abc&track=aa或/json?track=rr将工作
/json?type=abc&track=aa
/json?track=rr
你不能有可选的路径变量,但你可以有两个调用相同服务代码的控制器方法:
@RequestMapping(value = "/json/{type}", method = RequestMethod.GET) public @ResponseBody TestBean typedTestBean( HttpServletRequest req, @PathVariable String type, @RequestParam("track") String track) { return getTestBean(type); } @RequestMapping(value = "/json", method = RequestMethod.GET) public @ResponseBody TestBean testBean( HttpServletRequest req, @RequestParam("track") String track) { return getTestBean(); }