Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"error-page" configuration in Spring MVC JavaConfig webapp? (no web.xml)

How would I go about adding "error-page" type configurations to a Spring MVC webapp using Java config? (No web.xml)?

<error-page>
     <error-code>404</error-code>
     <location>/errors/404</location>
</error-page>

I'd like to use a configuration like this (in Java Config) to forward all uncaught Exceptions to a specific controller method.

I was hoping to avoid the @ControllerAdvice / @ExceptionHandler configuration (which allows me to create a controller method that would handle ALL errors) because I'd like Access Denied exceptions to continue to be caught by Spring Security, and just let any other exceptions get handled by my code.

It looks like a similar question was asked here: Spring JavaConfig is not catching PageNotFound?

like image 301
Dan Avatar asked Oct 09 '13 19:10

Dan


2 Answers

look at https://java.net/jira/browse/SERVLET_SPEC-50 - it's not possible to configure that without web.xml, but you can create manual filter that will do same thing for you.

like image 132
Alexander Kudrevatykh Avatar answered Nov 14 '22 22:11

Alexander Kudrevatykh


You can create SimpleMappingExceptionResolver bean, and set pages for http errors, without using web.xml. Or default views for any exceptions. Here:

    @Bean
    public SimpleMappingExceptionResolver simpleMappingExceptionResolver(){

    SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();

    //page and statusCode pare 
    //you also can use method setStatusCodes(properties)
    resolver.addStatusCode(viewName, statusCode); 

    //set views for exception 
    Properties mapping = new Properties();
    mapping.put("ua.package.CustomException" , "page")    
    resolver.setExceptionsMapping(mapping); 

    return resolver;
    }
like image 33
Yaroslav Avatar answered Nov 14 '22 23:11

Yaroslav