重定向的网址未显示在浏览器中

时间:2018-12-21 07:07:12

标签: java spring-mvc modelandview

我正在从另一个控制器(分别称为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”。我想显示被调用的网址。

2 个答案:

答案 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";
}
相关问题