Java 如何在Spring3MVC中创建一个触发过滤器的@CustomAnnotation注释?
我想在Spring 3 mvc中做@CustomFilter注释,如下所示:Java 如何在Spring3MVC中创建一个触发过滤器的@CustomAnnotation注释?,java,spring,spring-mvc,spring-annotations,Java,Spring,Spring Mvc,Spring Annotations,我想在Spring 3 mvc中做@CustomFilter注释,如下所示: @CustomFilter @RequestMapping("/{id}") public Account retrieve(@PathVariable Long id) { // ... } public class CustomFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse re
@CustomFilter
@RequestMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
// ...
}
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);
}
}
(假设升级到Spring 4受到限制)目前我必须对Spring 3执行的操作如下:
@CustomFilter
@RequestMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
// ...
}
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);
}
}
我的问题是:如何在Spring3MVC中触发过滤器的@CustomAnnotation注释?您必须理解的是,在Servlet规范中,过滤器和Servlet在Servlet之前调用两个明确的独立组件和过滤器
在您的情况下,您需要做的是拥有一个拦截器,如本文所述,您可以使用 创建标记注释:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomFilter {
}
创建一个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;
}
}
注册拦截器:
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean class="com.example.CustomFilterHandlerInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
Great-但是我可以在原始类上触发拦截器作为注释吗?否则,为拦截器类添加xml或为过滤器类添加xml的开销大致相同。