1、CXF框架的深入使用,CXF的拦截器,为什么设计CXF拦截器?
答:为了在webservice请求过程中,能动态操作请求和响应数据,,CXF设计了拦截器。
2、CXF的拦截器分类:
1)、按所处的位置分:服务器端拦截器,客户端拦截器。
2)、按消息的方向分:入拦截器,出拦截器。
3)、按定义者分:系统拦截器,自定义拦截器。
![](https://i-blog.csdnimg.cn/blog_migrate/36d52227e8af8f4080978ff3c8001a7c.png)
3、使用拦截器就可以不适用tcp/ip监控的工具了,因为此监控工具还需要将wsdl文件下载到本地,然后修改端口才能进行监控。
将apache-cxf-2.5.9\lib里面的包导入到项目中,然后编写SEI(Service Endpoint Interface),SEI在webservice中称为portType,在java中就是普通接口。
1 package com.bie.webservice.sei;
2
3 import javax.jws.WebMethod;
4 import javax.jws.WebService;
5
6 /**
7 *
8 * @author
9 * 编写SEI(Service Endpoint Interface),SEI在webservice中称为portType,在java中就是普通接口 。
10 *
11 * 1、第一步,开发服务器端,Web Service编码。
12 * –@WebService(SEI和SEI的实现类),该注解用来定义SEI和SEI的实现类。
13 * –@WebMethod(SEI中的所有方法),该注解用来定义SEI里面的方法。
14 * 2、第二步,发布Web Service,–Endpoint(终端, 发布webservice)。
15 */
16 @WebService
17 public interface HelloWebServiceSEI {
18
19 @WebMethod
20 public String sayHello(String name);
21
22 }
然后编写SEI实现类,如下所示:
1 package com.bie.webservice.sei.impl;
2
3 import javax.jws.WebService;
4
5 import com.bie.webservice.sei.HelloWebServiceSEI;
6
7 /**
8 *
9 * @author
10 *
11 * 1、SEI实现类
12 *
13 *
14 */
15 @WebService // SEI实现类也要使用此注解
16 public class HelloWebServiceSEIImpl implements HelloWebServiceSEI {
17
18 @Override
19 public String sayHello(String name) {
20 System.out.println("Service server sayHello() : " + name);
21 return "hello " + name;
22 }
23
24 }
发布WebService,Endpoint(终端, 发布webservice),可以在服务器端编写拦截器,此拦截器可以替换掉tcp/ip监控工具。
1 package com.bie.webservice.endpoint;
2
3 import java.util.List;
4
5 import javax.xml.ws.Endpoint;
6
7 import org.apache.cxf.interceptor.Interceptor;
8 import org.apache.cxf.interceptor.LoggingInInterceptor;
9 import org.apache.cxf.interceptor.LoggingOutInterceptor;
10 import org.apache.cxf.jaxws22.EndpointImpl;
11 import org.apache.cxf.message.Message;
12
13 import com.bie.webservice.sei.HelloWebServiceSEI;
14 import com.bie.webservice.sei.impl.HelloWebServiceSEIImpl;
15
16 /**
17 *
18 * @author 1、发布WebService,Endpoint(终端, 发布webservice)。
19 *
20 */
21 public class WebServiceEndpoint {
22
23 public static void main(String[] args) {
24 // 使用Endpoint发布webservice
25 // 参数一,url地址
26 String address = "http://localhost:8888/webservice/hello";
27 // 参数二,是SEI实现类对象
28 HelloWebServiceSEI implementor = new HelloWebServiceSEIImpl();
29 // 终端
30 Endpoint endpoint = Endpoint.publish(address, implementor);
31 System.out.println(endpoint.toString());
32
33 // 将Endpoint转换为EndpointImpl,使用更多的实现方法
34 EndpointImpl endpointImpl = (EndpointImpl) endpoint;
35 // 如果要添加拦截器,是使用终端Endpoint来添加拦截器的,这里使用EndpointImpl来添加拦截器
36 // 添加服务器端的入拦截器
37 List<Interceptor<? extends Message>> inInterceptors = endpointImpl.getInInterceptors();
38 // 向拦截器集合中添加拦截器&