出于业务需求,我需要从jersey迁移到spring-mvc / rest ......
我在spring-mvc中寻找的东西相当于泽西ContainerRequestFilter
,ContainerResponseFilter
。
有什么想法吗?
答案 0 :(得分:4)
我认为您正在寻找的是HandlerInterceptor
。您无法在两级请求/响应风格中找到它,但这两种过滤方法都以preHandle
和postHandle
的形式包含在同一个类中,这相当于请求 - filter
和回复 - filter
。拦截器包装处理程序调用。这是一个例子:
拦截器:
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);
}
}
配置:
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());
}
...
}