我正在从另一个控制器(分别称为controller1和controller2)调用一个控制器的视图。它已成功运行,但是即使我重定向到controller2,浏览器也会显示controller1的URL。如何更改呢?
@Controller
@SessionAttributes
public class UserFormController {
@Autowired
private UserService userService;
@Autowired
private Controller2 controller2;
@RequestMapping(value = "/method1", method = RequestMethod.GET)
public ModelAndView redirectFormPage() {
return controller2.redirectMethod();
}
此处显示的是网址“ method1”。我想显示被调用的网址。
答案 0 :(得分:0)
controller2.redirectMethod()的作用是什么?
代替直接从控制器调用方法,而是使用它并将URL放入redirectMethod(redirectURL)
return new ModelAndView("redirect:/redirectURL");
或
return "redirect:/redirectURL"
取决于您返回的物品
在您的情况下,它将被视为常规方法。
控制器1:
@Controller
@RequestMapping("/")
public class Controller11 {
@RequestMapping("/method1")
public String method1(Model model) {
return "redirect:/method2";
// If method return ModelAndView
// return new ModelAndView("redirect:/method2");
}
}
Controller2:
@Controller
public class Controller22 {
@RequestMapping("/method2")
public String method1(Model model) {
model.addAttribute("method", "method2");
return "method";
//If method return ModelAndView
// model.addAttribute("method", "method2");
// return new ModelAndView("method");
}
}
查看:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Method1</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'Method, ' + ${method} + '!'" />
</body>
</html>
答案 1 :(得分:0)
在Controller2
中编写另一个处理程序,该处理程序将调用redirectMethod()
。
在Controller2
中:
@RequestMapping(value = "/redirectFromUser", method = RequestMethod.GET)
public ModelAndView handleRedirectionFromUser() {
return redirectMethod();
}
在UserFormController
中:
@RequestMapping(value = "/method1", method = RequestMethod.GET)
public String redirectFormPage() {
return "redirect:/url/to/redirectFromUser";
}