Apache cxf JaxRs基本应用

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

在前一篇中,我们完成了《Apache cxf JaxWs基本应用》 的编写,我们现在实现一个Restful风格的Cxf 。

一、我们首先依旧是基于Maven project配置pom.xml的依赖

[html] view plaincopyprint?

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  

  2.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  

  3.     <modelVersion>4.0.0</modelVersion>  

  4.     <artifactId>abc-api</artifactId>  

  5.     <packaging>war</packaging>  

  6.     <version>${global.version}</version>  

  7.       

  8.     <parent>  

  9.         <groupId>com.abc.module</groupId>  

  10.         <artifactId>abc-parent</artifactId>  

  11.         <version>0.0.1-SNAPSHOT</version>  

  12.     </parent>  

  13.       

  14.     <dependencies>  

  15.         <dependency>  

  16.             <groupId>javax.ws.rs</groupId>  

  17.             <artifactId>jsr311-api</artifactId>  

  18.             <version>1.1.1</version>  

  19.         </dependency>  

  20.         <dependency>  

  21.             <groupId>org.apache.cxf</groupId>  

  22.             <artifactId>cxf-rt-transports-http</artifactId>  

  23.             <version>2.6.1</version>  

  24.         </dependency>  

  25.         <dependency>  

  26.             <groupId>org.apache.cxf</groupId>  

  27.             <artifactId>cxf-rt-frontend-jaxws</artifactId>  

  28.             <version>2.6.1</version>  

  29.         </dependency>  

  30.         <dependency>  

  31.             <groupId>org.apache.cxf</groupId>  

  32.             <artifactId>cxf-rt-frontend-jaxrs</artifactId>  

  33.             <version>2.6.1</version>  

  34.         </dependency>  

  35.         <dependency>  

  36.             <groupId>org.codehaus.jettison</groupId>  

  37.             <artifactId>jettison</artifactId>  

  38.             <version>1.3.5</version>  

  39.         </dependency>  

  40.         <dependency>  

  41.             <groupId>axis</groupId>  

  42.             <artifactId>axis</artifactId>  

  43.             <version>1.4</version>  

  44.         </dependency>  

  45.         <dependency>  

  46.             <groupId>org.codehaus.woodstox</groupId>  

  47.             <artifactId>stax2-api</artifactId>  

  48.             <version>3.1.1</version>  

  49.         </dependency>  

  50.         <dependency>  

  51.             <groupId>org.jbarcode</groupId>  

  52.             <artifactId>jbarcode</artifactId>  

  53.             <version>0.2.8</version>  

  54.         </dependency>  

  55.     </dependencies>  

  56.   

  57.     <build>  

  58.         <finalName>${project.artifactId}</finalName>  

  59.     </build>  

  60. </project>  


二、配置web.xml

[html] view plaincopyprint?

  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"  

  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.     <display-name>fsp-api</display-name>  

  7.     <context-param>  

  8.         <param-name>contextConfigLocation</param-name>  

  9.         <param-value>classpath*:application.xml</param-value>  

  10.     </context-param>  

  11.   

  12.     <!-- spring context listener -->  

  13.     <listener>  

  14.         <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>  

  15.     </listener>  

  16.     <listener>  

  17.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  

  18.     </listener>  

  19.   

  20.     <!-- CXF -->  

  21.     <servlet>  

  22.         <servlet-name>cxf</servlet-name>  

  23.         <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>  

  24.         <load-on-startup>1</load-on-startup>  

  25.     </servlet>  

  26.     <servlet-mapping>  

  27.         <servlet-name>cxf</servlet-name>  

  28.         <url-pattern>/services/*</url-pattern>  

  29.     </servlet-mapping>  

  30.       

  31. </web-app>  


三、创建Webservice对外接口

[java] view plaincopyprint?

  1. /** 

  2.  * Copyright (c) 2011-2014 All Rights Reserved. 

  3.  */  

  4. package com.abc.warehouse.service;  

  5.   

  6. import javax.servlet.http.HttpServletRequest;  

  7. import javax.servlet.http.HttpServletResponse;  

  8. import javax.ws.rs.GET;  

  9. import javax.ws.rs.POST;  

  10. import javax.ws.rs.Path;  

  11. import javax.ws.rs.PathParam;  

  12. import javax.ws.rs.Produces;  

  13. import javax.ws.rs.core.Context;  

  14. import javax.ws.rs.core.MediaType;  

  15.   

  16. @Path ("/logisticsApi")  

  17. public interface ILogisticsApi {  

  18.   

  19.     @GET   

  20.     @Path ("/doGet/{first}/{last}")  

  21.     @Produces(MediaType.APPLICATION_XML)  

  22.     public String doGet(@PathParam(value = "first") String firstName, @PathParam(value = "last") String lastName);  

  23.       

  24.       

  25.     @POST  

  26.     @Path("/itemConfirm")  

  27.     @Produces(MediaType.APPLICATION_XML)  

  28.     public String itemConfirm(String xmlParam,  

  29.                                     @Context HttpServletRequest servletRequest,   

  30.                                     @Context HttpServletResponse servletResponse);  

  31.   

  32. }  


