CXF_2

package cn.itcast.cxf;
/**
 * 通过wsdl2java生成客户端代码调用Webservice服务
 *
 */
public class App {

	public static void main(String[] args) {
		/**
		 * <wsdl:service name="IHelloServiceService">
		 */
		IHelloServiceService hss = new IHelloServiceService();
		/**
		 * <wsdl:portType name="IHelloService">
		 */
		IHelloService hs = hss.getIHelloServicePort();
		/**
		 * <wsdl:operation name="sayHello">
		 */
		String ret = hs.sayHello("aa");
		System.out.println(ret);
	}
}

 服务端代码:

1_接口类

package cn.itcast.cxf;

import javax.jws.WebService;
import javax.xml.ws.BindingType;
import javax.xml.ws.soap.SOAPBinding;

@WebService
@BindingType(value=SOAPBinding.SOAP12HTTP_BINDING)
/**
 * 通过@BindingType(value=SOAPBinding.SOAP12HTTP_BINDING)转换为实现SOAP1.2
 */
public interface IHelloService {

	public String sayHello(String name);
}

 2_接口实现类

package cn.itcast.cxf;

import java.text.SimpleDateFormat;
import java.util.Date;

public class HelloServiceImpl implements IHelloService {

	public String sayHello(String name) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		System.out.println("sayHello()... name:" + name);
		return sdf.format(new Date()) + " hello " + name;
	}

}

 3_服务发布类

package cn.itcast.cxf;

import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.JaxWsServerFactoryBean;

/**
 * 
 * 使用JaxWsServerFactoryBean发布CXF的Web服务
 * 必须加入WebService注解,如果不加,虽然不报错,但是所有的方法都暴露不出来
 */

public class Server {

	public static void main(String[] args) {
		JaxWsServerFactoryBean bean = new JaxWsServerFactoryBean();
		bean.setAddress("http://"+IpUtils.localIp()+":7788/hello");
		//提供服务的类的类型或接口类型
		bean.setServiceClass(IHelloService.class);
		bean.setServiceBean(new HelloServiceImpl());
		
		//加入请求的消息拦截器
		bean.getInInterceptors().add(new LoggingInInterceptor());
		//加入请求的消息拦截器
		bean.getOutInterceptors().add(new LoggingOutInterceptor());
		
		bean.create();
		System.out.println("Hello Service ready...");
	}
}

 4_工具类

package cn.itcast.cxf;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class IpUtils {
	@SuppressWarnings("static-access")
	public static String localIp(){
		//服务的地址
		InetAddress address;
		String localIp = "";
		try {
			address = InetAddress.getLocalHost();
			localIp = address.getLocalHost().getHostAddress();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		return localIp;
	}

}

 

你可能感兴趣的:(CXF)