Mrugank
Mrugank

Reputation: 43

Spring java based configuration for custom error pages

I have created a CustomErrorHandler bean that extends org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver as a replacement for xml based configuration for handling custom error pages.The bean class is registered inside WebInitializer which is a web.xml equivalent.The problem is that i am unable to view the custom error pages that i have designed when a '404' exception is occurred or any of those that i have configured to handle in the bean class.

This is the code for my CustomErrorHandler bean class and WebInitializer:

CustomErrorHandler.java:

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;

public class CustomHandlerExceptionResolver extends DefaultHandlerExceptionResolver {


    private static final Logger logger = LoggerFactory
            .getLogger(CustomHandlerExceptionResolver.class);

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request,
                                              HttpServletResponse response,
                                              Object handler,
                                              Exception ex) {
        try {

            if (ex instanceof java.lang.Throwable) {

                return new ModelAndView("redirect:/uncaughtException");
            } else if (ex instanceof java.lang.Exception) {

                return new ModelAndView("redirect:/uncaughtException");
            } else if (response.getStatus()==404) {

                return new ModelAndView("redirect:/resourceNotFound");
            } else if (response.getStatus()==500) {

                return new ModelAndView("redirect:/resourceNotFound");
            }             //end webflow
            //error 500
            else if (ex instanceof org.springframework.context.ApplicationContextException) {
                logger.warn("applicationcontextexception");
                return new ModelAndView("redirect:/resourceNotFound");
            }
            //end error 500

            //default
            return super.doResolveException(request, response, handler, ex);
        }
        catch (Exception handlerException) {
            logger.warn("Handling of [" + ex.getClass().getName() + "] resulted in Exception", handlerException);
        }
        return null;
    }


}

WebInitializer.java:

import java.util.EnumSet;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
import javax.servlet.SessionTrackingMode;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.web.session.HttpSessionEventPublisher;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.servlet.DispatcherServlet;

import com.knowesis.sift.service.util.PropertyFileReader;

public class WebInitializer implements WebApplicationInitializer {


    @Autowired
    PropertyFileReader propertyfilereader;



    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {

        Set<SessionTrackingMode> modes = EnumSet.noneOf(SessionTrackingMode.class);
        modes.add(SessionTrackingMode.COOKIE);

        AnnotationConfigWebApplicationContext ctx=new AnnotationConfigWebApplicationContext();
       // ctx.register(PropertyFileReaderConfig.class);
       //   ctx.register(RootContext.class);
        ctx.register(SecurityConfig.class);
        servletContext.addListener(new ContextLoaderListener(ctx));
        servletContext.addListener(new HttpSessionEventPublisher());
        //servletContext.addFilter("springExceptionFilter",ExceptionInterceptor.class);
        servletContext.addFilter("springSecurityFilterChain",DelegatingFilterProxy.class);
        servletContext.setSessionTrackingModes(modes);
        AnnotationConfigWebApplicationContext dispatcherContext=new AnnotationConfigWebApplicationContext();
        dispatcherContext.register(ServletContextInitializer.class);

/**
here i have registered the custom handler
*/      
dispatcherContext.register(CustomHandlerExceptionResolver.class);

        Dynamic servlet=servletContext.addServlet("appServlet",new DispatcherServlet(dispatcherContext));
        servlet.addMapping("/");
        servlet.setLoadOnStartup(1);


    }

}

Is it that i need to use any other Handler class provided by spring or change my current configuration ?. I also might have made a silly mistake,so please forgive as i am new to spring framework.

Upvotes: 4

Views: 4737

Answers (1)

Matt
Matt

Reputation: 3662

Registering your class in the Spring context is not enough.

If you're using Spring > 3.1, you should have a confuguration class for your app somewhere. This class should be annotated with @Configuration and extends WebMvcConfigurationSupport (or add @EnableWebMvc) which has all the basic configuration for a Spring MVC webapp.

To register your custom HandlerExceptionResolver, you should overide the configureHandlerExceptionResolvers method in your config class.

@Override
public void configureHandlerExceptionResolvers(
            List<HandlerExceptionResolver> exceptionResolvers) {
        exceptionResolvers.add(new CustomHandlerExceptionResolver());
        addDefaultHandlerExceptionResolvers(exceptionResolvers);
}

Upvotes: 3

Related Questions