Apache CXF实现WebService开发(一)

Apache CXF简介
        Apache CXF 是一个开源的 Services 框架,CXF 帮助您利用 Frontend 编程 API 来构建和开发 Services ,像 JAX-WS 。这些 Services 可以支持多种协议,比如:SOAP、XML/HTTP、RESTful HTTP 或者 CORBA ,并且可以在多种传输协议上运行,比如:HTTP、JMS 或者 JBI,CXF 大大简化了 Services 的创建,同时它继承了 XFire 传统,一样可以天然地和 Spring 进行无缝集成。

       Apache CXF 是一个开放源代码框架,提供了用于方便地构建和开发 Web 服务的可靠基础架构。它允许创建高性能和可扩展的服务,您可以将这样的服务部署在 Tomcat 和基于 Spring 的轻量级容器中,以及部署在更高级的服务器上,例如 Jboss、IBM? WebSphere? 或 BEA WebLogic。

【转载使用,请注明出处:http://blog.csdn.net/mahoking

基本环境搭建
        下载最新的CXF需要的jar文件,http://cxf.apache.org/download.html或者http://download.csdn.net/detail/ma_hoking/8210349。在这里我们不进行区分,将所有Apache CXF\apache-cxf-3.0.2\lib下的jar文件(不包含子目录下的文件)复制到项目下。在此我们新建一个Java Project项目CXFWebService,将前面所述的jar文件导入项目中。


创建自定义对象
注解:
@XmlRootElement-指定XML根元素名称(可选) 
@XmlAccessorType-控制属性或方法序列化 , 四种方案: 

  • FIELD-对每个非静态,非瞬变属性JAXB工具自动绑定成XML,除非注明XmlTransient 
  • NONE-不做任何处理 
  • PROPERTY-对具有set/get方法的属性进行绑定,除非注明XmlTransient 
  • PUBLIC_MEMBER -对有set/get方法的属性或具有共公访问权限的属性进行绑定,除非注 明XmlTransient 

@XmlType-映射一个类或一个枚举类型成一个XML Schema类型

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 * 定义对象演示
 * @author mahc
 *
 */
@XmlRootElement(name="User")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder={"name","loginName","age"})
public class User {

	//请使用基本属性类型
	private String name;
	private String loginName;
	private int age;

