Spring 3.0转发请求到不同的控制器

Ant*_*ony 28 java spring-mvc

在春天将请求转发给不同控制器的正确方法是什么?

@RequestMapping({"/someurl"})
public ModelAndView execute(Model model) {
    if (someCondition) {
        //forward to controller A
    } else {
        //forward to controller B
    }
}
Run Code Online (Sandbox Code Playgroud)

所有控制器都有Spring注入的依赖项,所以我不能自己创建它们并自己调用它们,但我希望将请求属性传递给其他控制器.

Joh*_*int 37

尝试返回一个String,而String则是前向url.

@RequestMapping({"/someurl"})
public String execute(Model model) {
    if (someCondition) {
        return "forward:/someUrlA";
    } else {
        return "forward:/someUrlB";
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这里是RedirectView的Spring 3.0.x文档的链接,其中还包括:forward.http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#mvc-redirecting (2认同)

Eug*_*hov 6

您可以使用视图名称,如"redirect:controllerName"或"forward:controllerName".后者将重新路由请求到另一个控制器,前者将告诉浏览器将请求重定向到另一个URL.

docs:https://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#mvc-redirecting-redirect-prefix