您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

使用Spring可以使路径变量可选吗?

使用Spring可以使路径变量可选吗?

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

@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(
    @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"
    }       
}
Java 2022/1/1 18:17:00 有439人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