使用cxf开发RESTful WebService

使用cxf开发RESTful WebService

 

Cxf2.7实现了大部分的jax-rs规范,从cxf3.0开始实现jax-rs的全套规范

 

服务端


Spring3+cxf开发RESTfulweb service

 
服务端jar包(下边示例项目中有jar包)此lib包为基础包 可作为已有项目的cxf补充包,如需要完整包请看下面的项目链接,项目链接中有完整lib包。
 
实体类



WebService 实现类
  1. public class MyServiceImpl implements IMyService {  
  2.   
  3.     private HashMap<String, User> users = new HashMap<String,User>();  
  4.       
  5.     public MyServiceImpl(){  
  6.         init();  
  7.     }  
  8.       
  9.     public Response addUser(User user) {  
  10.   
  11.         users.put(user.getId(), user);  
  12.         System.out.println("添加用户成功");  
  13.         System.out.println(users.size());  
  14.         System.out.println(users.get("2").getName());  
  15.         return Response.ok().build();  
  16.     }  
  17.   
  18.   
  19.     public Response delUser(String id) {  
  20.         users.remove(id);  
  21.         System.out.println(users.size());  
  22.         return Response.ok().build();  
  23.     }  
  24.   
  25.   
  26.     public Response updateUser(User user) {  
  27.         users.put(user.getId(), user);  
  28.         System.out.println(users.get("1").getName());  
  29.         return Response.ok().build();  
  30.     }  
  31.   
  32.   
  33.     public User getUserById(String id) {  
  34.         return users.get(id);  
  35.     }  
  36.       
  37.       
  38.       
  39.     private void init(){  
  40.         User user = new User();  
  41.         user.setId("1");  
  42.         user.setName("温欢");  
  43.         users.put(user.getId(), user);  
  44.     }  
  45.   
  46.       
  47.     public List<User> findAllUsers() {  
  48.         List<User> userlist = new ArrayList<User>();  
  49.         userlist.add(users.get("1"));  
  50.         return userlist;  
  51.     }  
  52.   
  53. }  
1、spring-cxf.xml 配置文件
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="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.0.xsd
      http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
     <!-- 注意这里的jaxrs命名空间需要大家手动添加 -->
     <!-- 发布webservice -->
     <beanid="serviceBean"class="serviceImpl.MyServiceImpl"/>
     <jaxrs:serverid="userService"address="/myservice">
          <jaxrs:serviceBeans>
              <refbean="serviceBean"/>
          </jaxrs:serviceBeans>
          
          
          <jaxrs:extensionMappings>
           <entrykey="json"value="application/json"/>
           <entrykey="xml"value="application/xml"/>
        </jaxrs:extensionMappings>
        <jaxrs:languageMappings>
                <entrykey="en"value="en-gb"/>
        </jaxrs:languageMappings>
     </jaxrs:server>
</beans>






发布后访问显示这个说明发布成功:


客户端调用

