SpringMVC - Method可以返回Redirect(String)或ModelAndView

gen*_* b. 2 spring spring-mvc

我的方法做出决定; 在一种情况下,它重定向到URL.在另一种情况下,它必须进行ModelAndView JSP刷新.

这个方法的签名应该是什么?

马上,

public String removeForm(final HttpServletRequest request) throws Exception
{
   if (condition1) {
      return "redirect:/myaction";
   }
   else {
      // Need to do a View, or a ModelAndView?
   }

}
Run Code Online (Sandbox Code Playgroud)

相反,我的方法可能是基于ModelAndView的方法,但我需要在一个案例中返回一个Redirect字符串.如何结合它们?

Ral*_*lph 5

最简单的方法是只使用Object返回类型.

public Object removeForm(final HttpServletRequest request) throws Exception
{
   if (condition1) {
      return "redirect:/myaction";
   } else {
     return new ModelAndView("jspName", modelMap);
   }    
}
Run Code Online (Sandbox Code Playgroud)

但更优雅的是使用ModelAndView和使用RedirectView重定向情况

public ModelAndView removeForm(final HttpServletRequest request) throws Exception
{
   if (condition1) {
      return new ModelAndView(new RedirectView("/myaction"));
   } else {
       return new ModelAndView("jspName", modelMap);
   )
}
Run Code Online (Sandbox Code Playgroud)