JavaEE的RESTful标准技术JAX-RS,jersey-client客户端使用介绍【享学Java】

软件开发往往是这样:最开始的 90% 代码占用了开始的 90% 的开发时间;剩下10% 代码同样需要 90% 的开发时间。

前言

Spring大行其道的今天,很多人对Java的RESTful规范JAX-RS可能比较陌生甚至未曾听闻,当然这也是能被“理解”的,毕竟Spring似乎现在已是JavaEE的事实标准。

现在有越来越多的公司希望能以简单而又贴合Web架构本身的方式公开Web API,因此REST变得越来越重要和流行。使用Ajax进行通信的富浏览器端也在朝这个目标不断迈进。这个架构原则提升了万维网的可伸缩性,无论何种应用都能从该原则中受益无穷。


正文

其实关于JAX-RS的资料并不算多,根据存在即合理原则我们需要承认它的重要性肯定比不上Spring,但是由于老外一般喜欢使用JavaEE规范技术,所以使得一些开源社区框架使用的均是基于JAX-RS的实现,因此对它来个简单的了解还是很有必要的。


何为JAX-RS(1.0和2.0)

JAX-RS是JAVA EE6引入的一个新技术,它的英文全称为Java API for RESTful Web Services,它的核心概念是Resource,即面向资源。JavaEE 6于2019年12月份正式发布。


JSR 311

它被称为JAX-RS 1.0标准,它提供一套JSR311标准API:

<dependency>
    <groupId>javax.ws.rs</groupId>
    <artifactId>jsr311-api</artifactId>
    <version>1.1.1</version>
</dependency>

在这里插入图片描述
这些注解和Spring MVC@RequestMapping、@RequestParam、@PathVariable...何其相似,各位可以类比起来学习,本处不必一一展开。但是注意一点,SpringMVC在开发REST应用时,是不支持JSR311标准的。


JSR 339

它是JAX-RS 2.0版本,于2018年发布。它不仅定义了一套用于构建 RESTful 网络服务的 API,同时也通过增强客户端 API 功能简化了REST 客户端的构建过程。

<dependency>
    <groupId>jakarta.ws.rs</groupId>
    <artifactId>jakarta.ws.rs-api</artifactId>
    <version>2.1.6</version>
</dependency>

在这里插入图片描述
规范API的向下兼容度还是非常好的,它在1.0规范的基础上对Client的构建做了增强,如提供了javax.ws.rs.client.ClientBuilderjavax.ws.rs.client.WebTarget等实用API。


落地产品

每个JavaEE规范都应对应其落地产品的实现,就像JPA的实现落地实现有HibernateTopLink等。基于JAX-RS实现的框架有Jersey、RESTEasy,当然还有Apache CXF。但是,因为Jersey是最早的实现(出现得比JSR311还早),是JSR311参考的主要对象,所以,可以说Jersey就是事实上的标准,就像Hibernate是JPA的事实标准一样~

值得一提的是:RESTEasy是由JBoss公司开发的,所以将用RESTEasy框架实现的应用部署到JBoss服务器上,可以实现很多额外的功能(但很显然,JBoss已经退出了历史舞台)。


Jersey

Jersey是一个REST框架,既然是REST框架,那自然提供了REST服务相关的一切东西。因此在使用过程中,你可以同Spring MVC做对比,部署到Servlet容器上即可运行,形如这样:

@Path("/api/v1/user")
public class UserResource{

    @GET
    @Path("/{username}")
    @Consumes({"application/json", "application/xml"})
    @Produces("application/json")
    public String getUser(@PathParam("username") String username){
        ...
    }
}

作为服务端,它使用的库是:

1.x:
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-servlet</artifactId>
    <version>1.19.4</version>
</dependency>

2.x:
<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet</artifactId>
    <version>2.30.1</version>
</dependency>

1.x和2.x的区别

1.x在2017年5月发布其最后一个版本1.19.4后就已经寿终正寝了,因此不建议再使用。2.x从2013年发布迭代至今,是现在推荐的使用方式(可见它俩重叠开发了好几年)。

