Webservice拦截器:在webservice请求过程中,动态操作请求和响应的数据

分类

按照所处的位置分:服务器端拦截器  客户端拦截器

按照消息的方向分:入拦截器  出拦截器

按照定义者分:系统拦截器 自定义拦截器 



在服务器端添加拦截器

package com.demo;

//注意引入的类一定要正确

import javax.xml.ws.Endpoint;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.jaxws.EndpointImpl;

public class webServiceApp {
	public static void main(String[] args) {
		System.out.println("Starting web service... ");
		HelloWorldImpl implementor = new HelloWorldImpl();
		String address = "http://localhost:8080/helloWorld";
		Endpoint endpoint = Endpoint.publish(address, implementor);

		// jaxws API 转到 cxf API 添加日志拦截器
		EndpointImpl jaxwsEndpointImpl = (EndpointImpl) endpoint;
		org.apache.cxf.endpoint.Server server = jaxwsEndpointImpl.getServer();
		org.apache.cxf.endpoint.Endpoint cxfEndpoint = server.getEndpoint();

		LoggingInInterceptor logging = new LoggingInInterceptor();
		cxfEndpoint.getInInterceptors().add(logging);
		System.out.println("Web service started");
	}
}


客户端

package com.demo.client;

import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;

import com.demo.HelloWorld;
import com.demo.User;

//参考http://blog.csdn.net/fhd001/article/details/5778915
public class HelloWorldClient {
	public static void main(String[] args) {
		JaxWsProxyFactoryBean svr = new JaxWsProxyFactoryBean();
		svr.setServiceClass(HelloWorld.class);
		svr.setAddress("http://localhost:8080/helloWorld");
		HelloWorld hw = (HelloWorld) svr.create();

		// jaxws API 转到 cxf API 添加日志拦截器
		org.apache.cxf.endpoint.Client client = org.apache.cxf.frontend.ClientProxy
				.getClient(hw);
		org.apache.cxf.endpoint.Endpoint cxfEndpoint = client.getEndpoint();

		LoggingOutInterceptor logging = new LoggingOutInterceptor();
		cxfEndpoint.getOutInterceptors().add(logging);

		User user = new User();
		user.setUsername("Umgsai");
		user.setDescription("test");
		System.out.println(hw.sayHiToUser(user));
		String sayHi = hw.sayHi("test~~~");
		System.out.println(sayHi);
	}
}