Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Migrating from jersey to spring-mvc/rest: ContainerRequestFilter, ContainerResponseFilter

I need to migrate from jersey to spring-mvc/rest in cause of business requirements ...

I am searching in spring-mvc for something that is equivalent to jersey's ContainerRequestFilter, ContainerResponseFilter.

Any ideas?

like image 839
t777 Avatar asked Feb 21 '15 00:02

t777


1 Answers

I think what you're looking for is the HandlerInterceptor. You won't find it in the two-class request/response flavor, but both filter methods are included in the same class, in the form of preHandle and postHandle, which is the equivalent of request-filter and response-filter, respectively. The interceptor wraps the handler call. Here's an example:

Interceptor:

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class LogginHandlerInterceptor implements HandlerInterceptor{
    @Override
    public boolean preHandle(HttpServletRequest hsr, 
                             HttpServletResponse hsr1, Object handler) throws Exception {
        System.out.println("preHandle - " + handler);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest hsr, HttpServletResponse hsr1, 
                           Object handler, ModelAndView mav) throws Exception {
        System.out.println("postHandle - " + handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest hsr, HttpServletResponse hsr1, 
                                Object handler, Exception excptn) throws Exception {
        System.out.println("afterCompletion - " + handler);
    }
}

Config:

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"..."})
public class WebAppConfiguration extends WebMvcConfigurerAdapter {
    ...
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LogginHandlerInterceptor());
    }
    ...
}

See also:

  • Intercepting Requests with HandlerInterceptor
  • MVC Config Interceptors
like image 149
Paul Samsotha Avatar answered Oct 08 '22 21:10

Paul Samsotha