How to register a servlet filter in Spring MVC
In a nutshell, a servlet filter lets you intercepts requests and responses on your web application. This article shows you how to register a servlet filter in Spring XML and JavaConfig.
1. Servlet Filter
Review the following custom filter, it will catch any exceptions and redirect to an error page.
package com.mkyong.form.web;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class ErrorHandleFilter implements Filter {
@Override
public void destroy() {
// ...
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
//
}
@Override
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException {
try {
chain.doFilter(request, response);
} catch (Exception ex) {
request.setAttribute("errorMessage", ex);
request.getRequestDispatcher("/WEB-INF/views/jsp/error.jsp")
.forward(request, response);
}
}
}
2. Spring XML
In Spring MVC + XML configuration, you can register the filters via web.xml
web.xml
<filter>
<filter-name>errorHandlerFilter</filter-name>
<filter-class>com.mkyong.form.web.ErrorHandleFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>errorHandlerFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3. Spring JavaConfig
In Spring MVC + JavaConfig + no web.xml
file, you can register the filters via the initializer class.
MyWebInitializer.java
package com.mkyong.form.config.servlet3;
import javax.servlet.Filter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import com.mkyong.form.config.SpringRootConfig;
import com.mkyong.form.config.SpringWebConfig;
import com.mkyong.form.web.ErrorHandleFilter;
public class MyWebInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
//...
@Override
protected Filter[] getServletFilters() {
return new Filter[]{new ErrorHandleFilter()};
}
}
so and what about url-pattern?
For Spring boot add annotation
@Component
public class ErrorHandleFilter implements Filter {
and that is enough for Spring-boot to register filter.
Why in 2nd Point. The filter-name should be in camelCase.
If you define in TitleCase like this ErrorHandlerFilter. Spring throws and error saying no bean name available.
This works by same way in Spring ? (Not MVC)