【问题标题】:Redirected url not showing in browser重定向的网址未在浏览器中显示
【发布时间】:2018-12-21 07:07:12
【问题描述】:

我正在从另一个控制器(分别是控制器 1 和控制器 2)调用一个控制器的视图。它可以成功运行,但即使我重定向到控制器 2,浏览器也会显示控制器 1 的 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();

}

这里显示的是 url “method1”。我想显示被调用的url。

【问题讨论】:

    标签: java spring-mvc modelandview


    【解决方案1】:

    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");
        }
    }
    

    控制器2:

    @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>
    

    【讨论】:

    • 我得到一个空白页
    【解决方案2】:

    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";
    }
    

    【讨论】:

    • 我无法在控制器 1 中返回字符串,因为正在重定向检查条件
    • @Jiji 你可以做return new ModelAndView("redirect:/url/to/redirectFromUser");
    • 实际上我的代码正在运行,但唯一的问题是,浏览器显示 url /method1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-07
    • 2016-01-02
    • 1970-01-01
    • 2017-05-15
    • 2013-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多