Redirect in Spring MVC

后端 未结 8 2211
遇见更好的自我
遇见更好的自我 2020-11-28 11:00

Why can\'t I get this to work in my Controller

@RequestMapping(method = RequestMethod.POST)
public String onSubmit(
    Model model,
    @ModelAttribute(\"fo         


        
相关标签:
8条回答
  • 2020-11-28 11:43

    Try this, it should work if you have configured your view resolver properly

     return "redirect:/index.html";
    
    0 讨论(0)
  • 2020-11-28 11:43

    For completing the answers, Spring MVC uses viewResolver(for example, as axtavt metionned, InternalResourceViewResolver) to get the specific view. Therefore the first step is making sure that a viewResolver is configured.

    Secondly, you should pay attention to the url of redirection(redirect or forward). A url starting with "/" means that it's a url absolute in the application. As Jigar says,

    return "redirect:/index.html";  
    

    should work. If your view locates in the root of the application, Spring can find it. If a url without a "/", such as that in your question, it means a url relative. It explains why it worked before and don't work now. If your page calling "redirect" locates in the root by chance, it works. If not, Spring can't find the view and it doesn't work.

    Here is the source code of the method of RedirectView of Spring

    protected void renderMergedOutputModel(  
    Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)  
    throws IOException {  
      // Prepare target URL.  
      StringBuilder targetUrl = new StringBuilder();  
      if (this.contextRelative && getUrl().startsWith("/")) {  
        // Do not apply context path to relative URLs.  
        targetUrl.append(request.getContextPath());  
      }  
      targetUrl.append(getUrl());  
    
      // ...  
    
      sendRedirect(request, response, targetUrl.toString(), this.http10Compatible);  
    }  
    
    0 讨论(0)
提交回复
热议问题