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

12 浏览
0 Comments

使用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日
0
0 Comments

\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 Optional type,
    @RequestParam("track") String track) {      
    if (type.isPresent()) {
        //type.get() will return type value
        //corresponds to path "/json/{type}"
    } else {
        //corresponds to path "/json"
    }       
}

0
0 Comments

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

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

0