使用Spring 3.0,我可以创build一个可选的pathvariables吗?

使用Spring 3.0,我可以有一个可选的pathvariables?

例如

@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将会工作

你不能有可选的pathvariables,但你可以有两个控制器方法调用相同的服务代码:

 @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(); } 

不知道你也可以使用@PathVariable注解来注入pathvariables的Map。 我不确定这个特性在Spring 3.0中是否可用,或者是否在以后添加,但这里有另外一种方法来解决这个例子:

 @RequestMapping(value={ "/json/{type}", "/json" }, method=RequestMethod.GET) public @ResponseBody TestBean typedTestBean( @PathVariable Map<String, String> pathVariables, @RequestParam("track") String track) { if (pathVariables.containsKey("type")) { return new TestBean(pathVariables.get("type")); } else { return new TestBean(); } } 

如果您使用Spring 4.1和Java 8,则可以使用Spring MVC中@PathVariable@RequestHeader @MatrixVariable@PathVariable@MatrixVariable支持的java.util.Optional

 @RequestMapping(value = {"/json/{type}", "/json" }, method = RequestMethod.GET) public @ResponseBody TestBean typedTestBean( @PathVariable Optional<String> type, @RequestParam("track") String track) { if (type.isPresent()) { //type.get() will return type value //corresponds to path "/json/{type}" } else { //corresponds to path "/json" } } 

你可以使用:

 @RequestParam(value="somvalue",required=false) 

可选参数而不是pathVariable

检查这个Spring 3 WebMVC – 可选pathvariables 。 它显示了一个对AntPathMatcher进行扩展以启用可选pathvariables的文章,可能有帮助。 所有学分塞巴斯蒂安Herold张贴文章。

 $.ajax({ type : 'GET', url : '${pageContext.request.contextPath}/order/lastOrder', data : {partyId : partyId, orderId :orderId}, success : function(data, textStatus, jqXHR) }); @RequestMapping(value = "/lastOrder", method=RequestMethod.GET) public @ResponseBody OrderBean lastOrderDetail(@RequestParam(value="partyId") Long partyId,@RequestParam(value="orderId",required=false) Long orderId,Model m ) {}