使用Spring,我可以创建一个可选的路径变量吗?
使用Spring,我可以创建一个可选的路径变量吗?
在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
声明为请求参数:
@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
将起作用
admin 更改状态以发布 2023年5月23日
\n\n如果您正在使用Spring 4.1和Java 8,您可以使用被支持在Spring MVC中的@RequestParam
,@PathVariable
,@RequestHeader
和@MatrixVariable
中的java.util.Optional
-。\n
@RequestMapping(value = {"/json/{type}", "/json" }, method = RequestMethod.GET) public @ResponseBody TestBean typedTestBean( @PathVariable Optionaltype, @RequestParam("track") String track) { if (type.isPresent()) { //type.get() will return type value //corresponds to path "/json/{type}" } else { //corresponds to path "/json" } }
你不能有可选的路径变量,但你可以有两个控制器方法调用同一服务代码:
@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(); }