普通的http请求即可
package nio;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
public class ClientTest {
    public static void main(String[] args ) throws Exception {
        //注意以下四种颜色区分: 分别为固定访问 ,web.xml配置请求拦截 , spring-cxf中配置具体模块示例 , restful请求uri
//         doGet("http://localhost:8080/RestfulWebservice/services/myservice/userservice/getUserById/1");
//         doPost("http://localhost:8080/RestfulWebservice/services/myservice/userservice/addUser/");
//         doDelete("http://localhost:8080/RestfulWebservice/services/myservice/userservice/delUser/1");
//         doPut("http://localhost:8080/RestfulWebservice/services/myservice/userservice/updateUser/");
    }
    private static void doGet(String url ){
      try {
          HttpClient client = new HttpClient();
             GetMethod method = new GetMethod( url );
             int statusCode = client .executeMethod( method );
             if ( statusCode != HttpStatus. SC_OK ) {
                 System. err .println( "Method failed: " + method .getStatusLine());
             }
             byte [] responseBody = method .getResponseBody();
             System. out .println( new String( responseBody ));
          } catch (Exception e ) {
               e .printStackTrace();
          }
      
    }
    private static void doPost(String url ) throws Exception{
        HttpClient client = new HttpClient(); 
        PostMethod method = new PostMethod( url ); 
        method .setRequestHeader( "Context-Type" , "application/xml; charset=utf-8" ); 
        method .setRequestHeader( "Accept" , "application/xml; charset=utf-8" ); 
 
        User user = new User();
        user .setId( "2" );
        user .setName( "fanjunkai" );
        String str = XMLBean.convertToXml( user );
        method .setRequestEntity( new StringRequestEntity( str , "application/xml" , "utf-8" )); 
        try
            client .executeMethod( method ); 
            String resp = ""
            if ( method .getStatusCode() == HttpStatus. SC_OK
                resp = method .getResponseBodyAsString(); 
            System. out .println( resp ); 
        } finally
            method .releaseConnection(); 
        }
    }
   
    private static void doDelete(String url ) throws Exception{
      HttpClient client = new HttpClient(); 
      DeleteMethod method = new DeleteMethod( url );
      int statusCode = client .executeMethod( method );
      if ( statusCode == HttpStatus. SC_OK ){
           System. err .println( "Method failed: " + method .getStatusLine());
      }
      byte [] responseBody = method .getResponseBody();
         System. out .println( new String( responseBody )); 
    }
   
    private static void doPut(String url ) throws Exception{
     HttpClient client = new HttpClient();
     PutMethod method = new PutMethod( url );
     User user = new User();
      user .setId( "1" );
      user .setName( "fanjunkai" );
     String str = XMLBean.convertToXml( user );
         method .setRequestHeader( "Context-Type" , "application/xml; charset=utf-8" ); 
        method .setRequestHeader( "Accept" , "application/xml; charset=utf-8" ); 
        method .setRequestEntity( new StringRequestEntity( str , "application/xml" , "utf-8" )); 
      int statusCode = client .executeMethod( method );
      if ( statusCode == HttpStatus. SC_OK ){
          System. err .println( "Method failed: " + method .getStatusLine());
     }
      byte [] responseBody = method .getResponseBody();
     System. out .println( new String( responseBody ));
    }
}



********************************所需工具类**********************************
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
public class XMLBean {
      /**
     * JavaBean转换成xml
     */
    public static String convertToXml(Object obj ) {
        return convertToXml( obj , "UTF-8" );
    }
    /**
     * JavaBean转换成xml
     */
    public static String convertToXml(Object obj , String encoding ) {
     if ( obj == null && "" .equals( obj ))
          return null ;
        String result = null ;
        try {
            JAXBContext context = JAXBContext.newInstance( obj .getClass());
            Marshaller marshaller = context .createMarshaller();
            marshaller .setProperty(Marshaller. JAXB_FORMATTED_OUTPUT , true );
            marshaller .setProperty(Marshaller. JAXB_ENCODING , encoding );
            StringWriter writer = new StringWriter();
            marshaller .marshal( obj , writer );
            result = writer .toString();
        } catch (Exception e ) {
            e .printStackTrace();
        }
        return result ;
    }
    /**
     *xml转换成JavaBean
     */
    @SuppressWarnings ( "unchecked" )
    public static <T> T converyToJavaBean(String xml , Class<T> c ) {
        T t = null ;
        try {
            JAXBContext context = JAXBContext.newInstance( c );
            Unmarshaller unmarshaller = context .createUnmarshaller();
            t = (T) unmarshaller .unmarshal( new StringReader( xml ));
        } catch (Exception e ) {
            e .printStackTrace();
        }
        return t ;
    }
}

js发送get请求,请求restfull webservice接口

<script src="/jquery/jquery-1.11.1.min.js"></script>
<script>
    $(document).ready(function(){
      $("button").click(function(){
      $.get("http://192.168.0.156:8080/RestfulWebservice/services/myservice/userservice/getUserById/1",function(data,status){
          alert("数据:" + data + "\n状态:" + status);
        });
      });
    });
</script>

js发送post请求,请求restfull webservice接口
<script src="/jquery/jquery-1.11.1.min.js">
</script>
<script>
    $(document).ready(function(){
      $("button").click(function(){
        $.post("http://192.168.0.156:8080/RestfulWebservice/services/myservice/userservice/addUser/",
        {
          name:"fanjunkai"
        },
        function(data,status){
          alert("数据:" + data + "\n状态:" + status);
        });
      });
    });
</script>
项目示例:http://download.csdn.net/detail/zzming2012/9751758
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fjkxyl

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值