views:

121

answers:

1

I am using the Spring MVC for a project, and I am using the Spring DispatcherServlet to map the request's coming into the application to the controllers written elsewhere. I am looking for a way to have a default handler ( a catch all handler) if the request doesn't map to any of the exisiting controller-view maps. This currently shows a Resource not found exception, but I want to know if a catch all unmatched requests function is available in the Spring.

+1  A: 

Every HandlerMapping strategy in Spring MVC has a defaultHandler property for just this purpose.

This is easy if your Spring config is already specifying a HandlerMapping object explicitly (e.g. a SimpleUrlHandlerMapping), but it's less obvious if you're relying on the defaults to supply a HandlerMapping for you.

For example, if you're using annotated controllers, then you're probably relaying on the default declaration of DefaultAnnotationHandlerMapping which Spring supplies automatically. However, you can provide your own bean to override the default:

<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
   <property name="defaultHandler" ref="myDefaultHandler"/>
</bean>

This same pattern will work with any Handlermapping type, just substitute the class name.

skaffman