查了很多都是实现HandlerInterceptor,可以不用这个吗
自己写注解,在controller层和Interceptor的class里引用这个注解
想采用下面这种实现方法
首先自定义注解
解决方案:
原因:因为我们使用的框架是spring框架混用resteasy,所以好多有些网上的拦截器使用不了
解决办法:
1.自定义注解
@NameBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface DoublyPrevent{}
2.拦截器,可以实现ContainerRequestFilter,也可以实现ReaderInterceptor,下面用ReaderInterceptor举例
@Provider
@DoublyPrevent
@Component
@Transactional
public class domeInterceptor implements ReaderInterceptor, WriterInterceptor{
@Context
public HttpServletRequest request;
@Context
public HttpServletResponse response;
@Override
public Object aroundReadFrom(ReaderInterceptorContext context) throws IOException, WebApplicationException{
return context.proceed();
}
@Override
public Object aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException{
context.proceed();
}
}
3.controller层使用
在controller的方法上使用自定义的注解@DoublyPrevent
interceptor就是个拦截器,就是让你可以再请求发送过来先做一些处理,如果你能用别的方法达到目的,不用拦截器当然也可以啊,得看你的目的是什么,自定义注解如果能达到目的当然也是可以的,但是你再controller层才引用这个注解的话,那你为什么不直接再controller里面处理不久完了,干嘛还要拦截器,还要自定义注解呢
我们一般理解拦截器是拦截请求,那要么就是HandlerIntecepter,要么就是Filter。从你的描述来看,你只是希望实现类似AOP的功能,那跟这个就没啥关系了
建议你看下这篇博客Spring 拦截器(Interceptor )的使用