HOWTO handle 404 exceptions globally using Spring MVC configured using Java based Annotations

后端 未结 5 1902
眼角桃花
眼角桃花 2021-01-02 03:05

I am building a Spring 4 MVC app. And it is completely configured using Java Annotations. There is no web.xml. The app is configured by using instance of

5条回答
  •  难免孤独
    2021-01-02 03:57

    I can't comment on the above post by @Ysak (reputation<50), however I can confirm that this method does work with the setup described by the OP.

    I will add that from another guide I also had the DefaultServletHandling configured in my WebConfig to fix a separate issue, as below:

    @Configuration
    @EnableWebMvc
    @ComponentScan("com.acme.tat.controllers")
    public class WebConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware {
    ...
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
            configurer.enable();
    }
    
    }
    

    With this set to enable, there is no Exception thrown. Once I removed this line and set up manual resourceHandlers everything worked as expected.

    It took me around 2.5 hours to set up 404 redirecting because of this simple one line method.

提交回复
热议问题