美文网首页
CXF自定义Interceptor

CXF自定义Interceptor

作者: mtinsky | 来源:发表于2017-03-27 20:07 被阅读84次

CXF的过滤器可以实现在接口调用前及接口调用后执行一些逻辑处理,适合进行一些统一的接口校验或日志操作。

实现抽象类AbstractPhaseInterceptor

1. 实现构造方法
    public TestInInterceptor(String phase) {
        super(phase);
    }
2. 实现方法handleMessage
    @Override
    public void handleMessage(Message message) throws Fault {
        //message包含请求的参数和path等信息
        String path = (String) message.get(Message.REQUEST_URI);

        System.out.println("hello in interceptor");
        //路径包含calc1的请求不进行拦截
        if(path.indexOf("calc1")!=-1) {
            System.out.println("跳过");
        } else {
            buildRspMessage(message, Response.Status.OK,"提前返回");
        }
    }
3. 方法handleMessage中的参数Message

message内包含很多的属性,包括请求的path、参数等。但是不同的phase(调用阶段),内部包含的值不一样。想要在过滤器内跳过接口直接返回,需要通过message,如以下所示。

4. 跳过调用的接口,直接响应请求
    private void buildRspMessage(Message message, Response.Status status, Object content) {
        Response response = Response
                .status(Response.Status.OK)
                .entity(content)
                .type(MediaType.TEXT_PLAIN)
                .build();
        message.getExchange().put(Response.class,response);
    }

添加Interceptor,发布及启动REST接口

JAXRSServerFactoryBean factory = new JAXRSServerFactoryBean();
//配置两个自定义的服务TestService1和TestService2
factory.setResourceClasses(TestService1.class, TestService2.class);
//设置TestService1为单例
factory.setResourceProvider(TestService1.class,
        new SingletonResourceProvider(new TestService1()));
factory.setResourceProvider(new SingletonResourceProvider(new TestService1()));
//设置访问地址,必须为本机可用的ip或者host name(如localhost)
factory.setAddress("http://localhost:9999/");
//增加过滤器
factory.getInInterceptors().add(new TestInInterceptor(Phase.RECEIVE));
//增加过滤器
factory.getOutInterceptors().add(new TestOutInterceptor(Phase.MARSHAL));
//创建服务
factory.create();

Interceptor除了上面所示通过编码进行添加,也可以通过配置文件配置,在此不列出。

查看效果

启动服务后,浏览器内输入
http://localhost:9999/calc1/add/1/2
http://localhost:9999/calc2/add/1/2

代码示例下载

cxf interceptor示例

参考文档

http://cxf.apache.org/docs/interceptors.html

相关文章

网友评论

      本文标题:CXF自定义Interceptor

      本文链接:https://www.haomeiwen.com/subject/aupgnttx.html