CXF WebService以及RestFulWebService搭建整理

1.CXF簡單介紹:
開源的webservice框架,
  支持SOAP1.1/1.2REST
  支持XMLJSON
CXF是apache旗下的開源框架,由Celtix + XFire這兩門經典的框架合成,是一套非常流行的web service框架。
它提供了JAX-WS的全面支持,並且可以根據實際項目的需要,採用代碼優先(Code First)或者 WSDL 優先(WSDL First)來輕鬆地實現 Web Services 的發佈和使用,同時它能與spring進行完美結合

2.cxf-webService
A.導入依賴pom.xml 配置
<properties> <cxf.version>2.2.7</cxf.version> </properties>
<dependencies>
<dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxws</artifactId> <version>${cxf.version}</version> </dependency>
<dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-http</artifactId> <version>${cxf.version}</version> </dependency>
<dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-http-jetty</artifactId> <version>${cxf.version}</version> </dependency>
<dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-ws-security</artifactId> <version>${cxf.version}</version> </dependency>
<dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-ws-policy</artifactId> <version>${cxf.version}</version> </dependency>
<dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-bundle-jaxrs</artifactId> <version>${cxf.version}</version> </dependency> <dependency> <groupId>javax.ws.rs</groupId> <artifactId>jsr311-api</artifactId> <version>1.1.1</version> </dependency>
<dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.5.8</version> </dependency>
<dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-jdk14</artifactId> <version>1.5.8</version>
</dependency> <dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.0</version> </dependency>
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.3</version> </dependency>
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.1</version> <scope>test</scope> </dependency>
</dependencies>

