Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a @CustomAnnotation annotation that triggers a filter in Spring 3 MVC?

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?

like image 343
hawkeye Avatar asked Mar 09 '16 04:03

hawkeye


People also ask

How filter is implemented in Spring 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.

What is the use of FilterRegistrationBean?

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.

What are soring and filters?

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.


1 Answers

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>
like image 106
fateddy Avatar answered Sep 21 '22 06:09

fateddy