在spring Controller 类中重定向到一个url
有些地方都使用
return "redirect:/abc.htm";
.同样使用
return new ModelAndView("redirect:/abc.htm")
.
请哪位大神解释一下这两种说法的异同。
以及它必须在什么情况下使用。
罗希特:
我正在使用 RedirectAttribute 从旧网址获取值。
在这种情况下,使用此 return "redirect:/abc.htm";
时获得值(value)
但不在此return new ModelAndView("redirect:/abc.htm")
中。
RedirectAttributes
最佳答案
声明:
return "redirect:/abc.htm"
return new ModelAndView("redirect:/abc.htm")
做同样的事情:重定向
请求到abc.htm
。如果返回的 View 名称具有
前缀 redirect:
,这被认为是需要重定向的特殊指示。 View 名称的其余部分将被视为重定向 URL。
附言
return "redirect:/abc.htm"
您只能返回重定向 View 名称。
使用 ModelAndView
您可以在一个返回值中同时返回 model
和 view
:
ModelAndView modelAndView = new ModelAndView("redirect:/abc.htm");
modelAndView.addObject("modelAttribute" , new ModelAttribute());
return modelAndView;
但该属性值在客户端(浏览器)将为 URL /abc.htm
发出的新重定向请求中将不可用。 ModelAndView
的最佳用途是当您将请求转发到新的 URL 时,这样您就可以将 model
和 view
一起返回到一个单一的返回值。对于重定向场景,如果要传递属性,应该使用RedirectAttributes
。
关于java - model和view内部redirect和redirect的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19516719/