如何在Spring MVC的请求映射中检查URI中的PathVariable?

时间:2017-06-08 07:28:15

标签: spring spring-mvc

在我的控制器中有这样的代码。

@RequestMapping(value = "/{scene}/{function}/**")
    public void processProxyCall(@PathVariable("scene") final String scene, @PathVariable("function") final String function,
        final HttpServletRequest request,final HttpServletResponse response) throws IOException {
    ...
}

在测试阶段,{scene}的可能值为“sit”或“uat”。在阶段中还有一些额外的逻辑来处理这个变量。 所以它非常适合这种URI“/ sit / student / add”。场景是坐着的,功能就是学生。

但是在制作中不再有“坐”或“uat”,在这种情况下,URI将是“/ student / add”。也无需处理场景变量。

问题是如何在上面的代码片段中对PathVariable“scene”进行一些检查。如果是生产情况,场景将自动映射到“学生”,这是非常错误的。

我正在尝试添加另一个RequestMapping来处理生产案例,并保持测试不变。但得到了404 ......

@RequestMapping(value = "/{function}/**")
    public void processProxyCall(@PathVariable("function") final String function, final HttpServletRequest request,
            final HttpServletResponse response) throws IOException {
}

1 个答案:

答案 0 :(得分:0)

@RequestMapping(value = {"/{scene}/{function}/**", "/{function}/**"})
public void processProxyCall(@PathVariable(value="scene", required=false) final String scene, @PathVariable("function") final String function,
        final HttpServletRequest request,final HttpServletResponse response) throws IOException {
    ...
}

定义多个映射并生成scene路径变量required=false

更新:

@RequestMapping(value = "/{scene}/{function}/**")
public void processProxyCall(@PathVariable(value="scene", required=false) final String scene, @PathVariable("function") final String function,
        final HttpServletRequest request,final HttpServletResponse response) throws IOException {
    ...
}

@RequestMapping(value = "/{function}/**")
public void processProxyCallShort(@PathVariable(value="scene", required=false) final String scene, @PathVariable("function") final String function,
        final HttpServletRequest request,final HttpServletResponse response) throws IOException {
    processProxyCall(null, function, request, response);
}