使用cxf开发RESTful WebService

    xiaoxiao2021-03-25  95

    使用cxf开发RESTful WebService

     

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

     

    服务端

    Spring3+cxf开发RESTfulweb service

      服务端jar包(下边示例项目中有jar包)此lib包为基础包 可作为已有项目的cxf补充包,如需要完整包请看下面的项目链接,项目链接中有完整lib包。   实体类 WebService 实现类 public class MyServiceImpl implements IMyService {          private HashMap<String, User> users = new HashMap<String,User>();              public MyServiceImpl(){           init();       }              public Response addUser(User user) {              users.put(user.getId(), user);           System.out.println("添加用户成功");           System.out.println(users.size());           System.out.println(users.get("2").getName());           return Response.ok().build();       }             public Response delUser(String id) {           users.remove(id);           System.out.println(users.size());           return Response.ok().build();       }             public Response updateUser(User user) {           users.put(user.getId(), user);           System.out.println(users.get("1").getName());           return Response.ok().build();       }             public User getUserById(String id) {           return users.get(id);       }                            private void init(){           User user = new User();           user.setId("1");           user.setName("温欢");           users.put(user.getId(), user);       }                 public List<User> findAllUsers() {           List<User> userlist = new ArrayList<User>();           userlist.add(users.get("1"));           return userlist;       }      }   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
    转载请注明原文地址: https://ju.6miu.com/read-19528.html

    最新回复(0)