1.x和2.x版本互不兼容,核心API均出现了一定的差异性,举例如下:

  • 实现规范
    • 1.x:实现的JAX-RS 1.0规范,也就是JSR 311
    • 2.x:实现的JAX-RS 2.0规范,也就是JSR 339
  • Servlet容器全类名
    • 1.x:com.sun.jersey.spi.container.servlet.ServletContainer(sun公司)
    • 2.x: org.glassfish.jersey.servlet.ServletContainer(glassfish公司)
  • 资源扫描
    • 1.x:com.sun.jersey.config.property.packages
    • 2.x:jersey.config.server.provider.packages
  • 注解支持
    • 1.x:不支持Servet3.x的注解
    • 2.x:支持注解如@WebServlet来扫描jersey的资源

说明:glassfish是一款web应用服务器,和tomcat一样,也是一款优秀的Servlet容器。它既是EJB容器也是WEB容器,由Sun公司开发(现Oracle赞助)。


jersey-client

以上大体介绍了jersey作为Server端技术的实施,接下来介绍其客户端API,这便是jersey-client工程。Jersey的客户端API能够让我们非常方便的创建出REST的Web服务客户端,不管是客户端应用,还是用于测试的代码,都是非常容易和舒服的。

特别说明:本文讲解、实例使用的jersey-client版本是1.x版本,1.x版本,1.x版本

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-client</artifactId>
    <version>1.19.4</version>
</dependency>

它的jar包依赖情况如下:

在这里插入图片描述

使用示例

@Test
public void fun1() {
    // 1、创建一个Client
    DefaultClientConfig clientConfig = new DefaultClientConfig();
    Client client = Client.create(clientConfig);

    // 2、准备一个WebResource,等待发送请求(注意:http前缀不能省)
    // WebResource webResource = client.resource( URI.create("www.baidu.com"));
    WebResource resource = client.resource("http://www.baidu.com");

    // 3、发送get/post请求获取资源
    // String result = resource.get(String.class);
    // System.out.println(result);

    // 若你想获取响应详情,可以使用ClientResponse
    ClientResponse response = resource.get(ClientResponse.class);
    System.out.println(response.getStatus());
    System.out.println(response.getHeaders());
    System.out.println(response.getLocation());
    System.out.println(response.getEntity(String.class));
}

运行程序,控制台打印:

200
{Server=[bfe], Content-Length=[2381], Date=[Sat, 14 Mar 2020 09:55:47 GMT], Content-Type=[text/html]}
null
<!DOCTYPE html> ... // 百度首页的html,略

说明:Client的构建属于昂贵资源,因此请重复使用它,它底层使用的java.net.HttpURLConnection进行请求发送的


jersey-client vs HttpClient

在Java中,REST Client实现方式有多种,比如JBoss RestEasy、 Sun Jersey、Dropwizard、Apache HTTPClient、OkHttp等等。很多人直接使用Apache Http Client, 我并不推荐直接使用这个库,主要是因为这个库相对比较底层,需要自己处理的东西很多,,API也相对繁琐。

另外,对于JDK源生的URLConnectionApache HTTPClient附上一个对比图:
在这里插入图片描述
总体上HttpClient比HttpURLConnection功能更加丰富且好用,但是更加占用内存和CPU资源,大家都知道!当然,若你在Spring环境下需要使用Rest Client,那就用RestTemplate吧~

说明:jersey社区贡献了一个项目com.sun.jersey.contribs:jersey-apache-client4,它是基于Apache的HC发送请求的,具有更好的效率,使用得也是比较广泛的


总结

本文介绍了JAX-RS标准JavaEE技术,并且对JSR 311/JSR 339等做了一个简单的科普,示例了jersey-client的使用介绍。个人觉得过于国内程序员来说JAX-RS技术(jersey的使用)不用太过于深究,浅尝辄止即可。

分隔线

声明

原创不易,码字不易,多谢你的点赞、收藏、关注。把本文分享到你的朋友圈是被允许的,但拒绝抄袭。你也可【左边扫码/或加wx:fsx641385712】邀请你加入我的 Java高工、架构师 系列群大家庭学习和交流。
往期精选

发布了377 篇原创文章 · 获赞 572 · 访问量 51万+
App 阅读领勋章
微信扫码 下载APP
阅读全文

