5

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?

hawkeye
  • 34,745
  • 30
  • 150
  • 304

2 Answers2

4

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>
fateddy
  • 6,887
  • 3
  • 22
  • 26
2

What you must understand is that in Servlet Specification, Filters and Servlets two clear separate components and Filters are invoked before Servlets.

In your case what you need to do is to have an Interceptor as described in this post

shazin
  • 21,379
  • 3
  • 54
  • 71
  • Great - but can I trigger the interceptor as an annotation on my original class? Otherwise adding xml for an interceptor class, or adding xml for a filter class are about the same overhead. – hawkeye Mar 09 '16 at 04:24