CXF創建簡單的RESTful 風格的webservice

淺談REST原理

REST與RPC(Rmote Procedure Call)幾乎沒有任何關係,RPC是面向服務的,並關注行爲和動作;而REST是面向資源的,強調描述應用程序的事物和名詞。儘管URL在REST中起了關鍵作用,但它們僅僅是整體的一部分而已。
更簡潔的講,REST就是將資源的狀態以合適的形式從服務端轉移到客戶端(或者反之)。
 
【Spring本身也提供對REST的支持,但本章我們只是對CXF的RESTful進行簡單應用】

環境

JDK7.0  +  Tomcat7.x  + Spring4.1.8

項目結構

服務端代碼

a) IRESTfulWebService

package com.restful.base.service;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;

import com.restful.base.vo.LoginUser;

public interface IRESTfulWebService {
	
	@GET
    @Path(value = "/{id}/info")  
	@Consumes( { MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
	String  findById(@PathParam("id") String id);
	
	@GET
    @Path(value = "/search")  
	@Consumes( { MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
	String  findByAll();
	
	
	@GET
    @Path(value = "/{loginId}/user")  
	@Consumes( { MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
	LoginUser  findUserById(@PathParam("loginId") String loginId);
} 


b) RESTfulWebServiceImp(接口實現類)

package com.restful.base.service.imp;

import org.apache.log4j.Logger;

import com.restful.base.service.IRESTfulWebService;
import com.restful.base.vo.LoginUser;

public class RESTfulWebServiceImp implements IRESTfulWebService {
	
	private static final Logger log = Logger.getLogger(RESTfulWebServiceImp.class);

	@Override
	public String findById(String id) {
		log.info("---RESTful webservice測試--- param:"+id);
		return "restful webservice test success! id="+id;
	}

	@Override
	public String findByAll() {
		log.info("---RESTful webservice測試---");
		return "restful webservice test success!";
	}

	@Override
	public LoginUser findUserById(String loginId) {
		log.info("---RESTful webservice測試--- loginid:"+loginId);
		return this.getUserInfo();
	}
	
	//模擬數據庫賦值
	private LoginUser getUserInfo(){
		LoginUser user = new LoginUser();
		user.setId("123");
		user.setLoginid("login1");
		user.setPwd("pwd123");
		user.setRegisterDate("2015-11-04");
		user.setStatus("1");
		return user;
	}

} 
@Produces 
@Produces註釋用來指定將要返回給client端的數據標識類型(MIME)。
指定多個MIME類型 
@Produces({“application/json”,“application/xml”})

@Consumes 
@Consumes與@Produces相反,用來指定可以接受client發送過來的MIME類型,也可以指定多個MIME類型

c) applicationContext-cxf.xml (註冊)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:jaxws="http://cxf.apache.org/jaxws"
     xmlns:jaxrs="http://cxf.apache.org/jaxrs"
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
                            http://www.springframework.org/schema/beans/spring-beans-4.1.xsd  
                            http://cxf.apache.org/jaxws   
                            http://cxf.apache.org/schemas/jaxws.xsd 
                            http://cxf.apache.org/jaxrs 
                            http://cxf.apache.org/schemas/jaxrs.xsd ">
 
	<!--  日誌攔截  -->
	<bean id="inMessageInterceptor" class="org.apache.cxf.interceptor.LoggingInInterceptor" />  
    <bean id="outMessageInterceptor" class="org.apache.cxf.interceptor.LoggingOutInterceptor"/>  
    
    <!-- RESTful webservice -->
    <bean id="service" class="com.restful.base.service.imp.RESTfulWebServiceImp" />
    <jaxrs:server id="rest1" address="/hello">
        <jaxrs:serviceBeans>
            <ref bean="service" />
        </jaxrs:serviceBeans>
        <jaxrs:inInterceptors>  
           <ref bean="inMessageInterceptor"/>  
        </jaxrs:inInterceptors>  
        <jaxrs:outInterceptors>  
            <ref bean="outMessageInterceptor"/>  
        </jaxrs:outInterceptors>  
    </jaxrs:server>
   
</beans>

訪問頁面



客戶端代碼

a)RESTfullCilent

package com.restful.base.webclient;

import java.lang.reflect.Field;

import javax.ws.rs.core.MediaType;

import org.apache.cxf.jaxrs.client.WebClient;

import com.restful.base.vo.LoginUser;

public class RESTfullCilent {
	
	private static final String CATEGORY_URL = "http://localhost:8080/cxfrestful/webservice";  
 	private static final String path1 = "/hello/005/info";
 	private static final String path2 = "/hello/search";
 	private static final String path3 = "/hello/log1/user";
  
    public static void main(String[] args) throws Exception {  
       String str = webClient(path1,String.class);
       System.out.println("RESTful 測試1,服務端返回信息:"+str);
       
       str = webClient(path2,String.class);
       System.out.println("RESTful 測試2,服務端返回信息:"+str);
       
       LoginUser user = null;
       user = webClient(path3,LoginUser.class);
       
       System.out.println("RESTful 測試3,服務端返回信息:");
       Field[] file =  LoginUser.class.getDeclaredFields();
       for (int i = 0; i < file.length; i++) {
    	   Field f = file[i];
           f.setAccessible( true ); // 設置些屬性是可以訪問的
           Object val = f.get(user); // 得到此屬性的值  
    	   System.out.print(" "+f.getName()+"="+val);
       }
    }  

       private static <T> T  webClient(String path,Class<T> c){
          T t =null;
          WebClient client = WebClient.create(CATEGORY_URL).path(path);
          t = client.accept(MediaType.APPLICATION_XML).get(c);
          return t;
        }
}


b)執行客戶端結果






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章