4

I am converting a web application to use spring-boot. The application currently uses resteasy which I want to convert to use spring-rest/mvc.

It has been really straight forward so far (mainly replacing annotations). The one place I am having problems has to do with Filters (HTTP Filters).

Currently the application has a Filter that is used in a few of the endpoints. An annotation is used to specify which rest points the filter is applied to. The annotation is based on @NameBinding

Can this be done with Spring (ie create an annotation and for each rest endpoint method that I want the filter applied I would annotate it)?

Hani Naguib
  • 101
  • 2
  • 5

2 Answers2

1

You could define a Filter class that extends OncePerRequestFilter and override shouldNotFilter() method. You would @Autowire RequestMappingHandlerMapping to get an associated handler with the incoming request.

Then you can simply check whether that handler method contains the annotation or not.

@Autowired
private RequestMappingHandlerMapping reqMap;

@Override
protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
    HandlerMethod method = (HandlerMethod) reqMap.getHandler(request).getHandler();
    return !method.getMethod().isAnnotationPresent(SomeAnnotation.class);
}

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) {
     // filtering logic
}
dippas
  • 49,171
  • 15
  • 93
  • 105
0

If you are working with spring-boot, you can use FilterRegistrationBean and map it to specific URLS

How to add a filter class in Spring Boot?

http://www.leveluplunch.com/blog/2014/04/01/spring-boot-configure-servlet-mapping-filters/

Community
  • 1
  • 1
Paul John
  • 1,626
  • 1
  • 11
  • 15
  • 1
    yes, but using an annotation on the method seems a lot cleaner. Is there no way to do it using annotations? – Hani Naguib Mar 01 '15 at 08:23
  • as per this post..http://stackoverflow.com/questions/19825946/how-to-add-a-filter-class-in-spring-boot – Paul John Mar 01 '15 at 08:26
  • Thanks Paul, but the annotation mentioned in the link (@Filter) is used to specify a Filter. What I am looking for is an annotation I would put on rest methods to specify that I want a given Filter to be applied to the specific rest endpoint being annotated. I guess I could create a smart FilterRegistrationBean that inspected annotations and assigned filters accordingly, was just hoping it already existed. – Hani Naguib Mar 02 '15 at 17:51
  • I did a li'l bit of research..I couldn't find anything that did that off the bat. – Paul John Mar 03 '15 at 12:53