	/**
	 * ※ 需要※       无参数默认构造器
	 */
	public User() {
		super();
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getLoginName() {
		return loginName;
	}

	public void setLoginName(String loginName) {
		this.loginName = loginName;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public User(String name, String loginName, Integer age) {
		this.name = name;
		this.loginName = loginName;
		this.age = age;
	}

	@Override
	public String toString() {
		return "User [name=" + name + ", loginName=" + loginName + ", age="
				+ age + "]";
	}
	
}

构建WebService的接口类

import java.util.List;

import javax.jws.WebParam;
import javax.jws.WebService;

import com.mahaochen.cxf.User;

/**
 * ※@WebService:申明为webservice的注解 
 *  endpointInterface:要暴露的接口类
 *  serviceName:服务名
 * @author mahc
 *
 */
@WebService(endpointInterface = "com.mahaochen.cxf.ws.IUserService", serviceName = "UserService")
public interface IUserService {

	/**
	 * ※@WebParam(name = "name"):自定义请求参数的名称
	 * @param name
	 * @param loginName
	 * @param age
	 * @return
	 */
	public User registerUser(
			@WebParam(name = "name") String name,
			@WebParam(name = "loginName") String loginName,
			@WebParam(name = "age") int age);
	
	public List<User> getRegistedUsers();

}
注意事项:
如果
@WebService(endpointInterface = "com.mahaochen.cxf.ws.IUserService", serviceName = "UserService")
填写错误会报错:Could not load Webservice SEI。


构建WebService的实现类

import java.util.ArrayList;
import java.util.List;

import com.mahaochen.cxf.User;

public class UserService implements IUserService{

	private static List<User> userList = new ArrayList<User>();
	
	@Override
	public User registerUser(String name, String loginName, int age) {
		
		User user = new User(name, loginName, age);
		userList.add(user);
		return user;
	}

	@Override
	public List<User> getRegistedUsers() {

		for(int i=0;i<2;i++){
			User tempUser = new User("name"+i, "loginName"+i, 18+i);
			userList.add(tempUser);
		}
		return userList;
	}

}

发布WebService服务

/**
 * 发布WebServie服务测试类
 * @author mahc
 *
 */
public class TestCXFWebService {

	public static void main(String[] args) {
		System.out.println("CXFWebService is starting!");
		IUserService userService = new UserService();
		String address = "http://localhost:8090/CXFWebService";
//		String testAddress = "http://localhost:8090/CXFWebService?wsdl";
		Endpoint.publish(address, userService);
		System.out.println("CXFWebService is started!");
	}
}

测试WebService
通过IE浏览器,访问http://localhost:8090/CXFWebService?wsdl

 

<?xml version='1.0' encoding='UTF-8'?><wsdl:definitions xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:tns="http://ws.cxf.mahaochen.com/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:ns1="http://schemas.xmlsoap.org/soap/http" name="UserServiceService" targetNamespace="http://ws.cxf.mahaochen.com/">
  <wsdl:types>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://ws.cxf.mahaochen.com/" elementFormDefault="unqualified" targetNamespace="http://ws.cxf.mahaochen.com/" version="1.0">
  <xs:element name="User" type="tns:user"/>
  <xs:element name="getRegistedUsers" type="tns:getRegistedUsers"/>
  <xs:element name="getRegistedUsersResponse" type="tns:getRegistedUsersResponse"/>
  <xs:element name="registerUser" type="tns:registerUser"/>
  <xs:element name="registerUserResponse" type="tns:registerUserResponse"/>

  <xs:complexType name="registerUser">
    <xs:sequence>
      <xs:element minOccurs="0" name="name" type="xs:string"/>
      <xs:element minOccurs="0" name="loginName" type="xs:string"/>
      <xs:element name="age" type="xs:int"/>
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="registerUserResponse">
    <xs:sequence>
      <xs:element minOccurs="0" name="return" type="tns:user"/>
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="user">
    <xs:sequence>
      <xs:element minOccurs="0" name="name" type="xs:string"/>
      <xs:element minOccurs="0" name="loginName" type="xs:string"/>
      <xs:element name="age" type="xs:int"/>
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="getRegistedUsers">
    <xs:sequence/>
  </xs:complexType>

  <xs:complexType name="getRegistedUsersResponse">
    <xs:sequence>
      <xs:element maxOccurs="unbounded" minOccurs="0" name="return" type="tns:user"/>
    </xs:sequence>
  </xs:complexType>

</xs:schema>
  </wsdl:types>
  <wsdl:message name="registerUserResponse">
    <wsdl:part element="tns:registerUserResponse" name="parameters">
    </wsdl:part>
  </wsdl:message>
  <wsdl:message name="getRegistedUsers">
    <wsdl:part element="tns:getRegistedUsers" name="parameters">
    </wsdl:part>
  </wsdl:message>
  <wsdl:message name="registerUser">
    <wsdl:part element="tns:registerUser" name="parameters">
    </wsdl:part>
  </wsdl:message>
  <wsdl:message name="getRegistedUsersResponse">
    <wsdl:part element="tns:getRegistedUsersResponse" name="parameters">
    </wsdl:part>
  </wsdl:message>
  <wsdl:portType name="IUserService">
    <wsdl:operation name="registerUser">
      <wsdl:input message="tns:registerUser" name="registerUser">
    </wsdl:input>
      <wsdl:output message="tns:registerUserResponse" name="registerUserResponse">
    </wsdl:output>
    </wsdl:operation>
    <wsdl:operation name="getRegistedUsers">
      <wsdl:input message="tns:getRegistedUsers" name="getRegistedUsers">
    </wsdl:input>
      <wsdl:output message="tns:getRegistedUsersResponse" name="getRegistedUsersResponse">
    </wsdl:output>
    </wsdl:operation>
  </wsdl:portType>
  <wsdl:binding name="UserServiceServiceSoapBinding" type="tns:IUserService">
    <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
    <wsdl:operation name="registerUser">
      <soap:operation soapAction="" style="document"/>
      <wsdl:input name="registerUser">
        <soap:body use="literal"/>
      </wsdl:input>
      <wsdl:output name="registerUserResponse">
        <soap:body use="literal"/>
      </wsdl:output>
    </wsdl:operation>
    <wsdl:operation name="getRegistedUsers">
      <soap:operation soapAction="" style="document"/>
      <wsdl:input name="getRegistedUsers">
        <soap:body use="literal"/>
      </wsdl:input>
      <wsdl:output name="getRegistedUsersResponse">
        <soap:body use="literal"/>
      </wsdl:output>
    </wsdl:operation>
  </wsdl:binding>
  <wsdl:service name="UserServiceService">
    <wsdl:port binding="tns:UserServiceServiceSoapBinding" name="UserServicePort">
      <soap:address location="http://localhost:8090/CXFWebService"/>
    </wsdl:port>
  </wsdl:service>
</wsdl:definitions>

测试WebService访问的Client类

import java.util.List;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import com.mahaochen.cxf.User;

public class Client {

	public static void main(String[] args) {
		
		 JaxWsProxyFactoryBean factoryBean = new JaxWsProxyFactoryBean();  
	     factoryBean.setServiceClass(IUserService.class);  
	     factoryBean.setAddress("http://localhost:8090/CXFWebService");  
	     IUserService userService  = (IUserService) factoryBean.create();  
	     User user = userService.registerUser("name", "loginName", 28);
	     user.toString();
	     List<User> users = userService.getRegistedUsers();
	     System.out.println(user.toString());
	}
}


            以上是单独部署的方式之一,然而很多情况下,我们并不希望我们的WebService和我们的应用分开成两个服务器,而希望他们在同一个容器,Tomcat或JBOSS或其他的,这样我们就必须通过WEB来部署我们前面完成的webservice。这部分将在下篇博文中介绍,敬请期待!

 

【转载使用,请注明出处:http://blog.csdn.net/mahoking


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。