404 error redirect in Spring with java config

2019-01-05 02:59发布

As you know, in XML, the way to configure this is:

<error-page>
    <error-code>404</error-code>
    <location>/my-custom-page-not-found.html</location>
</error-page>

But I haven't found a way to do it in Java config. The first way I tried was:

@RequestMapping(value = "/**")
public String Error(){
    return "error";
}

And it appeared to work, but it has conflicts retrieving the resources.

Is there a way to do it?

7条回答
太酷不给撩
2楼-- · 2019-01-05 03:29

For Java config there is a method setThrowExceptionIfNoHandlerFound(boolean throwExceptionIfNoHandlerFound) in DispatcherServlet. By settting it to true I guess you are doing same thing

<init-param>
    <param-name>throwExceptionIfNoHandlerFound</param-name>
    <param-value>true</param-value>
</init-param>

then you can can this NoHandlerFoundException.class in controller advice as stated in above answer

it will be like something

public class WebXml implements WebApplicationInitializer{

    public void onStartup(ServletContext servletContext) throws ServletException {
        WebApplicationContext context = getContext();
        servletContext.addListener(new ContextLoaderListener(context));


        DispatcherServlet dp =  new DispatcherServlet(context);
        dp.setThrowExceptionIfNoHandlerFound(true);

        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", dp);
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping(MAPPING_URL);
    }
}
查看更多
登录 后发表回答