如何定义RequestMapping优先级

Jam*_*ore 6 java spring spring-mvc

我有一种情况,我需要以下内容RequestMapping:

@RequestMapping(value={"/{section}"})
...method implementation here...

@RequestMapping(value={"/support"})
...method implementation here...
Run Code Online (Sandbox Code Playgroud)

有一个明显的冲突.我希望Spring会自动解决这个问题并映射/support到第二个方法,并将其他所有内容映射/support到第一个方法,但它会映射到第一个方法.

我如何告诉Spring允许显式RequestMapping覆盖RequestMappinga PathVariable在同一个地方?

编辑2:如果/support映射在映射之前出现,它似乎会起作用/{section}.不幸的是,我们有许多控制器包含许多方法RequestMapping.如何确保具有/{section}映射的控制器最后被初始化?或者预拦截器是否可行?

编辑1:这是简化的,我知道RequestMapping单凭这两个人就没有多大意义了)

小智 4

使用 Spring,您可以扩展 org.springframework.web.HttpRequestHandler 来支持您的场景。

实现方法:

@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
Run Code Online (Sandbox Code Playgroud)

使用它来分析传入的请求,确定请求 url 是否是请求 url 的特殊子集的一部分,并将其转发到适当的位置。

前任:

@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
/** You will want to check your array of values and have this data cached  **/
if (urlPath.contains("/sectionName")) {
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("sections" + "/" + urlPath);
        requestDispatcher.forward(request, response);
    }

}
Run Code Online (Sandbox Code Playgroud)

并设置您的部分,例如:

@RequestMapping(value={"/sections/{sectionName}"})
Run Code Online (Sandbox Code Playgroud)

这不会干扰任何预先存在的控制器映射。