Mapping to app root "/" is failing, but other than that is working

Viewed 178

I'm using Spring Boot 2.5.2. I configured all things (not security, it is auto configured and need to convert all configuration from XML to Java. Authentication is working via LDAP) and working correctly except one thing i.e. mapping to / -> redirect:/main.

Note: This is a migration from Spring to Spring Boot with .jsp as view.

Below is the mapping in XML:

<mvc:view-controller path="/" view-name="redirect:/main" />

Above is working correctly in Spring but when converted to Spring Boot using Java code as below then this specific case is not working:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("redirect:/main");
    }
}

Note: If I set addViewController something else like /documentation then it is redirecting successfully but not with /.

4 Answers

you can use addRedirectViewController

@Configuration
public class WebConfiguration implements WebMvcConfigurer {

@Override
    public void addViewControllers(ViewControllerRegistry registry) {
    registry.addRedirectViewController("/", "redirect:/main");
    }
}

After trying many things, finally got the solution. I need to setOrder() to highest precedence to work. But I still don't know why I need to do this for this specific case. Below is the code:

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/").setViewName("redirect:/main");
    registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
}

When using addRedirectViewController() one have to set url name properly:

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addRedirectViewController("/", "/yourURL");
}
  • but NOT "redirect:/yourURL"
Related