Spring MVC, forward

情到浓时终转凉″ 提交于 2020-01-10 00:51:09

问题


Is there any difference between

public class Controller1 extends AbstractController {
    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        return new AnotherController().handleRequest(request, response);
    }
}

and

@Controller
public class Controller1 {

    @RequestMapping ...
    public String handleRequest() {
        return "forward:/path_to_my_another_controller";
    }
}

回答1:


They're similar, but not quite the same.

The second approach will create a new internal request to be forwarded on to the second controller, whereas the first one will re-use the same request object.

Whether or not that matters depends on what each of the controllers does to the request.

I've found that chaining controllers together using direct method calls is one of the more appealing aspects of Spring annotated controllers, it can make for a much more natural flow than chucking forwarded requests around.

As always, your mileage may vary.




回答2:


By creating controllers yourself, you will prevent Spring from injecting any dependencies into them. This may cause your self-created controllers to not work correctly.

If you really need to chain controllers like this, I would ask the Spring application context for an instance of the controller you want instead of creating one with the new operator.



来源:https://stackoverflow.com/questions/2997866/spring-mvc-forward

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!