四、实现Webservice接口

[java] view plaincopyprint?

  1. /** 

  2.  * Copyright (c) 2011-2014 All Rights Reserved. 

  3.  */  

  4. package com.abc.api.service;  

  5.   

  6. import javax.servlet.http.HttpServletRequest;  

  7. import javax.servlet.http.HttpServletResponse;  

  8.   

  9. import org.slf4j.Logger;  

  10. import org.slf4j.LoggerFactory;  

  11.   

  12. import com.abc.warehouse.service.ILogisticsApi;  

  13.   

  14.   

  15. public class LogisticsApiImpl implements ILogisticsApi {  

  16.   

  17.     private Logger log = LoggerFactory.getLogger(getClass());  

  18.       

  19.     /**  

  20.      * @see com.abc.warehouse.service.ILogisticsApi#itemConfirm(java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) 

  21.      */  

  22.     @Override  

  23.     public String itemConfirm(String xmlParam,  

  24.                                     HttpServletRequest servletRequest,   

  25.                                     HttpServletResponse servletResponse) {  

  26.         // TODO Auto-generated method stub  

  27.         // to do something ...  

  28.   

  29.         return response;  

  30.     }  

  31.   

  32.   

  33.     /**  

  34.      * @see com.abc.warehouse.service.ILogisticsApi#doGet(java.lang.String, java.lang.String) 

  35.      */  

  36.     @Override  

  37.     public String doGet(String firstName, String lastName) {  

  38.         // TODO Auto-generated method stub  

  39.         log.debug("doGet : " + firstName + ", lastName : " + lastName);  

  40.         // to to something ...  

  41.   

  42.         return response;  

  43.     }  

  44.   

  45.   

  46.   

  47. }  


五、配置Spring xml,让Webservice提供服务

[html] view plaincopyprint?

  1. <?xml version="1.0" encoding="UTF-8"?>  

  2. <beans xmlns="http://www.springframework.org/schema/beans"  

  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   

  4.     xmlns:jaxws="http://cxf.apache.org/jaxws"  

  5.     xmlns:jaxrs="http://cxf.apache.org/jaxrs"  

  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans  

  7.                        http://www.springframework.org/schema/beans/spring-beans.xsd  

  8.                        http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd  

  9.                     http://cxf.apache.org/jaxrs  

  10.                     http://cxf.apache.org/schemas/jaxrs.xsd">  

  11.   

  12.     <import resource="classpath:META-INF/cxf/cxf.xml" />  

  13.     <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />  

  14.     <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />  

  15.   

  16.     <bean id="encodingLoggingInInterceptor" class="com.abc.api.util.EncodingLoggingInInterceptor"/>  

  17.     <bean id="outLoggingInterceptor" class="org.apache.cxf.interceptor.LoggingOutInterceptor"/>  

  18.     <bean id="logisticsApi" class="com.abc.api.service.LogisticsApiImpl"/>  

  19.     <jaxrs:server id="logisticsApiServiceContainer">  

  20.         <jaxrs:serviceBeans>  

  21.             <ref bean="logisticsApi" />  

  22.         </jaxrs:serviceBeans>  

  23.           

  24.         <jaxrs:inInterceptors>  

  25.             <ref bean="encodingLoggingInInterceptor"/>  

  26.         </jaxrs:inInterceptors>  

  27.         <jaxrs:outInterceptors>  

  28.             <ref bean="outLoggingInterceptor"/>  

  29.         </jaxrs:outInterceptors>  

  30.           

  31.         <jaxrs:extensionMappings>  

  32.             <!-- <entry key="json" value="application/json" /> -->  

  33.             <entry key="xml" value="application/xml" />  

  34.         </jaxrs:extensionMappings>  

  35.       

  36.         <jaxrs:languageMappings>  

  37.             <entry key="en" value="en-gb"/>    

  38.         </jaxrs:languageMappings>  

  39.     </jaxrs:server>  

  40.   

  41. </beans>  