使用cxf开发restful的时候遇到的问题

01-04

在网页中输入http://localhost:8080/student-B/services/student/delete/6的时候 Tomcat报错 ’![图片说明](https://img-ask.csdn.net/upload/201701/04/1483510209_957885.png) 一月 04, 2017 1:59:26 下午 org.apache.cxf.jaxrs.utils.JAXRSUtils findTargetMethod 警告: No operation matching request path "/student-B/services/student/delete/6" is found, Relative Path: /delete/6, HTTP Method: GET, ContentType: */*, Accept: text/html,application/xhtml+xml,image/webp,application/xml;q=0.9,*/*;q=0.8,. Please enable FINE/TRACE log level for more details. 一月 04, 2017 1:59:26 下午 org.apache.cxf.jaxrs.impl.WebApplicationExceptionMapper toResponse 警告: javax.ws.rs.ClientErrorException: HTTP 405 Method Not Allowed at org.apache.cxf.jaxrs.utils.SpecExceptions.toHttpException(SpecExceptions.java:117) at org.apache.cxf.jaxrs.utils.ExceptionUtils.toHttpException(ExceptionUtils.java:166) at org.apache.cxf.jaxrs.utils.JAXRSUtils.findTargetMethod(JAXRSUtils.java:529) at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.processRequest(JAXRSInInterceptor.java:177) at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.handleMessage(JAXRSInInterceptor.java:77) at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:307) at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121) at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:251) at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:234) at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:208) at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:160) at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:171) at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:293) at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doGet(AbstractHTTPServlet.java:217) at javax.servlet.http.HttpServlet.service(HttpServlet.java:624) at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:268) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:442) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1082) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:623) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745) 问答

JaxWsDynamicClientFactory cxf动态客户端

08-04

