热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

ApacheCXF整合RESTfulServices

为什么80%的码农都做不了架构师?一、首先还是创建个项目并把包导入去,弄2个package,分别用于装server和client。记得要把comm

为什么80%的码农都做不了架构师?>>>   hot3.png

一、首先还是创建个项目并把包导入去,弄2个package,分别用于装server和client。记得要把commons-httpclient-3.1.jar也要放入来,因为Client用http请求的:

二、在com.yao.server下新建一个类Customer,我们注意到有一个@XmlRootElement(name="Customer")这个是用来标识Customer是可用来转化为xml的:

package com.yao.rs.server;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElement(name="Customer")
public class Customer {private long id;private String name;@Overridepublic String toString() {return "Customer [id=" + id + ", name=" + name + "]";}public long getId() {return id;}public void setId(long id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}}



三、同理再新建一个类Product:

package com.yao.rs.server;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElement(name="Product")
public class Product {private long id;private String description;public long getId() {return id;}public void setId(long id) {this.id = id;}public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}@Overridepublic String toString() {return "Product [id=" + id + ", description=" + description + "]";}}



四、再新建一个Order类。该类有一个getProduct方法,通过id返回一个 Product实例。:该方法有2个注释@GET和@Path("products/{productId}/"),前者表示为用get发起请求,后者为匹配的路径,下面的Client会用到这个请求。

package com.yao.rs.server;import java.util.HashMap;
import java.util.Map;import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;public class Order {private long id;private String description;private Map products = new HashMap();public Order(){init();}final void init() {Product p = new Product();p.setId(323);p.setDescription("product 323");products.put(p.getId(), p);}@GET@Path("products/{productId}/")public Product getProduct(@PathParam("productId") int productId){System.out.println("----invoking getProduct with id: " + productId);Product p = products.get(new Long(productId));return p;}public long getId() {return id;}public void setId(long id) {this.id = id;}public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}@Overridepublic String toString() {return "Order [id=" + id + ", description=" + description + ", products=" + products + "]";}}



五、新建CustomerService类,这个类为客户端要调用的。每一个方法都有对应的请求方式与匹配路径,以便客户端可以匹配调用。

package com.yao.rs.server;import java.util.HashMap;
import java.util.Map;import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;@Path("/customerservice/")
@Produces("text/xml")//可以通过修改@Produces注解来声明暴露接口返回的json还是xml数据格式
public class CustomerService {long currentId = 123;Map customers = new HashMap();Map orders = new HashMap();public CustomerService() {init();}@GET@Path("/customers/{id}/")public Customer getCustomer(@PathParam("id") String id) {System.out.println("----invoking getCustomer, Customer id is: " + id);long idNumber = Long.parseLong(id);Customer c = customers.get(idNumber);return c;}@PUT@Path("/customers/")public Response updateCustomer(Customer customer) {System.out.println("----invoking updateCustomer, Customer name is: " + customer.getName());Customer c = customers.get(customer.getId());Response r;if (c != null) {customers.put(customer.getId(), customer);r = Response.ok().build();} else {r = Response.notModified().build();}return r;}@POST@Path("/customers/")public Response addCustomer(Customer customer) {System.out.println("----invoking addCustomer, Customer name is: " + customer.getName());customer.setId(++currentId);customers.put(customer.getId(), customer);return Response.ok(customer).build();}@DELETE@Path("/customers/{id}/")public Response deleteCustomer(@PathParam("id") String id) {System.out.println("----invoking deleteCustomer, Customer id is: " + id);long idNumber = Long.parseLong(id);Customer c = customers.get(idNumber);Response r;if (c != null) {r = Response.ok().build();customers.remove(idNumber);} else {r = Response.notModified().build();}return r;}@Path("/orders/{orderId}/")public Order getOrder(@PathParam("orderId") String orderId) {System.out.println("----invoking getOrder, Order id is: " + orderId);long idNumber = Long.parseLong(orderId);Order c = orders.get(idNumber);return c;}final void init() {Customer c = new Customer();c.setName("John");c.setId(123);customers.put(c.getId(), c);Order o = new Order();o.setDescription("order 223");o.setId(223);orders.put(o.getId(), o);}}



六、新建一个source folder名为config,在里面放置2个文件add_customer.xml和update_customer.xml用于客户端增加与更新的xml文件。如下为其代码:

    6.1 add_customer.xml


Jack

    6.2 update_customer.xml


Mary123
七、新建Server启动类:

package com.yao.rs.server;import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider;public class Server {protected Server() throws Exception {JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();sf.setResourceClasses(CustomerService.class);sf.setResourceProvider(CustomerService.class, new SingletonResourceProvider(new CustomerService()));sf.setAddress("http://localhost:9000/");sf.create();}public static void main(String args[]) throws Exception {new Server();System.out.println("Server ready...");Thread.sleep(5 * 6000 * 1000);System.out.println("Server exiting");System.exit(0);}
}
八、新建客户端类Client:

package com.yao.rs.client;import java.io.File;
import java.io.InputStream;
import java.net.URL;import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.FileRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.RequestEntity;import org.apache.cxf.helpers.IOUtils;
import org.apache.cxf.io.CachedOutputStream;
import org.apache.cxf.resource.URIResolver;public final class Client {private Client() {}public static void main(String args[]) throws Exception {// Sent HTTP GET request to query all customer info/** URL url = new URL("http://localhost:9000/customers");* System.out.println("Invoking server through HTTP GET to query all* customer info"); InputStream in = url.openStream(); StreamSource* source = new StreamSource(in); printSource(source);*/// Sent HTTP GET request to query customer infoSystem.out.println("Sent HTTP GET request to query customer info");URL url = new URL("http://localhost:9000/customerservice/customers/123");InputStream in = url.openStream();System.out.println(getStringFromInputStream(in));// Sent HTTP GET request to query sub resource product infoSystem.out.println("\n");System.out.println("Sent HTTP GET request to query sub resource product info");url = new URL("http://localhost:9000/customerservice/orders/223/products/323");in = url.openStream();System.out.println(getStringFromInputStream(in));// Sent HTTP PUT request to update customer infoSystem.out.println("\n");System.out.println("Sent HTTP PUT request to update customer info");Client client = new Client();String inputFile = client.getClass().getResource("/update_customer.xml").getFile();URIResolver resolver = new URIResolver(inputFile);File input = new File(resolver.getURI());PutMethod put = new PutMethod("http://localhost:9000/customerservice/customers");RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");put.setRequestEntity(entity);HttpClient httpclient = new HttpClient();try {int result = httpclient.executeMethod(put);System.out.println("Response status code: " + result);System.out.println("Response body: ");System.out.println(put.getResponseBodyAsString());} finally {// Release current connection to the connection pool once you are// doneput.releaseConnection();}// Sent HTTP POST request to add customerSystem.out.println("\n");System.out.println("Sent HTTP POST request to add customer");inputFile = client.getClass().getResource("/add_customer.xml").getFile();resolver = new URIResolver(inputFile);input = new File(resolver.getURI());PostMethod post = new PostMethod("http://localhost:9000/customerservice/customers");post.addRequestHeader("Accept" , "text/xml");entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");post.setRequestEntity(entity);httpclient = new HttpClient();try {int result = httpclient.executeMethod(post);System.out.println("Response status code: " + result);System.out.println("Response body: ");System.out.println(post.getResponseBodyAsString());} finally {// Release current connection to the connection pool once you are// donepost.releaseConnection();}System.out.println("\n");System.exit(0);}private static String getStringFromInputStream(InputStream in) throws Exception {CachedOutputStream bos = new CachedOutputStream();IOUtils.copy(in, bos);in.close();bos.close();return bos.getOut().toString();}}



九、启动Server类打印:

2014-8-22 12:45:34 org.apache.cxf.endpoint.ServerImpl initDestination
信息: Setting the server's publish address to be http://localhost:9000/
2014-8-22 12:45:34 org.eclipse.jetty.server.Server doStart
信息: jetty-8.1.15.v20140411
2014-8-22 12:45:34 org.eclipse.jetty.server.AbstractConnector doStart
信息: Started SelectChannelConnector@localhost:9000
2014-8-22 12:45:35 org.apache.cxf.wsdl.service.factory.ReflectionServiceFactoryBean buildServiceFromWSDL
信息: Creating Service {http://docs.oasis-open.org/ws-dd/ns/discovery/2009/01}Discovery from WSDL: classpath:/org/apache/cxf/ws/discovery/wsdl/wsdd-discovery-1.1-wsdl-os.wsdl
2014-8-22 12:45:35 org.apache.cxf.endpoint.ServerImpl initDestination
信息: Setting the server's publish address to be soap.udp://239.255.255.250:3702
2014-8-22 12:45:35 org.apache.cxf.wsdl.service.factory.ReflectionServiceFactoryBean buildServiceFromClass
信息: Creating Service {http://docs.oasis-open.org/ws-dd/ns/discovery/2009/01}DiscoveryProxy from class org.apache.cxf.jaxws.support.DummyImpl
Server ready...



十、启动Client类打印:

Sent HTTP GET request to query customer info
123JohnSent HTTP GET request to query sub resource product info
product 323323Sent HTTP PUT request to update customer info
Response status code: 200
Response body: Sent HTTP POST request to add customer
Response status code: 200
Response body:
124Jack



同时Server的端口也会打印:

----invoking getCustomer, Customer id is: 123
----invoking getOrder, Order id is: 223
----invoking getProduct with id: 323
----invoking updateCustomer, Customer name is: Mary
----invoking addCustomer, Customer name is: Jack



十一、最终工程的目录如下:



转:https://my.oschina.net/jamaly/blog/305525



推荐阅读
  • Java自带的观察者模式及实现方法详解
    本文介绍了Java自带的观察者模式,包括Observer和Observable对象的定义和使用方法。通过添加观察者和设置内部标志位,当被观察者中的事件发生变化时,通知观察者对象并执行相应的操作。实现观察者模式非常简单,只需继承Observable类和实现Observer接口即可。详情请参考Java官方api文档。 ... [详细]
  • 关键词:Golang, Cookie, 跟踪位置, net/http/cookiejar, package main, golang.org/x/net/publicsuffix, io/ioutil, log, net/http, net/http/cookiejar ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • Spring源码解密之默认标签的解析方式分析
    本文分析了Spring源码解密中默认标签的解析方式。通过对命名空间的判断,区分默认命名空间和自定义命名空间,并采用不同的解析方式。其中,bean标签的解析最为复杂和重要。 ... [详细]
  • XML介绍与使用的概述及标签规则
    本文介绍了XML的基本概念和用途,包括XML的可扩展性和标签的自定义特性。同时还详细解释了XML标签的规则,包括标签的尖括号和合法标识符的组成,标签必须成对出现的原则以及特殊标签的使用方法。通过本文的阅读,读者可以对XML的基本知识有一个全面的了解。 ... [详细]
  • flowable工作流 流程变量_信也科技工作流平台的技术实践
    1背景随着公司业务发展及内部业务流程诉求的增长,目前信息化系统不能够很好满足期望,主要体现如下:目前OA流程引擎无法满足企业特定业务流程需求,且移动端体 ... [详细]
  • Android开发实现的计时器功能示例
    本文分享了Android开发实现的计时器功能示例,包括效果图、布局和按钮的使用。通过使用Chronometer控件,可以实现计时器功能。该示例适用于Android平台,供开发者参考。 ... [详细]
  • 本文介绍了如何使用C#制作Java+Mysql+Tomcat环境安装程序,实现一键式安装。通过将JDK、Mysql、Tomcat三者制作成一个安装包,解决了客户在安装软件时的复杂配置和繁琐问题,便于管理软件版本和系统集成。具体步骤包括配置JDK环境变量和安装Mysql服务,其中使用了MySQL Server 5.5社区版和my.ini文件。安装方法为通过命令行将目录转到mysql的bin目录下,执行mysqld --install MySQL5命令。 ... [详细]
  • Java在运行已编译完成的类时,是通过java虚拟机来装载和执行的,java虚拟机通过操作系统命令JAVA_HOMEbinjava–option来启 ... [详细]
  • MyBatis多表查询与动态SQL使用
    本文介绍了MyBatis多表查询与动态SQL的使用方法,包括一对一查询和一对多查询。同时还介绍了动态SQL的使用,包括if标签、trim标签、where标签、set标签和foreach标签的用法。文章还提供了相关的配置信息和示例代码。 ... [详细]
  • 本文讨论了如何在codeigniter中识别来自angularjs的请求,并提供了两种方法的代码示例。作者尝试了$this->input->is_ajax_request()和自定义函数is_ajax(),但都没有成功。最后,作者展示了一个ajax请求的示例代码。 ... [详细]
  • CEPH LIO iSCSI Gateway及其使用参考文档
    本文介绍了CEPH LIO iSCSI Gateway以及使用该网关的参考文档,包括Ceph Block Device、CEPH ISCSI GATEWAY、USING AN ISCSI GATEWAY等。同时提供了多个参考链接,详细介绍了CEPH LIO iSCSI Gateway的配置和使用方法。 ... [详细]
  • iOS超签签名服务器搭建及其优劣势
    本文介绍了搭建iOS超签签名服务器的原因和优势,包括不掉签、用户可以直接安装不需要信任、体验好等。同时也提到了超签的劣势,即一个证书只能安装100个,成本较高。文章还详细介绍了超签的实现原理,包括用户请求服务器安装mobileconfig文件、服务器调用苹果接口添加udid等步骤。最后,还提到了生成mobileconfig文件和导出AppleWorldwideDeveloperRelationsCertificationAuthority证书的方法。 ... [详细]
  • 本文讨论了如何使用Web.Config进行自定义配置节的配置转换。作者提到,他将msbuild设置为详细模式,但转换却忽略了带有替换转换的自定义部分的存在。 ... [详细]
  • Android系统源码分析Zygote和SystemServer启动过程详解
    本文详细解析了Android系统源码中Zygote和SystemServer的启动过程。首先介绍了系统framework层启动的内容,帮助理解四大组件的启动和管理过程。接着介绍了AMS、PMS等系统服务的作用和调用方式。然后详细分析了Zygote的启动过程,解释了Zygote在Android启动过程中的决定作用。最后通过时序图展示了整个过程。 ... [详细]
author-avatar
湛江耳鼻喉医院196_991
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有