其中EncodingLoggingInInterceptor类主要是为了解决传输内容在LoggingInInterceptor类内构建并输出时的乱码问题

[java] view plaincopyprint?

  1. /** 

  2.  * Copyright (c) 2011-2014 All Rights Reserved. 

  3.  */  

  4. package com.abc.api.util;  

  5.   

  6. import org.apache.cxf.interceptor.Fault;  

  7. import org.apache.cxf.interceptor.LoggingInInterceptor;  

  8. import org.apache.cxf.message.Message;  

  9. import org.slf4j.Logger;  

  10. import org.slf4j.LoggerFactory;  

  11.   

  12.   

  13. public class EncodingLoggingInInterceptor extends LoggingInInterceptor {  

  14.   

  15.     private Logger log = LoggerFactory.getLogger(getClass());  

  16.       

  17.     /** 

  18.      *  

  19.      */  

  20.     public EncodingLoggingInInterceptor() {  

  21.         // TODO Auto-generated constructor stub  

  22.         super();  

  23.     }  

  24.       

  25.     /**  

  26.      * @see org.apache.cxf.interceptor.LoggingInInterceptor#handleMessage(org.apache.cxf.message.Message) 

  27.      */  

  28.     @Override  

  29.     public void handleMessage(Message message) throws Fault {  

  30.         // TODO Auto-generated method stub  

  31.           

  32.         String encoding = System.getProperty("file.encoding");  

  33.         encoding = encoding == null || encoding.equals("") ? "UTF-8" : encoding;  

  34.           

  35.         log.debug("encoding : " + encoding);  

  36.         message.put(Message.ENCODING, encoding);  

  37.           

  38.         super.handleMessage(message);  

  39.     }  

  40. }  

至此,Webservice服务器端代码已经编写完成,假设Maven project名字为abc-api,那么访问该Webservice接口的地址为:http://ip:port/abc-api/services/


六、接下来我们编写一个基于WebClient简单客户端

[java] view plaincopyprint?

  1. /** 

  2.  * Copyright (c) 2011-2014 All Rights Reserved. 

  3.  */  

  4. package com.abc.api.service;  

  5.   

  6. import static org.junit.Assert.*;  

  7.   

  8. import javax.ws.rs.core.MediaType;  

  9.   

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

  11. import org.junit.After;  

  12. import org.junit.Before;  

  13. import org.junit.Test;  

  14.   

  15.   

  16. public class LogisticsApiTester {  

  17.   

  18.     private WebClient client;  

  19.     private String baseAddress = "http://localhost:8080/abc-api/services/logisticsApi";  

  20.     /** 

  21.      *  

  22.      * @throws java.lang.Exception 

  23.      */  

  24.     @Before  

  25.     public void setUp() throws Exception {  

  26.         client = WebClient.create(baseAddress)  

  27.             .header("charset", "UTF-8")  

  28.             .encoding("UTF-8")  

  29.             .acceptEncoding("UTF-8");  

  30.     }  

  31.   

  32.     /** 

  33.      *  

  34.      * @throws java.lang.Exception 

  35.      */  

  36.     @After  

  37.     public void tearDown() throws Exception {  

  38.         client = null;  

  39.     }  

  40.   

  41.     /** 

  42.      * Test method for {@link com.abc.api.service.LogisticsApiImpl#itemConfirm(java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)}. 

  43.      */  

  44.     @Test  

  45.     public void testItemConfirm() {  

  46.         //fail("Not yet implemented");  

  47.           

  48.         Object xmlParam = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"  

  49.             + "<itemName>诺基亚</itemName>";  

  50.         String responseMessage = client.path("itemConfirm")  

  51.                                         .accept(MediaType.APPLICATION_XML)  

  52.                                         .post(xmlParam, String.class);  

  53.         System.out.println("responseMessage : " + responseMessage);  

  54.         assertNotEquals(responseMessage, null);  

  55.     }  

  56.   

  57.     /** 

  58.      * Test method for {@link com.abc.api.service.LogisticsApiImpl#doGet(java.lang.String, java.lang.String)}. 

  59.      */  

  60.     @Test  

  61.     public void testDoGet() {  

  62.         //fail("Not yet implemented");  

  63.           

  64.         String responseString = client.path("doGet/{first}/{last}", 1, 2)  

  65.                                     .accept(MediaType.APPLICATION_XML)  

  66.                                     .get(String.class);  

  67.         assertNotEquals(responseString, null);  

  68.     }  

  69.   

  70.   

  71. }  



到这里我们就完成了基于Apache cxf JaxRs的服务端和客户端的Demo编写。



转载于:https://my.oschina.net/sniperLi/blog/505471

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/544205.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

白嫖1年阿里云,反手就搭一个Java环境

作者 | 磊哥来源 | Java中文社群&#xff08;ID&#xff1a;javacn666&#xff09;转载请联系授权&#xff08;微信ID&#xff1a;GG_Stone&#xff09;早上收到阿里云小姐姐的消息&#xff0c;阿里云有搞事情了&#xff0c;这次是送一年的阿里云 ECS 服务器。有便宜不占王八蛋…

setseed_Java Random setSeed()方法与示例

setseed随机类setSeed()方法 (Random Class setSeed() method) setSeed() method is available in java.util package. setSeed()方法在java.util包中可用。 setSeed() method is used to set the given seed of this Random Number Generator. setSeed()方法用于设置此随机数生…

.Net 自己写个简单的 半 ORM (练手)

ORM 大家都知道&#xff0c; .Net 是EF 还有一些其他的ORM 从JAVA 中移植过来的 有 &#xff0c; 大神自己写的也有 不管ORM 提供什么附加的 乱七八糟的功能 但是 最主要的 还是 关系映射 的事情。 我自己一直在使用ORMDapper 这个很小的ORM 第一次看到这个ORM 是通过一…

synchronized和ReentrantLock的5个区别!

作者 | 磊哥来源 | Java面试真题解析&#xff08;ID&#xff1a;aimianshi666&#xff09;转载请联系授权&#xff08;微信ID&#xff1a;GG_Stone&#xff09;在 Java 中&#xff0c;常用的锁有两种&#xff1a;synchronized&#xff08;内置锁&#xff09;和 ReentrantLock&a…

Java Random nextInt()方法与示例

随机类nextInt()方法 (Random Class nextInt() method) Syntax: 句法&#xff1a; public int nextInt();public int nextInt(int num);nextInt() method is available in java.util package. nextInt()方法在java.util包中可用。 nextInt() method is used to return the nex…

《小强升职记》读后感和思维导图

语言幽默轻松&#xff0c;寓教于乐&#xff0c;看完之后有挽起袖子大干一场的冲动&#xff0c;但是诚如书中所言&#xff0c;“不做收藏家&#xff0c;要做建筑工”&#xff0c;实践和坚持才能有所收获。第一次画思维导图(′▽〃)Xmind格式文件转载于:https://www.cnblogs.com/…

oppo后端16连问

前言 大家好&#xff0c;我是磊哥。最近有位读者去面试了oppo&#xff0c;给大家整理了面试真题的答案。希望对大家有帮助哈&#xff0c;一起学习&#xff0c;一起进步。聊聊你印象最深刻的项目&#xff0c;或者做了什么优化。你项目提到分布式锁&#xff0c;你们是怎么使用分布…

java enummap_Java EnumMap values()方法与示例

java enummapEnumMap类values()方法 (EnumMap Class values() method) values() method is available in java.util package. values()方法在java.util包中可用。 values() method is used to get all the values in a Collection view of this enum map. values()方法用于获取…

