为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

繁华开满天机 2019-11-11 14:40:31
在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将工作
查看完整描述

3 回答

?
HUWWW

TA贡献1874条经验 获得超12个赞

您不能具有可选的路径变量,但是可以有两个调用相同服务代码的控制器方法:


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

}


查看完整回答
反对 回复 2019-11-11
?
白板的微信

TA贡献1883条经验 获得超3个赞

如果您在使用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(

    @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"

    }       

}


查看完整回答
反对 回复 2019-11-11
?
FFIVE

TA贡献1797条经验 获得超6个赞

众所周知,您还可以使用@PathVariable批注注入路径变量的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();

    }

}


查看完整回答
反对 回复 2019-11-11
  • 3 回答
  • 0 关注
  • 478 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信