使用Spring,我可以创建一个可选的路径变量吗?

在Spring 3.0中,我可以有一个可选的path变量吗?


例如


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


繁华开满天机
浏览 483回答 3
3回答

HUWWW

您不能具有可选的路径变量,但是可以有两个调用相同服务代码的控制器方法:@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();}

白板的微信

如果您在使用Spring 4.1和Java 8,你可以使用java.util.Optional它支持@RequestParam,@PathVariable,@RequestHeader和@MatrixVariableSpring MVC中-@RequestMapping(value = {"/json/{type}", "/json" }, method = RequestMethod.GET)public @ResponseBody TestBean typedTestBean(&nbsp; &nbsp; @PathVariable Optional<String> type,&nbsp; &nbsp; @RequestParam("track") String track) {&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; if (type.isPresent()) {&nbsp; &nbsp; &nbsp; &nbsp; //type.get() will return type value&nbsp; &nbsp; &nbsp; &nbsp; //corresponds to path "/json/{type}"&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; //corresponds to path "/json"&nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp;}

FFIVE

众所周知,您还可以使用@PathVariable批注注入路径变量的Map。我不确定该功能是否在Spring 3.0中可用或是否在以后添加,但是这是解决示例的另一种方法:@RequestMapping(value={ "/json/{type}", "/json" }, method=RequestMethod.GET)public @ResponseBody TestBean typedTestBean(&nbsp; &nbsp; @PathVariable Map<String, String> pathVariables,&nbsp; &nbsp; @RequestParam("track") String track) {&nbsp; &nbsp; if (pathVariables.containsKey("type")) {&nbsp; &nbsp; &nbsp; &nbsp; return new TestBean(pathVariables.get("type"));&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; return new TestBean();&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP