[java] Redirect in Spring MVC

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

@RequestMapping(method = RequestMethod.POST)
public String onSubmit(
    Model model,
    @ModelAttribute("form") Form form,
    BindingResult result, HttpServletRequest request)
    throws IOException, WriteException, BiffException {

    if (result.hasErrors()) {
        return "redirect:index.html";
    }

 }

I get:

javax.servlet.ServletException: Could not resolve view with name 'redirect:index.html' in servlet with name 'dispatcher'
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1042)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:798)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:390)

I've got this to work before. Why not now?

This question is related to java spring spring-mvc

The answer is


Try this

HttpServletResponse response;       
response.sendRedirect(".../webpage.xhtml");

i know this is late , but you should try redirecting to a path and not to a file ha ha


Also note that redirect: and forward: prefixes are handled by UrlBasedViewResolver, so you need to have at least one subclass of UrlBasedViewResolver among your view resolvers, such as InternalResourceViewResolver.


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

 return "redirect:/index.html";

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

try to change this in your dispatcher-servlet.xml

<!-- Your View Resolver -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
    <property name="basenames" value="views" />
    <property name="order" value="1" />
</bean>   
<!-- UrlBasedViewResolver to Handle Redirects & Forward -->
<bean id="urlViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView" />
    <property name="order" value="2" />
</bean>        

What happens is clearly explained here http://projects.nigelsim.org/wiki/RedirectWithSpringWebMvc


Axtavt answer is correct.

This is how your resolver should look like (annotations based):

    @Bean
UrlBasedViewResolver resolver(){
    UrlBasedViewResolver resolver = new UrlBasedViewResolver();

    resolver.setPrefix("/views/");
    resolver.setSuffix(".jsp");
    resolver.setViewClass(JstlView.class);

    return resolver;
}

Obviously the name of your views directory should change based on your project.


It is possible to define a urlBasedViewResolver in your properties file:

excel.(class)=fi.utu.seurantaraporttisuodatin.service.Raportti  
index.(class)=org.springframework.web.servlet.view.urlBasedView  
index.viewClass =org.springframework.web.servlet.view.JstlView  
index.prefix = /WEB-INF/jsp/  
index.suffix =.jsp

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to spring

Are all Spring Framework Java Configuration injection examples buggy? Two Page Login with Spring Security 3.2.x Access blocked by CORS policy: Response to preflight request doesn't pass access control check Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Spring Data JPA findOne() change to Optional how to use this? After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName The type WebMvcConfigurerAdapter is deprecated No converter found capable of converting from type to type

Examples related to spring-mvc

Two Page Login with Spring Security 3.2.x ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized The type WebMvcConfigurerAdapter is deprecated RestClientException: Could not extract response. no suitable HttpMessageConverter found Spring boot: Unable to start embedded Tomcat servlet container UnsatisfiedDependencyException: Error creating bean with name 8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)