B.WEB-INF目錄下,web.xml配置
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
  4.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
  5.     id="WebApp_ID" version="2.5">  
  6.   
  7.     <!--spring需要加載的配置文件-->  
  8.     <context-param>  
  9.         <param-name>contextConfigLocation</param-name>  
  10.         <param-value>  
  11.             classpath:applicationContext-server.xml  
  12.         </param-value>  
  13.     </context-param>  
  14.     <listener>  
  15.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  16.     </listener>  
  17.     <!-- 
  18.         cxf服務啓動servlet 
  19.     -->  
  20.     <servlet>  
  21.         <servlet-name>CXFServlet</servlet-name>  
  22.         <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>  
  23.         <load-on-startup>1</load-on-startup>  
  24.     </servlet>  
  25.     <servlet-mapping>  
  26.         <servlet-name>CXFServlet</servlet-name>  
  27.         <url-pattern>/services/*</url-pattern>  
  28.     </servlet-mapping>  
  29.     <welcome-file-list>  
  30.         <welcome-file>index.jsp</welcome-file>  
  31.     </welcome-file-list>  
  32. </web-app>  

C.spring集成CXF配置
<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
                     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd     
                        http://www.springframework.org/schema/context     
            http://www.springframework.org/schema/context/spring-context-3.0.xsd  
     http://cxf.apache.org/jaxws       
      http://cxf.apache.org/schemas/jaxws.xsd">  
    <import resource="classpath:META-INF/cxf/cxf.xml" />  
    <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />  
    <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />  
</beans> 


D.編寫接口,將其聲明爲webservice服務類
因爲SOAPBinding.Style不同,在生成webwervice時的一些差異。
SOAPBinding.Style:PRCDOCUMENTJDK6 中默認的是DOCUMENT JDK1.7使用PRC
接口上添加@WebService 註解將此類聲明爲服務類,
@WebParam(name=名稱)傳入參數 定義服務類參數名稱
import javax.jws.WebParam;  
import javax.jws.WebService;  
import javax.jws.soap.SOAPBinding;  
import javax.jws.soap.SOAPBinding.Style;  
  
  
@WebService  
@SOAPBinding(style = Style.RPC)  
public interface IUserService {  
  
    public String getUserByName(@WebParam(name = "username") String username);  
    public void setUser(String username);  


編寫接口實現類
public class UserService implements IUserService {  
  
    public String getUserByName(String username) {  
        return "Hello:"+username;  
    }  
  
    public void setUser(String username) {  
        System.out.println(username);  
    }  
  
}  


E.配置spring映射文件
jaxws配置中serviceClass 表示配置好的服務類(接口上有webservice註解的類)
address表示訪問路徑能
serviceBean表示接口的實現類
<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
                     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd     
                        http://www.springframework.org/schema/context     
            http://www.springframework.org/schema/context/spring-context-3.0.xsd  
     http://cxf.apache.org/jaxws       
      http://cxf.apache.org/schemas/jaxws.xsd">  
    <import resource="classpath:META-INF/cxf/cxf.xml" />  
    <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />  
    <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />  
  
    <bean id="userServiceBean" class="com.UserService" />  
      
    <jaxws:server id="userService" serviceClass="com.IUserService"  
        address="/userService">  
        <jaxws:serviceBean>  
            <ref bean="userServiceBean" />  
        </jaxws:serviceBean>  
    </jaxws:server>  
</beans> 

F.啓動服務器進行發佈部署,在瀏覽器中輸入http://localhost:8080/SpringCXF/services/userService?wsdl 看頁面是否會出現xml文檔,來判斷服務是否配置成功

G:客戶端配置
server.client 的配置
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans >
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.xsd"
<importresource="classpath:META-INF/cxf/cxf.xml"/>
<importresource="classpath:META-INF/cxf/cxf-extension-soap.xml"/>
<importresource="classpath:META-INF/cxf/cxf-servlet.xml"/>
<jaxws:clientid="userWsClient"serviceClass="com.hoo.service.IComplexUserService"
address="http://localhost:8080//SpringCXF/services/userService"/>
</beans>


2.RESTful Webservice
RESTful風格的WebService主張重用HTTP協議,面向資源編程(ROA)。扼要的說,RESTful風格WebService中,每一個URL即表示一個資源.
RESTful 簡化了 web service 的設計,它不再需要 wsdl ,也不再需要 soap 協議,而是通過最簡單的 http 協議傳輸數據 ( 包括 xml 或 json) 。既簡化了設計,也減少了網絡傳輸量(因爲只傳輸代表數據的 xml 或 json ,沒有額外的 xml 包裝)

A.pom.xml配置,引入依賴的jar包
<dependencies>
<dependency> <groupId>javax.ws.rs</groupId> <artifactId>jsr311-api</artifactId> <version>1.1.1</version> </dependency>
<dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxrs</artifactId> <version>2.4.4</version> </dependency>
</dependencies>
web.xml配置
<servlet>  
        <description>Apache CXF Endpoint</description>  
        <display-name>cxf</display-name>  
        <servlet-name>cxf</servlet-name>  
        <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>  
        <load-on-startup>1</load-on-startup>  
    </servlet>  
    <servlet-mapping>  
        <servlet-name>cxf</servlet-name>  
        <url-pattern>/services/*</url-pattern>  
    </servlet-mapping> 

B.restful webService 註解講解
標籤 用法和解釋
@GET,@POST,@PUT,@DELETE 該組標籤將一個標註方法的 HTTP 請求類型
@PATH 該標籤可用於類或者方法,表示定位此 RESTful 資源的路徑。
@Produces 該標籤標註資源類或方法返回的 MIME 類型 , 也就是資源方法產生並且返回給客戶端的響應消息的類型。例如 application/xml.
@Consumes 該標籤標註資源類或方法可以接受的請求消息的類型,也就是客戶端發送的請求中可以包含的 Http Entity 的類型。
@PathParam,@QueryParam,@HeaderParam,@CookieParam 該組分別標註方法的參數來自於 HTTP 請求的不同位置,例如,@PathParam 來自於 URL 的路徑,@QueryParam 來自於 URL 的查詢參數,@HeaderParam 來自於 HTTP 請求的頭信息,@CookieParam 來自於 HTTP 請求的 Cookie。
@Context 該標籤標註資源請求或者響應的上下文實例,例如我們可以再資源方法參數中注入 HttpServletRequest (@Context HttpServletRequest httpRequest) 來獲取 Http 請求的相關信息
Demo:
@GET @PATH(value=”/staff/query/{id}”) @Produces(“application/xml”) Staff getStaffById(@PathParam("id") int id)

C.restful webservice註解釋義
@XmlAccessorType(XmlAccessType.PROPERTY) @XmlRootElement(name = "User") @XmlType(propOrder = { "userId", "nickname", "gender","registerDate"})
publicclassUser implementsSerializable {
privatestaticfinallong
serialVersionUID= 1L;
private
String userId;
privateString nickname;
private
String gender;
private
Date registerDate;
public
User(String userId, String nickname, String gender, Date registerDate)
{ this.userId = userId; this.nickname = nickname; this.gender = gender;this.registerDate = registerDate; }
publicString getUserId()
 { returnuserId; }
publicvoidsetUserId(String userId)
 { this.userId = userId; }
publicString getNickname()
 { returnnickname; }
publicvoid
setNickname(String nickname)
{ this.nickname = nickname; }
 publicString getGender()
{ returngender; }
 publicvoidsetGender(String gender)
 { this.gender = gender; }
@XmlJavaTypeAdapter(DateConverter.
class)
 
publicDate getRegisterDate() { returnregisterDate; }
 publicvoidsetRegisterDate(Date registerDate)
 { this.registerDate = registerDate; }
@Override publicString toString()
{ return"User [userId=" + userId + ", nickname=" + nickname + ", gender=" + gender + ", registerDate =" + registerDate + "]"; } }

爲了用 XML 映射多個用戶,我們定義了 Users 類,Users 類只有一個成員變量,它是一個裝有 User 對象的 java.util.List 列表。
@XmlRootElement(name = "Users")
publicclass
Users
 { @XmlElement(name = "User")
privateList<User> users;
publicList<User> getUsers()
 { returnusers; }
 publicvoidsetUsers(List<User> users)
 { this.users = users; } }
對於註冊日期 registerDate 變量的映射,需要做一些必要的處理,我們希望日期被映射爲 yyyy-mm-dd 的形 式,上述 User 類中, 我們用 @XmlJavaTypeAdapter 標籤 註釋 registerDate 的 getter 方法, 希望 告知 JAXB 遇到這個屬性的時候, 用 DateConverter 類做處理

@Produces({ MediaType.APPLICATION_XML})
 @Consumes({ MediaType.
APPLICATION_XML})
publicinterface
UserService
 {
@GET @Produces(MediaType.APPLICATION_XML) @Path("/searchuser/{userId}")
User searchUser(
@PathParam("userId") String userId);
 
@POST @Consumes(MediaType.APPLICATION_XML) @Path("/adduser")
Response addUser(User user);
@DELETE @Consumes(MediaType.
APPLICATION_XML) @Path("/deleteuser/{userId}")
Response deleteUser(
@PathParam("userId") String userId);
 
@PUT @Path("/category") @Consumes(MediaType.APPLICATION_XML)
Response updateUser(User user);
@GET @Path("/getusers/startdate/{startDate}/enddate/{endDate}") @Produces({ MediaType.APPLICATION_XML})
Users getUsers(
@PathParam("startDate") String startDate ,@PathParam("endDate") String endDate); }



publicclassUserServiceImplimplementsUserService
{
publicUser searchUser(String userId)
{ User user = UserDAO.
searchUser(userId);if(user ==null)
 {
ResponseBuilder builder = Response.status(Status.NOT_FOUND);builder.type("application/xml"); builder.entity("<errorMsg>User with id:" + userId + " can not be found!</errorMsg>");thrownewWebApplicationException(builder.build()); }else{ System.out.println("User with id:" + userId + " is found"); returnuser; } }

 
publicResponse addUser(User user) { User userObj = (User) UserDAO.searchUser(user.getUserId());
 
if(userObj !=null)
 {
ResponseBuilder builder = Response.status(Status.FORBIDDEN); builder.type("application/xml"); builder.entity("<errorMsg>User with id:" + user.getUserId() + " already exists</errorMsg>");thrownewWebApplicationException(builder.build()); }else{ UserDAO.addUser(user);returnResponse.ok(user).build();} }

publicResponse deleteUser(String userId) { User userObj = (User) UserDAO.searchUser(userId);
if(userObj ==null)
 {
ResponseBuilder builder = Response.status(Status.FORBIDDEN); builder.type("application/xml"); builder.entity("<errorMsg>User with id:" + userId + " is not existed, delettion request is rejected</errorMsg>");thrownewWebApplicationException(builder.build()); }else{ UserDAO.deleteUser(userId);returnResponse.ok().build();} }

publicResponse updateUser(User user) { User userObj = (User) UserDAO.searchUser(user.getUserId());
if
(userObj == null)
{
ResponseBuilder builder = Response.status(Status.FORBIDDEN); builder.type("application/xml"); builder.entity("<errorMsg>User with id:" + user.getUserId() + " is not existed, update request is rejected</errorMsg>");thrownewWebApplicationException(builder.build()); }else{ UserDAO.updateUser(user);returnResponse.ok(user).build(); } }
publicUsers getUsers(String startDate, String endDate) { List<User> userList =newArrayList<User>();
ResponseBuilder builder = Response.status(Status.OK); builder.type("application/xml");
try
{ userList = UserDAO.getUsersByRegDate(startDate, endDate); }catch(Exception e) { e.printStackTrace();builder = Response.status(Status.NOT_ACCEPTABLE); builder.entity("<errorMsg>" + "not accpertable date format for startDate or endDate</errorMsg>");thrownewWebApplicationException(builder.build());} if(userList.size() < 1) {builder = Response.status(Status.NOT_FOUND); builder.entity("<errorMsg>no user found registered between" +startDate+ " and " + endDate + "</errorMsg>");thrownewWebApplicationException(builder.build()); }else{ Users users =newUsers(); users.setUsers(userList);returnusers; } }


D.spring集成restful webService
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi=
"http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs=
"http://cxf.apache.org/jaxrs"
xsi:schemaLocation=
"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd http://camel.apache.org/schema/osgi http://camel.apache.org/schema/osgi/camel-osgi.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd http://camel.apache.org/schema/cxfhttp://camel.apache.org/schema/cxf/camel-cxf.xsd">
<import resource=
"classpath:META-INF/cxf/cxf.xml"/>
<jaxrs:server id=
"userRestService"address="/userservices/v1.0">
<jaxrs:serviceBeans>
<ref bean=
"userServiceImpl"/>
</jaxrs:serviceBeans>
</jaxrs:server>
 
<bean id="userServiceImpl"class="com.netprovider.user.service.baseinfo.impl.UserServiceImpl"> </bean> </beans>

E. 客戶端調用
1.添加:post請求
private static void testAddUser()
 {
WebClient client = WebClient.create(SERVICE_URL);
client.path("/adduser").accept(MIME_TYPE).type(MIME_TYPE);
User user = new User(); user.setUserId("00" + new Random().nextInt(10000)); user.setGender("Male"); user.setNickname("Who am I"); user.setRegisterDate(new Date()); User addedUser = client.post(user, User.class);System.out.println("added user id:" + addedUser.getUserId()); assertResult(user.getUserId(),addedUser.getUserId()); //set TEST_USER_ID to the one added, so that the user //which is added for testing can be deleted later TEST_USER_ID = addedUser.getUserId(); System.out.println("Test addUser method successfully");}

2.查詢:get請求
private static void testGetUsers() {
WebClient client = WebClient.create(SERVICE_URL); //according to the tested data we insert,during this time period //only one person registered
Users users = client.path("/getusers/startdate/2012-10-17/ enddate/2012-10-19") .accept(MIME_TYPE).type(MIME_TYPE).get(Users.class);
assertResult("1", String.valueOf(users.getUsers().size())); System.out.println("Test getUsers method successfully");}


3.修改:put請求
private static void testUpdateUser() {
WebClient client = WebClient.create(SERVICE_URL);
User user = new User(); user.setUserId(TEST_USER_ID); user.setGender("Female"); user.setNickname("Test Nickname"); user.setRegisterDate(new Date());Response response = client.path("/updateuser") .accept(MIME_TYPE).type(MIME_TYPE).put(user);assertResult("200", String.valueOf(response.getStatus())); System.out.println("Test updateUser method successfully"); }

4.刪除:delete請求 private static void testDeleteUser() {
WebClient client = WebClient.create(SERVICE_URL);Response response = client.path("/deleteuser/" + TEST_USER_ID) .accept(MIME_TYPE).type(MIME_TYPE).delete();assertResult("200", String.valueOf(response.getStatus())); System.out.println("Test getUsers method successfully");} private static void assertResult(String expectedResult , String realResult) { if (expectedResult != realResult && !expectedResult.equals(realResult)) { throw new RuntimeException("Test failed,excepted result:" + expectedResult + " real returned result:" + realResult); } }}
F.客戶端配置和spring集成

    <?xml version="1.0" encoding="UTF-8"?>  
  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"  
  3.     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"  
  4.     xmlns:oscache="http://www.springmodules.org/schema/oscache"  
  5.     xmlns:p="http://www.springframework.org/schema/p"       
  6.     xmlns:cache="http://www.springframework.org/schema/cache"   
  7.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd   
  8.     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd   
  9.     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd   
  10.     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd   
  11.     http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd">  
  12.     <context:annotation-config/>  
  13.     <import resource="applicationContext-cxf-server.xml"/>  
  14.     <context:component-scan base-package="jaxRs" />  
  15.     <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>  
  16.     <bean id="webClient" class="org.apache.cxf.jaxrs.client.WebClient" factory-method="create">  
  17.         <constructor-arg type="java.lang.String" value="http://localhost:8080/webservice/RESTWebService/" />  
  18.     </bean>  
  19.   
  20.     <bean id="rESTSample" class="org.apache.cxf.jaxrs.client.JAXRSClientFactory" factory-method="create">  
  21.         <constructor-arg type="java.lang.String" value="http://localhost:8080/webservice/RESTWebService/" />  
  22.         <constructor-arg type="java.lang.Class" value="jaxRs.RESTSample" />  
  23.     </bean>  
  24.   
  25. </beans>  



G.  註釋(Annotation):在 javax.ws.rs.* 中定義,是 JAX-RS (JSR 311) 規範的一部分。  
    @Path:定義資源基 URI。由上下文根和主機名組成,資源標識符類似於 http://localhost:8080/RESTful/rest/hello。  
    @GET:這意味着以下方法可以響應 HTTP GET 方法。  
    @Produces:以純文本方式定義響應內容 MIME 類型。  
  
    @Context: 使用該註釋注入上下文對象,比如 Request、Response、UriInfo、ServletContext 等。  
    @Path("{contact}"):這是 @Path 註釋,與根路徑 “/contacts” 結合形成子資源的 URI。  
    @PathParam("contact"):該註釋將參數注入方法參數的路徑,在本例中就是聯繫人 id。其他可用的註釋有 @FormParam、@QueryParam 等。  
    @Produces:響應支持多個 MIME 類型。在本例和上一個示例中,APPLICATION/XML 將是默認的 MIME 類型。 
        @Consumes:聲明該方法使用 HTML FORM。  
        @FormParam:注入該方法的 HTML 屬性確定的表單輸入。  
        @Response.created(uri).build(): 構建新的 URI 用於新創建的聯繫人(/contacts/{id})並設置響應代碼(201/created)。 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章