django 1.8 官方文档翻译:2-1-1 模型语法

模型 模型是你的数据的唯一的、权威的信息源。它包含你所储存数据的必要字段和行为。通常&#xff0c;每个模型对应数据库中唯一的一张表。 基础&#xff1a; 每个模型都是django.db.models.Model 的一个Python 子类。模型的每个属性都表示数据库中的一个字段。Django 提供一套…

实战!阿里神器 Seata 实现 TCC 模式解决分布式事务

今天这篇文章介绍一下Seata如何实现TCC事务模式&#xff0c;文章目录如下&#xff1a;目录什么是TCC模式&#xff1f;TCC&#xff08;Try Confirm Cancel&#xff09;方案是一种应用层面侵入业务的两阶段提交。是目前最火的一种柔性事务方案&#xff0c;其核心思想是&#xff1…

Java Dictionary get()方法与示例

字典类的get()方法 (Dictionary Class get() method) get() method is available in java.util package. get()方法在java.util包中可用。 get() method is used to get the value on the specified key element (key_ele) in this dictionary. get()方法用于获取此字典中指定键…

[CareerCup] 8.10 Implement a Hash Table 实现一个哈希表

8.10 Design and implement a hash table which uses chaining (linked lists) to handle collisions. 这道题让我们实现一个简单的哈希表&#xff0c;我们采用了最简单的那种取余映射的方式来实现&#xff0c;我们使用Cell来保存一对对的key和value的映射关系&#xff0c;然后…

Spring Boot 中实现跨域的 5 种方式,你一定要知道!

一、为什么会出现跨域问题出于浏览器的同源策略限制。同源策略&#xff08;Sameoriginpolicy&#xff09;是一种约定&#xff0c;它是浏览器最核心也最基本的安全功能&#xff0c;如果缺少了同源策略&#xff0c;则浏览器的正常功能可能都会受到影响。可以说Web是构建在同源策略…

stl:queue 源码_C ++ STL中的queue :: empty()和queue :: size()

stl:queue 源码In C STL, Queue is a type of container that follows FIFO (First-in-First-out) elements arrangement i.e. the elements which inserts first will be removed first. In queue, elements are inserted at one end known as "back" and are delet…

术中导航_密码术中的计数器(CTR)模式

术中导航The Counter Mode or CTR is a simple counter based block cipher implementation in cryptography. Each or every time a counter initiated value is encrypted and given as input to XOR with plaintext or original text which results in ciphertext block. Th…

Android社交类APP动态详情代码实现通用模板

&#xfeff;&#xfeff;Android社交类APP动态详情代码实现通用模板 Android平台上一些比较流行的社交类APP比如微信、陌陌等&#xff0c;都有动态详情页&#xff0c;在该页面&#xff0c;用户发表的动态详情&#xff0c;好友可以发起评论、点赞等等。这种设计在微信和陌陌上大…

聊聊并发编程的12种业务场景

前言并发编程是一项非常重要的技术&#xff0c;无论在面试&#xff0c;还是工作中出现的频率非常高。并发编程说白了就是多线程编程&#xff0c;但多线程一定比单线程效率更高&#xff1f;答&#xff1a;不一定&#xff0c;要看具体业务场景。毕竟如果使用了多线程&#xff0c;…

软件工程编码阶段_软件工程的编码阶段

软件工程编码阶段The coding phase in the software engineering paradigm is usually defined after the designing phase. In this phase, the developers or the coders have to implement the software design practically using any computer language(s) so that the sof…

梳理50道经典计算机网络面试题

我梳理了50道计算机网络面试题&#xff0c;每一道题目都特别经典&#xff0c;大厂也非常喜欢问。相信大家看完&#xff0c;会有新的收获滴~1. 说说HTTP常用的状态码及其含义&#xff1f;思路: 这道面试题主要考察候选人&#xff0c;是否掌握HTTP状态码这个基础知识点。不管是不…

A successful Git branching model

原文&#xff1a;http://nvie.com/posts/a-successful-git-branching-model/ In this post I present the development model that I’ve introduced for all of my projects (both at work and private) about a year ago, and which has turned out to be very successful. I…