Java Spring MVC,前进
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2997866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring MVC, forward
提问by user12384512
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";
}
}
采纳答案by skaffman
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.
我发现使用直接方法调用将控制器链接在一起是 Spring 带注释的控制器更吸引人的方面之一,它可以比将转发的请求放在一起更自然的流程。
As always, your mileage may vary.
与往常一样,您的里程可能会有所不同。
回答by davetron5000
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.
通过自己创建控制器,您将防止 Spring 向它们注入任何依赖项。这可能会导致您自己创建的控制器无法正常工作。
If you reallyneed 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.
如果您真的需要像这样链接控制器,我会向 Spring 应用程序上下文询问您想要的控制器实例,而不是使用new
操作符创建一个实例。