public class PolicyConfirmTest { public static void main(String[] args) { JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance(); org.apache.cxf.endpoint.Client client = dcf.createClient("http://120.55.174.144:7207/PolicyConfirmService?wsdl"); String requestXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><reqData><policyNo>CA7617F514717D3F8D0FA7285C88FCAE1E7FABAE3CE6703F044B381A25B1219F</policyNo><queryFlag>B791A9C34230B50505C06A3F09D596DA</queryFlag><insuredFlag>B791A9C34230B50505C06A3F09D596DA</insuredFlag><idType>D7FCE62A70D9A0AB92893983BB19F7F2</idType><customerId>73C346CCCA776AADB8F87783C97B2BC3</customerId><verifyCode>6F3188D3ADB1C3E2A5D8FD18CA7881CCC83D971FA249A222AF59F2A772387504054E9335FB325F5F76F87593854BA65DABC95190BE91C8DF43C1093C6D76BC6F</verifyCode></reqData>"; QName name=new QName("http://service.policyconfirm.apps.gateway.sinosoft.com/","policyConfirmRequest"); try { Object[] objects = client.invoke(name,requestXML); System.out.println(objects[0]); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 用JaxWsDynamicClientFactory.newInstance() ,client.invoke(name,requestXML)时服务器端收到的请求信息为空。 但是用JaxWsDynamicClientFactory的父类DynamicClientFactory.newInstance(),client.invoke(name,requestXML)时服务器端就能正常收到请求信息。 public static void main(String[] args) { DynamicClientFactory dcf = DynamicClientFactory.newInstance(); org.apache.cxf.endpoint.Client client = dcf.createClient("http://120.55.174.144:7207/PolicyConfirmService?wsdl"); String requestXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><reqData><policyNo>CA7617F514717D3F8D0FA7285C88FCAE1E7FABAE3CE6703F044B381A25B1219F</policyNo><queryFlag>B791A9C34230B50505C06A3F09D596DA</queryFlag><insuredFlag>B791A9C34230B50505C06A3F09D596DA</insuredFlag><idType>D7FCE62A70D9A0AB92893983BB19F7F2</idType><customerId>73C346CCCA776AADB8F87783C97B2BC3</customerId><verifyCode>6F3188D3ADB1C3E2A5D8FD18CA7881CCC83D971FA249A222AF59F2A772387504054E9335FB325F5F76F87593854BA65DABC95190BE91C8DF43C1093C6D76BC6F</verifyCode></reqData>"; QName name=new QName("http://service.policyconfirm.apps.gateway.sinosoft.com/","policyConfirmRequest"); try { Object[] objects = client.invoke(name,requestXML); System.out.println(objects[0]); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } 帮帮小弟看下是什么原因导致的。 问答

cxf2.7.0做RestFul时启动一直出问题

03-11

<div class="iteye-blog-content-contain" style="font-size: 14px;"> <p>最近使用cxf2.7.0做一个简单的restful例子,郁闷一直都在启动时出错,检查配置没发现有什么问题,大家帮忙看一下。</p> <p> </p> <p>出现的错误如下:</p> <pre name="code" class="xml">2013-3-11 15:25:33 org.apache.catalina.core.AprLifecycleListener init 信息: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: D:\Program Files\Java\jdk1.6.0_12\bin;D:\GXMCC\tools\tomcat7\bin 2013-3-11 15:25:33 org.apache.coyote.AbstractProtocolHandler init 信息: Initializing ProtocolHandler ["http-bio-9999"] 2013-3-11 15:25:33 org.apache.coyote.AbstractProtocolHandler init 信息: Initializing ProtocolHandler ["ajp-bio-8009"] 2013-3-11 15:25:33 org.apache.catalina.startup.Catalina load 信息: Initialization processed in 921 ms 2013-3-11 15:25:33 org.apache.catalina.core.StandardService startInternal 信息: Starting service Catalina 2013-3-11 15:25:33 org.apache.catalina.core.StandardEngine startInternal 信息: Starting Servlet Engine: Apache Tomcat/7.0.10 2013-3-11 15:25:33 org.apache.catalina.startup.HostConfig deployDirectory 信息: Deploying web application directory cxf 2013-3-11 15:25:34 org.apache.catalina.loader.WebappClassLoader validateJarFile 信息: validateJarFile(D:\GXMCC\tools\tomcat7\webapps\cxf\WEB-INF\lib\geronimo-servlet_3.0_spec-1.0.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class 2013-3-11 15:25:36 org.apache.catalina.core.ApplicationContext log 信息: Initializing Spring root WebApplicationContext 2013-3-11 15:25:36 org.springframework.web.context.ContextLoader initWebApplicationContext 信息: Root WebApplicationContext: initialization started 2013-3-11 15:25:36 org.springframework.context.support.AbstractApplicationContext prepareRefresh 信息: Refreshing Root WebApplicationContext: startup date [Mon Mar 11 15:25:36 CST 2013]; root of context hierarchy 2013-3-11 15:25:37 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions 信息: Loading XML bean definitions from class path resource [spring/applicationContext.xml] 2013-3-11 15:25:37 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions 信息: Loading XML bean definitions from class path resource [spring/integrationContext.xml] 2013-3-11 15:25:37 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions 信息: Loading XML bean definitions from class path resource [META-INF/cxf/cxf.xml] 2013-3-11 15:25:37 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions 信息: Loading XML bean definitions from class path resource [META-INF/cxf/cxf-extension-soap.xml] 2013-3-11 15:25:37 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions 信息: Loading XML bean definitions from class path resource [META-INF/cxf/cxf-servlet.xml] 2013-3-11 15:25:38 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons 信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@17e9134: defining beans [cxf,org.apache.cxf.bus.spring.BusWiringBeanFactoryPostProcessor,org.apache.cxf.bus.spring.Jsr250BeanPostProcessor,org.apache.cxf.bus.spring.BusExtensionPostProcessor,org.apache.cxf.binding.soap.SoapBindingFactory,org.apache.cxf.binding.soap.SoapTransportFactory,org.apache.cxf.binding.soap.customEditorConfigurer,userRS,userRsImpl]; root of factory hierarchy 2013-3-11 15:25:39 org.apache.cxf.bus.spring.OldSpringSupport logWarning 警告: Import of META-INF/cxf/cxf-extension-soap.xml has been deprecated and is unnecessary. UserRS constructor 2013-3-11 15:25:40 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons 信息: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@17e9134: defining beans [cxf,org.apache.cxf.bus.spring.BusWiringBeanFactoryPostProcessor,org.apache.cxf.bus.spring.Jsr250BeanPostProcessor,org.apache.cxf.bus.spring.BusExtensionPostProcessor,org.apache.cxf.binding.soap.SoapBindingFactory,org.apache.cxf.binding.soap.SoapTransportFactory,org.apache.cxf.binding.soap.customEditorConfigurer,userRS,userRsImpl]; root of factory hierarchy 2013-3-11 15:25:40 org.springframework.web.context.ContextLoader initWebApplicationContext 严重: Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRS': Invocation of init method failed; nested exception is org.apache.cxf.service.factory.ServiceConstructionException at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1422) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:518) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:455) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:282) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:204) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4651) at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5154) at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5149) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303) at java.util.concurrent.FutureTask.run(FutureTask.java:138) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:619) Caused by: org.apache.cxf.service.factory.ServiceConstructionException at org.apache.cxf.jaxrs.JAXRSServerFactoryBean.create(JAXRSServerFactoryBean.java:201) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeCustomInitMethod(AbstractAutowireCapableBeanFactory.java:1546) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1487) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1419) ... 20 more Caused by: java.lang.RuntimeException: Resource class interface com.sky.oa.cxf.service.IUserRS has no valid constructor at org.apache.cxf.jaxrs.lifecycle.PerRequestResourceProvider.<init>(PerRequestResourceProvider.java:45) at org.apache.cxf.jaxrs.JAXRSServerFactoryBean.updateClassResourceProviders(JAXRSServerFactoryBean.java:387) at org.apache.cxf.jaxrs.JAXRSServerFactoryBean.create(JAXRSServerFactoryBean.java:151) ... 27 more 2013-3-11 15:25:40 org.apache.catalina.core.StandardContext listenerStart 严重: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRS': Invocation of init method failed; nested exception is org.apache.cxf.service.factory.ServiceConstructionException at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1422) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:518) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:455) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:282) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:204) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4651) at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5154) at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5149) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303) at java.util.concurrent.FutureTask.run(FutureTask.java:138) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:619) Caused by: org.apache.cxf.service.factory.ServiceConstructionException at org.apache.cxf.jaxrs.JAXRSServerFactoryBean.create(JAXRSServerFactoryBean.java:201) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeCustomInitMethod(AbstractAutowireCapableBeanFactory.java:1546) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1487) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1419) ... 20 more Caused by: java.lang.RuntimeException: Resource class interface com.sky.oa.cxf.service.IUserRS has no valid constructor at org.apache.cxf.jaxrs.lifecycle.PerRequestResourceProvider.<init>(PerRequestResourceProvider.java:45) at org.apache.cxf.jaxrs.JAXRSServerFactoryBean.updateClassResourceProviders(JAXRSServerFactoryBean.java:387) at org.apache.cxf.jaxrs.JAXRSServerFactoryBean.create(JAXRSServerFactoryBean.java:151) ... 27 more 2013-3-11 15:25:40 org.apache.catalina.core.StandardContext startInternal 严重: Error listenerStart 2013-3-11 15:25:40 org.apache.catalina.core.StandardContext startInternal 严重: Context [/cxf] startup failed due to previous errors 2013-3-11 15:25:41 org.apache.catalina.core.ApplicationContext log 信息: Closing Spring root WebApplicationContext 2013-3-11 15:25:41 org.apache.catalina.startup.HostConfig deployDirectory 信息: Deploying web application directory docs 2013-3-11 15:25:41 org.apache.catalina.startup.HostConfig deployDirectory 信息: Deploying web application directory examples 2013-3-11 15:25:41 org.apache.catalina.core.ApplicationContext log 信息: ContextListener: contextInitialized() 2013-3-11 15:25:41 org.apache.catalina.core.ApplicationContext log 信息: SessionListener: contextInitialized() 2013-3-11 15:25:41 org.apache.catalina.startup.HostConfig deployDirectory 信息: Deploying web application directory host-manager 2013-3-11 15:25:41 org.apache.catalina.startup.HostConfig deployDirectory 信息: Deploying web application directory manager 2013-3-11 15:25:41 org.apache.catalina.startup.HostConfig deployDirectory 信息: Deploying web application directory Root 2013-3-11 15:25:41 org.apache.coyote.AbstractProtocolHandler start 信息: Starting ProtocolHandler ["http-bio-9999"] 2013-3-11 15:25:41 org.apache.coyote.AbstractProtocolHandler start 信息: Starting ProtocolHandler ["ajp-bio-8009"] 2013-3-11 15:25:41 org.apache.catalina.startup.Catalina start 信息: Server startup in 8064 ms </pre> <p> </p> <p>配置文件如下:</p> <p>Jar是从cxf2.7.0的lib中直接复制出来的,没有添加其他任何jar。</p> <p> </p> <p>web.xml</p> <pre name="code" class="xml"><?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>CXFServlet</servlet-name> <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>CXFServlet</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> <!-- 加载spring配置文件,文件路径设置在contextConfigLocation参数中 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/spring/applicationContext.xml</param-value> </context-param> <!-- 字符过滤器 --> <filter> <filter-name>encoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>*.json</url-pattern> </filter-mapping> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping> </web-app></pre> <p> </p> <p>applicationContext.xml</p> <pre name="code" class="java"><?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:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd" default-autowire="byName"> <import resource="classpath:/spring/integrationContext.xml" ></import> </beans></pre> <p> </p> <p>integrationContext.xml</p> <pre name="code" class="xml"><?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.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"> <description>Apache CXF的Web Service配置</description> <import resource="classpath:META-INF/cxf/cxf.xml" /> <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" /> <import resource="classpath:META-INF/cxf/cxf-servlet.xml" /> <jaxrs:server id="userRS" serviceClass="com.sky.oa.cxf.service.IUserRS" address="/userRSCXF"> <jaxrs:serviceBeans> <ref bean="userRsImpl"/> </jaxrs:serviceBeans> <jaxrs:extensionMappings> <entry key="json" value="application/json"></entry> <entry key="xml" value="application/xml" /> </jaxrs:extensionMappings> </jaxrs:server> <bean id="userRsImpl" class="com.sky.oa.cxf.service.UserRS"></bean> </beans> </pre> <p> </p> <p>IUserRS</p> <pre name="code" class="java">package com.sky.oa.cxf.service; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebService; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @WebService @Path("/users/") @Produces(MediaType.APPLICATION_JSON) public interface IUserRS { @WebMethod @GET @Path("/user/{userId}") public String getUser(@WebParam(name = "userId")String userId); } </pre> <p> </p> <p>UserRS</p> <pre name="code" class="java">package com.sky.oa.cxf.service; import javax.jws.WebService; @WebService public class UserRS implements IUserRS { public String getUser(String userId){ System.out.println("----------"); System.out.println(" return xixihaha"); return "xixihaha"; } } </pre> <p> </p> <p> </p> <p> </p> </div> 问答

cxf webservice客户端调用报错.高手请进.

10-24

<!-- WebServices设置 --> <servlet> <servlet-name>CXFServices</servlet-name> <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>CXFServices</servlet-name> <url-pattern>rvices/*</url-pattern> </servlet-mapping> 客户端调用异常信息 org.apache.catalina.core.StandardWrapperValve invoke 严重: Servlet.service() for servlet CXFServices threw exception java.lang.ClassNotFoundException: javax.mail.MessagingException at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1387) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1233) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320) at org.apache.cxf.interceptor.AttachmentInInterceptor.handleMessage(AttachmentInInterceptor.java:62) at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:262) at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:122) at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:211) at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:213) at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:193) at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:129) at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:187) at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doPost(AbstractHTTPServlet.java:110) at javax.servlet.http.HttpServlet.service(HttpServlet.java:637) at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:166) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454) at java.lang.Thread.run(Thread.java:619) 接口如下 @WebService public interface CmisWeb { public FamilyMemberResult findFamilyMembers(WsUser wSUser, FamilyMemberSearchDTO search); } 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: Age of Ai 设计师: meimeiellie

分享到微信朋友圈

×

扫一扫,手机浏览