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 config to handle custom error pages. The bean class is registered internally WebInitializer
which is equivalent web.xml
. The problem is that I am unable to view the custom error pages I developed when the "404" exception occurred, or any of the ones that I 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);
}
}
Do I need to use any Handler class provided by spring or change my current configuration? I also may have made a stupid mistake, so please forgive as I am new to spring framework.
source to share
It's not enough to register your class in the Spring context.
If you are using Spring> 3.1 you must have a confuguration class for your application. This class should be annotated with @Configuration
and extended WebMvcConfigurationSupport
(or added @EnableWebMvc
), which has all the basic configuration for Spring MVC webapp.
To register your custom one HandlerExceptionResolver
, you must override the method configureHandlerExceptionResolvers
in your config class.
@Override
public void configureHandlerExceptionResolvers(
List<HandlerExceptionResolver> exceptionResolvers) {
exceptionResolvers.add(new CustomHandlerExceptionResolver());
addDefaultHandlerExceptionResolvers(exceptionResolvers);
}
source to share