I'd like to do @CustomFilter annotation in Spring 3 mvc like this:
@CustomFilter
@RequestMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
// ...
}
(Assuming upgrading to Spring 4 is constrained) What I have to do at the moment with Spring 3 looks like this:
public class CustomFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
....
chain.doFilter(req, res);
}
}
My question is: How to do a @CustomAnnotation annotation that triggers a Filter in Spring 3 MVC?
Creating a Filter. Next, we override the doFilter method, where we can access or manipulate the ServletRequest, ServletResponse, or FilterChain objects. We can allow or block requests with the FilterChain object. Finally, we add the Filter to the Spring context by annotating it with @Component.
The FilterRegistrationBean is, as the name implies, a bean used to provide configuration to register Filter instances. It can be used to provide things like URL mappings etc.
A filter is an object used to intercept the HTTP requests and responses of your application. By using filter, we can perform two operations at two instances − Before sending the request to the controller. Before sending a response to the client.
You could pick up a custom annotation using a HandlerInterceptor
.
Create your marker annotation:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomFilter {
}
Create a HandlerInterceptor
:
public class CustomFilterHandlerInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws
Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
// Test if the controller-method is annotated with @CustomFilter
CustomFilter filter = handlerMethod.getMethod().getAnnotation(CustomFilter.class);
if (filter != null) {
// ... do the filtering
}
}
return true;
}
}
Register the interceptor:
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean class="com.example.CustomFilterHandlerInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With