[英]How to call one controller method in another controller with RedirectAttributes
Code i have written as below. 我写的代码如下。
Controller1 {
@Autowired
Controller2 controller2
//Caller method
void method1() {
controller2.furnction1(model,redirectattributes);
}
}
Controller2 {
public void function1(Model model, RedirectAttributes atr){
}
}
Question is: How to intialize RedirectAttributes ( redirectattributes )in my new Controller( Controller1 ). 问题是:如何在我的新Controller( Controller1 )中初始化RedirectAttributes ( redirectattributes )。 My Controller1 is not a form submit, so that i couldn't get RedirectAttributes by default.
我的Controller1不是表单提交,因此默认情况下我无法获取RedirectAttributes 。
How to call the funcation1 in controller2. 如何在controller2中调用funcation1。
Redirect will not work here. 重定向在这里不起作用。 All the form data will be lost.
所有表格数据将丢失。 Try forwarding request to another URL.
尝试将请求转发到另一个URL。
try something like 尝试类似
Controller1 {
@RequestMapping("url1")
public String method1() {
return "forward:/url2";
}
}
Controller2 {
@RequestMapping("/url2")
public String function1(Model model, RedirectAttributes atr){
//do something
}
}
In my opinion calling a Controller from another Controller is not a good practice. 我认为从另一个主计长调来一个主计长不是一个好习惯。 Try using return redirect:/function1 to call the function1 inside Controller2.
尝试使用return redirect:/ function1在Controller2内部调用function1。 If it is a common function / service try writing a helper which would do your job.
如果这是一种常见的功能/服务,请尝试编写一个可以帮助您完成工作的助手。
What RedirectAttributes as to do with POST request ? 与POST请求相关的RedirectAttributes是什么?
Just add it to your first controller method as parameter. 只需将其作为参数添加到您的第一个控制器方法中即可。
void method1(RedirectAttributes redirectattributes) {
controller2.furnction1(model,redirectattributes);
} }
But at the other said, it's not a good pattern, and you should use something like : 但对方说,这不是一个好的模式,您应该使用类似以下内容的代码:
return "redirect:/some/url";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.