java 将请求转发到 Spring MVC 中的另一个控制器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31796952/
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
Forward request to another controller in Spring MVC
提问by sublime
I'd like to know if there is a way I can forward a request from one controller to another without actually changing the URL in the browser.
我想知道是否有一种方法可以将请求从一个控制器转发到另一个控制器,而无需实际更改浏览器中的 URL。
@RequestMapping(value= {"/myurl"})
public ModelAndView handleMyURL(){
if(somecondition == true)
//forward to another controller but keep the url in the browser as /myurl
}
examples that I found online were redirecting to another url which was causing other controllers to handle that. I don't want to change the URL.
我在网上找到的示例重定向到另一个 url,这导致其他控制器处理它。我不想更改 URL。
回答by Harshal Patil
Try to return a String
instead of ModelAndView
, and the String being the forward url.
尝试返回 aString
而不是ModelAndView
,并且 String 是前向 url。
@RequestMapping({"/myurl"})
public String handleMyURL(Model model) {
if(somecondition == true)
return "forward:/forwardURL";
}
回答by xtian
Instead of forwarding, you may just call the controller method directly after getting a reference to it via autowiring. Controllers are normal spring beans:
您可以在通过自动装配获得对控制器方法的引用后直接调用控制器方法,而不是转发。控制器是普通的 spring bean:
@Controller
public class MainController {
@Autowired OtherController otherController;
@RequestMapping("/myurl")
public String handleMyURL(Model model) {
otherController.doStuff();
return ...;
}
}
@Controller
public class OtherController {
@RequestMapping("/doStuff")
public String doStuff(Model model) {
...
}
}
回答by Aditya
As far as I know "forward" of a request will be done internally by the servlet, so there will not be a second request and hence the URL should remain the same. Try using the following code.
据我所知,请求的“转发”将由 servlet 在内部完成,因此不会有第二个请求,因此 URL 应该保持不变。尝试使用以下代码。
@RequestMapping(value= {"/myurl"})
public ModelAndView handleMyURL(){
if(somecondition == true){
return new ModelAndView("forward:/targetURL");
}
}