WebService, CXF Framework (JAX-WS, JAX-RS, Integration with Spring)

Reprinted:http://blog.csdn.net/opopopwqwqwq/article/details/51763570

1 comment on webservice

1.1 Case:

Simulate the weather query Information, return the weather conditions for three days.

1.1.1 Implementation steps

Server:

The first step : Create a weather information pojo, including weather information, maximum and minimum temperature, and date.

Step 2: Write SEI

Step 3: Write SEI implementation class and return to the weather list

Step 4: Publish Webservice.

1.1.2 Code implementation

1.1.2.1 Pojo

[java] view plain copy

  1. publicclassWeatherModel{
  2. privateStringinfo;
  3. privateintmaxTemp;
  4. privateintminTemp; ​< /span>
  5. privateDate date;

1.1.2.2 SEI

Weather query SEI, return three-day weather conditions

[java] view plain copy

  1. @WebService
  2. publicinterfaceWeatherInterface{
  3. List queryWeather(String cityName);
  4. }



1.1.2.3 SEI implementation class

The implementation class uses @WebService to modify the name of the wsdl document element

[java] view plain copy

  1. @WebService(
  2. //endpointInterface=”com.itheima.weather.service.WeatherInterface” // SEI interface can be specified
  3. name=“WeatherInterface”,//standard portType when not using SEI interface Name
  4. serviceName=“WeatherService”,//The name of the service view
  5. PortName=“WeatherPort”,//The name attribute of the port node in the Service node span>
  6. TargetNamespace=“http://weather.itheima.com/”//wsdl namespace
  7. )
  8. < span style="margin:0px; padding:0px; border:none; color:black; background-color:inherit">publicclass< span style="margin:0px; padding:0px; border:none; background-color:inherit">WeatherInterfaceImplimplementsWeatherInterface{
  9. @Override
  10. @WebMethod/*(exclude=true)*/
  11. @WebResult(name= “WeatherInfo”)
  12. publicList queryWeather(@WebParam(name=“cityName”)String cityName){
  13. System.out.println(“City sent by client:”+cityName);
  14. //Query weather information /span>
  15. Listinfo=getWeatherInfo(cityName);
  16. //Return to weather information
  17. returninfo;
  18. }
  19. privateListgetWeatherInfo(StringcityName) {
  20. List weatherList=newArrayList<>();
  21. Calendar Calendar = Calendar.getInstance(); /span>
  22. //The first day
  23. WeatherModel model1 = newWeatherModel();
  24. Model1.setInfo(“雷阵雨”);
  25. model1. setMaxTemp(31);  
  26.         model1.setMinTemp(22);  
  27.         model1.setDate(calendar.getTime());  
  28.         weatherList.add(model1);  
  29.         //第二天  
  30.         WeatherModel model2 = new WeatherModel();  
  31.         model2.setInfo(“多云”);  
  32.         model2.setMaxTemp(33);  
  33.         model2.setMinTemp(25);  
  34.         calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + 1);  
  35.         model2.setDate(calendar.getTime());  
  36.         weatherList.add(model2);  
  37.         //第三天  
  38.         WeatherModel model3 = new WeatherModel();  
  39.         model3.setInfo(“多云”);  
  40.         model3.setMaxTemp(35);  
  41.         model3.setMinTemp(25);  
  42.         calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + 1);  
  43.         model3.setDate(calendar.getTime());  
  44.         weatherList.add(model3);  
  45.           
  46.         return weatherList;  
  47.     }  
  48.   
  49. }  



1.1.2.4    客户端

[java]  view plain  copy

  1. public class WeatherClient {  
  2.   
  3.     public static void main(String[] args) throws Exception {  
  4.         //创建服务视图  
  5.         Service service = Service.create(new URL(“http://127.0.0.1:12345/weather”),   
  6.                 new QName(“http://service.weather.itheima.com/”“WeatherInterfaceImplService”));  
  7.         //从服务视图获得protType对象  
  8.         WeatherInterfaceImpl weatherInterfaceImpl = service.getPort(WeatherInterfaceImpl.class);  
  9.         //调用服务端方法  
  10.         List list = weatherInterfaceImpl.queryWeather(“北京”);  
  11.         //显示天气信息  
  12.         for (WeatherModel weatherModel : list) {  
  13.             System.out.println(weatherModel.getDate().toGregorianCalendar().getTime().toLocaleString());  
  14.             System.out.println(weatherModel.getInfo());  
  15.             System.out.println(weatherModel.getMaxTemp());  
  16.             System.out.println(weatherModel.getMinTemp());  
  17.               
  18.         }  
  19.     }  
  20. }  



 

1.2   要规范wsdl需要使用到webservice注解


1.2.1       @Webservice

@WebService(

              //endpointInterface=”com.itheima.weather.service.WeatherInterface”//可以指定SEI接口

              name=”WeatherInterface”,//不使用SEI接口时规范portType的名称

              serviceName=”WeatherService”,   //服务视图的名称

              portName=”WeatherPort”,                   //Service节点中port节点的name属性

              targetNamespace=”http://weather.itheima.com/”   //wsdl的命名空间

                     )

 

 

1.2.2       @WebMethod

如果不指定@WebMethod注解默认是吧实现类中所有的public方法都发布成服务方法。

如果类中有的public方法不想发布成服务,就可以使用@WebMethod(exclude=true)把此方法排除,也就是不发布为webservice方法。

 

注意:每个Porttype中,必须有一个public方法并且不能标注为@WebMethod(exclude=true)

 

1.2.3       @WebParam、@WebResult

可以规范参数的名称

@WebResult(name=”xxxx”)修改返回值的元素的父标签名字

@WebParam(name=”xxxxx”)修改传入参数的元素的父标签名字

 

2     CXF框架

2.1   什么是CXF

Apache CXF = Celtix + Xfire,开始叫 Apache CeltiXfire,后来更名为 Apache CXF 了,以下简称为 CXF。 Apache CXF 

是一个开源的 web Services 框架,CXF 帮助您构建和开发 web Services ,它支持多种协议,比如:SOAP1.1,1,2、XML/HTTP、RESTful  或者 CORBA。

RESTful:一种风格而不是一个协议。它理念是网络上的所有事物都被抽象为资源,每个资源对应一个唯一的资源标识符。

CORBA(Common Object Request Broker Architecture公共对象请求代理体系结构,早期语言使用的WS。C,c++,C#)

Cxf是基于SOA总线结构,依靠spring完成模块的集成,实现SOA方式。

灵活的部署:可以运行在Tomcat,Jboss,Jetty(内置),weblogic上面。

 

2.2   CXF的安装及配置

从官网下载:cxf.apache.org

学习使用的版本是:3.0.2

 

使用的方法,直接把cxf的jar包添加到工程中就可以了。

 

环境配置

JAVA_HOME 需要jdk的支持

CXF_HOME  解压目录(bin的上层目录) 需要使用bin目录的可执行命令生成客户端代码

 

path = %JAVA_HOME%in;%CXF_HOME%in;

 

 

 

2.3   使用CXF实现java-ws规范的webservice

Soap1.1:

2.3.1       服务端

实现步骤:

第一步:创建一Java工程。

第二步:导入jar包导入cxf的jar包共138个。

第三步:编写SEI,在SEI上添加@Webservice注解。

第三步:编写SEI实现类。需要实现SEI接口,可以不加@Webservice注解

第四步:发布服务。

1、创建一个JaxWsServerFactoryBean对象。

2、设置服务的发布地址,是一个http url

3、设置SEI接口

4、设置SEI实现类对象

5、调用create方法发布服务。

2.3.2       代码实现

2.3.2.1    SEI

[java]  view plain  copy

  1. @WebService  
  2. public interface WeatherInterface {  
  3.   
  4.     String queryWeather(String cityName);  
  5. }  



2.3.2.2    实现类

[java]  view plain  copy

  1. public class WeatherInterfaceImpl implements WeatherInterface {  
  2.   
  3.     @Override  
  4.     public String queryWeather(String cityName) {  
  5.           
  6.         System.out.println(“城市名称:” + cityName);  
  7.         String result = “多云”;  
  8.           
  9.         return result;  
  10.     }  
  11. }  



2.3.3       发布服务

服务发布类:后面整合spring按照此步骤配置即可

[java]  view plain  copy

  1. public class WeatherServer {  
  2.   
  3.     public static void main(String[] args) {  
  4.         //创建一个JaxWsServerFactoryBean对象  
  5.         JaxWsServerFactoryBean factoryBean = new JaxWsServerFactoryBean();  
  6.         //设置服务发布的地址  
  7.         factoryBean.setAddress(“http://127.0.0.1:12345/weather”);  
  8.         //设置SEI  
  9.         factoryBean.setServiceClass(WeatherInterface.class);  
  10.         //设置实现类对象  < /li>
  11.         factoryBean.setServiceBean(new WeatherInterfaceImpl());  
  12.         //发布服务  
  13.         factoryBean.create();  
  14.     }  
  15. }  



 

2.4   客户端

2.4.1       Wsdl2java

可以使用wsimport生成客户端调用代码,也可以使用CXF自带的工具生成。 Wsdl2java。

可以实现wsimport同样的功能,两个工具生成的代码都是一样,wsdl2java工具的版本高。 Wsimport对soap1.2支持的不好。

它包含以下参数:

a) -d参数,指定代码生成的目录。

b) -p参数,指定生成的新的包结构。

例:

在命令行执行

wsdl2java –d . -p cn.test.cxftext http://127.0.0.1:6666/helloworld?wsdl

 

2.4.2       客户端的代码实现

2.4.2.1    实现步骤


1、可以直接使用生成的代码调用服务端方法。

2、使用CXF提供的工厂类调用。

第一步:创建JaxWsProxyFactoryBean对象

第二步:设置服务的url,服务端地址

第三步:设置SEI(portType)类型

第四步:调用Create方法获得portType对象。

第五步:调用服务端方法。

 

2.4.2.2    代码实现

使用CXF工厂调用webservice,后面与spring整合配置可以用来参考

[ java]  view plain  copy

  1. public class WeatherClient {  
  2.   
  3.     public static void main(String[] args) {  
  4.         //创建一个JaxWsProxyFactoryBean对象  
  5.         JaxWsProxyFactoryBean factoryBean = new JaxWsProxyFactoryBean();  
  6.         //设置服务的url  
  7.         factoryBean.setAddress(“http://127.0.0.1:12345/weather?wsdl”);  
  8.         //设置SEI的类型  
  9.         factoryBean.setServiceClass(WeatherInterface.class);  
  10.         //获得porttype对象  
  11.         WeatherInterface portType = (WeatherInterface) factoryBean.create();  
  12.         //调用服务端方法  
  13.         String result = portType.queryWeather(“北京”);  
  14.         System.out.println(result);  
  15.     }  
  16. }  



2.5   Jax-rs规范的webservice


2.5.1       什么是rest服务


一句话解释:URL定位资源,用HTTP动词(GET,POST,DELETE,DETC)描述操作。

简单来讲,就是可以用httprequest 调用某个function. 比如在浏览器里输入www.chx.site/api/guesswhoisawesome,就会调用后台的某个function得到一个response(可以是Json).

REST 是一种软件架构风格,设计风格而不是标准,只是提供了一组设计原则和约束条件。

它主要用于客户端和服务器交互类的软件。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。

rest服务采用HTTP 做传输协议,REST 对于HTTP 的利用分为以下两种:资源定位资源操作

 

关于JAX-WS与JAX-RS:

两者是不同风格的SOA(面向服务的体系结构)架构。

前者以动词为中心,指定的是每次执行函数。

而后者以名词为中心,每次执行的时候指的是资源。

 

    资源定位

Rest要求对资源定位更加准确,如下:

非rest方式:http://ip:port/queryUser.action?userType=student&id=001

Rest方式:http://ip:port/user/student/001

Rest方式表示互联网上的资源更加准确,但是也有缺点,可能目录的层级较多不容易理解。

    资源操作

利用HTTP 的GET、POST、PUT、DELETE 四种操作来表示数据库操作的SELECT、UPDATE、INSERT、DELETE 操作。

比如:

查询学生方法:

设置Http的请求方法为GET,url如下:

http://ip:port/user/student/001

添加学生方法:

设置http的请求方法为PUT,url如下:

http://ip:port/user/student/001/张三/……

 

Rest常用于资源定位,资源操作方式较少使用。

REST 是一种软件架构理念,现在被移植到Web 服务上,那么在开发Web 服务上,

偏于面向资源的服务适用于REST,REST 简单易用,效率高,

SOAP 成熟度较高,安全性较好。

注意:REST 不是WebService,JAX-RS 只是将REST 设计风格应用到Web 服务开发上。

 

代码实现

2.5.2       服务端

2.5.2.1    实现步骤

第一步:创建一个pojo,返回值的类型。需要在pojo上添加@XmlRootElement。

第二步:创建一个SEI。也就是一个接口。需要用到的注解

1、@Path:标注请求url

2、@GET、@POST、@PUT、@DELETE:标注操作的方法

3、@Produce:指定返回结果的数据类型,xml或者json等。

第三步:创建SEI的实现类。可以不使用任何注解。

第四步:发布rest服务。

1、使用JAXRsServerFactoryBean对象发服务。

2、设置服务发布的地址。设置url

3、设置SEI实现类对象。

4、发布服务,create方法。

2.5.2.2    代码实现

2.5.2.2.1 Pojo

返回值pojo类需要添加一个@XmlRootElement注解

[java]  view plain  copy

  1. @XmlRootElement  
  2. public class WeatherModel {  
  3.   
  4.     private String info;  
  5.     private int maxTemp;  
  6.     private int minTemp;  
  7.     private Date date;  


 

2.5.2.2.2 SEI

rest服务SEI

[java]  view plain  copy

  1. //窄化请求映射  
  2. @Path(“/weather”)  
  3. public interface WeatherInterface {  
  4.     //方法的请求路径{}中的内容就是参数,需要对应的使用@PathParam注解取参数  
  5.     @Path(“/city/{cityName}”)  
  6.     //请求的方法  
  7.     @GET  
  8.     //返回结果的数据类型,可以是xml也可以是json  
  9.     @Produces({MediaType.APPLICATION_JSON+“;charset=utf-8”, MediaType.APPLICATION_XML})  
  10.     List queryWeather(@PathParam(value=“cityName”)String cityName);  
  11. }  


 

2.5.2.2.3 SEI实现类

[java]  view plain  copy

  1. public class WeatherInterfaceImpl implements WeatherInterface{  
  2.   
  3.     @Override  
  4.     public List queryWeather(String cityName) {  
  5.           
  6.         List weatherInfo = getWeatherInfo(cityName);  
  7.           
  8.         return weatherInfo;  
  9.     }  
  10. …  



 

2.5.2.2.4 发布服务

使用执行命令生成相应的代码后

[java]  view plain  copy

  1. public class WeatherServer {  
  2.   
  3.     public static void main(String[] args) {  
  4.         //创建一个JAXRSServerFactoryBean对象  
  5.         JAXRSServerFactoryBean factoryBean = new JAXRSServerFactoryBean();  
  6.         //设置服务发布的地址  
  7.         factoryBean.setAddress(“http://127.0.0.1:12345/rest”);  
  8.         //设置实现类对象  
  9.         factoryBean.setServiceBean(new WeatherInterfaceImpl());  
  10.         //发布服务  
  11.         factoryBean.create();         
  12.     }  
  13. }  



 

2.5.3       查看结果

http://127.0.0.1:12345/rest/weather/city/上海

 

2.5.4       如果是多个参数可以使用

 

 

2.5.5       结果数据格式

2.5.5.1    Json

@Produces({MediaType.APPLICATION_JSON+”;charset=utf-8″, MediaType.APPLICATION_XML})

其中charset=utf-8 为了防止出现乱码


2.5.6       同一个方法返回两种数据类型

支持xml或者json数据格式

MediaType.APPLICATION_JSON

MediaType.APPLICATION_XML

默认返回xml格式的数据

 

如果想访问json格式的数据需要加参数:?_type=json

http://127.0.0.1:12345/rest/weather/city/%E4%B8%8A%E6%B5%B7?_type=json

 

2.5.7       客户端

可以使用ajax请求json数据。还可以使用HttpClient访问数据。需要自己转换成java对象。

 

 

3     CXF整合spring


3.1   整合的思路

Spring就是一个容器,服务端让spring容器实现服务的发布。客户端使用spring容器完成获得porttype的过程,直接从spring容器中获得一个porttype对象。

 

3.2   案例需求

服务端发布手机号查询服务供客户端调用,服务端配置调用公网手机号查询服务客户端,调用公网WebService查询手机号。

 

3.3   分析

 

  

 

3.4   实现步骤

服务端:有两个身份,一个是调用公网webservice的客户端。一个是对外提供手机号查询服务的服务端。

 

第一步:实现调用公网webservice的客户端

1、根据公网webservice的wsdl生成客户端调用代码

2、配置spring容器,完成创建服务视图获得porttype的过程。直接从spring容器中获得prottype对象。

3、直接调用porttype对象的服务端方法,查询手机号。

 

第二步:对外发布服务,实现手机号查询。

1、编写一个SEI接口。需要在SEI上添加@Webservice注解。

2、编写一个SEI实现类,调用公网webservice的porttype实现手机号查询。

3、发布服务,使用spring容器完成。

 

3.5   开发环境的搭建

第一步:创建一个Web工程

第二步:导入jar包。 需要spring的jar包和cxf的jar包

 

3.6   代码实现

3.6.1       服务端

3.6.1.1    生成调用公网webservice的客户端调用代码 

3.6.1.2    在spring容器中配置porttype

applicationContext.xml

[html]  view plain  copy

  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.     xmlns:cxf=“http://cxf.apache.org/core”  
  7.     xsi:schemaLocation=”http://www.springframework.org/schema/beans   

  8.                             http://www.springframework.org/schema/beans/spring-beans.xsd  
  9.                             http://cxf.apache.org/jaxrs   
  10.                             http://cxf.apache.org/schemas/jaxrs.xsd  
  11.                             http://cxf.apache.org/jaxws   
  12.                             http://cxf.apache.org/schemas/jaxws.xsd  
  13.                             http://cxf.apache.org/core   
  14.                             http://cxf.apache.org/schemas/core.xsd”>  
  15.       
  16.       
  17.     <jaxws:client id=“mobileCodeWSSoap” address=“http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx”   
  18.             serviceClass=“cn.com.webxml.MobileCodeWSSoap”/>  
  19.       
  20.     <bean id=“mobileInterfaceImpl” class=“com.itheima.mobile.service.MobileInterfaceImpl”>  
  21.         <property name=“mobileCodeWSSoap” ref=“mobileCodeWS Soap”>property>  
  22.     bean>  
  23. beans>  

NoClassDefFoundError: org/apache/cxf/logging/FaultListener

解决方法:添加FaultListener。
[html]  view plain  copy

  1. <cxf:bus>  
  2.        <cxf:properties>  
  3.            <entry key=“org.apache.cxf.logging.FaultListener”>  
  4.                           
  5.                <bean class=“org.apache.cxf.logging.NoOpFaultListener”< span class="tag" style="color:rgb(153,51,0); margin:0px; padding:0px; border:none; background-color:inherit; font-weight:bold">/>  
  6.            entry>  
  7.        cxf:properties>  
  8.    cxf:bus>  

需要的xmlns和xsd

[html]  view plain  copy

  1. xmlns:cxf=”http://cxf.apache.org/core  
  2. http://cxf.apache.org/core  
  3. http://cxf.apache.org/schemas/core.xsd  


3.6.1.3    SEI

调用公网webservice查询手机号的SEI

[java]  view plain  copy

  1. @WebService  
  2. public interface MobileInterface {  
  3.   
  4.     Mobile queryMobile(String code);  
  5.       
  6. }  



 

3.6.1.4    SEI实现类

手机号归属地查询服务

[java]  view plain  copy

  1. public class MobileInterfaceImpl implements MobileInterface {  
  2.   
  3.     //公网webservice的porttype配置注入  
  4.     private MobileCodeWSSoap mobileCodeWSSoap;    
  5.     public void setMobileCodeWSSoap(MobileCodeWSSoap mobileCodeWSSoap) {  
  6.         this.mobileCodeWSSoap = mobileCodeWSSoap;  
  7.     }  
  8.   
  9.     @Override  
  10.     public Mobile queryMobile(String code) {  
  11.         //第一个参数:手机号  
  12.         //第二个参数:免费用户是空串  
  13.         String info = mobileCodeWSSoap.getMobileCodeInfo(code, “”);  
  14.         Mobile mobile = new Mobile();  
  15.         mobile.setAddress(info);  
  16.         mobile.setCode(code);  
  17.         return mobile;  
  18.     }  
  19. }  



 

3.6.1.5    发布服务

 

3.6.1.6    Web.xml

配置spring容器,配置cxf使用servlet。

web.xml

[html]  view plain  copy

  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” xmlns:web=“http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd”  
  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>B06_spring_cxfdisplay-name>  
  7.   
  8.     < span style="margin:0px; padding:0px; border:none; background-color:inherit">  
  9.       
  10.     <context-param>  
  11.         <param-name>contextConfigLocationparam-name>  
  12.         <param-value>classpath:applicationContext.xmlparam-value>  
  13.     context-param>  
  14.     <listener>  
  15.         <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>  
  16.     listener>  
  17.       
  18.       
  19.       
  20.       
  21.     <servlet>  
  22.         <servlet-name>cxfservlet-name>  
  23.         <servlet-class>org.apache.cxf.transport.servlet.CXFServletservlet-class>  
  24.           
  25.         <load-on-startup>1load-on-startup>  
  26.     servlet>  
  27.     <servlet-mapping>  
  28.         <servlet-name>cxfservlet-name>  
  29.         <url-pattern>/ws/*url-pattern>  
  30.     servlet-mapping>  
  31. web-app>  


applicationContext.xml发布自己的服务

[html]  view plain  copy

  1. xml version=“1.0” encoding=“UTF-8”?>  
  2. <be ans xmlns=“http://www.springframework.org/schema/beans”  
  3.     xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance” xmlns:jaxws=“http://cxf.apache.org/jaxws”  
  4.     xmlns:jaxrs=“http://cxf.apache.org/jaxrs” xmlns:cxf=“http://cxf.apache.org/core”  
  5.     xsi:schemaLocation=”http://www.springframework.org/schema/beans   
  6.                             http://www.springframework.org/schema/beans/spring-beans.xsd  
  7.                             http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd  
  8.                             http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd  
  9.                             http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd”>  
  10.       
  11.       
  12.     <jaxws:client id=“mobileCodeWSSoap” address=“http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx”   
  13.             serviceClass=“cn.com.webxml.MobileCodeWSSoap”/>  
  14.       
  15.     <bean id=“mobileInterfaceImpl” class=“com.itheima.mobile.service.MobileInterfaceImpl”>  
  16.         <property name=“mobileCodeWSSoap” ref=“mobileCodeWSSoap”>property>  
  17.     bean>  
  18.       
  19.       
  20.       
  21.     <jaxws:server address=“/mobile” serviceClass=“com.itheima.mobile.service.MobileInterface”>  
  22.         <jaxws:serviceBean>  
  23.             <ref bean=“mobileInterfaceImpl”/>  
  24.         jaxws:serviceBean>  
  25.     jaxws:server>  
  26.       
  27.       
  28.     <bean id=“mobileRestImpl” class=“com.itheima.mobile.rest.MobileRestImpl”>  
  29.         <property name=“mobileCodeWSSoap” ref=“mobileCodeWSSoap”>property>  
  30.     bean>  
  31.       
  32.     <jaxrs:server address=“/rest”>  
  33.         <jaxrs:serviceBeans>  
  34.             <ref bean=“mobileRestImpl”/>  
  35.         jaxrs:serviceBeans >  
  36.     jaxrs:server>  
  37.                             
  38. beans>  



 

3.6.1 .7    访问路径

http://localhost:8081/B06_spring_cxf/ws/mobile?wsdl

 

 

3.6.2       客户端

步骤:

1、生成客户端调用代码

2、创建服务视图

3、获得porttype

4、调用服务端方法

3.7   Spring整合cxf发布rest服务


3.7.1       实现步骤

第一步:调用公网webservice查询手机号,需要公网webservice的porttype。

第二步:发布rest服务

1、先写一个pojo,需要加上@xmlrootElement注解。

2、编写一个SEI,需要添加@path、@GET、@Produces

3、编写一个SEI实现类,需要调用公网的webservice查询手机号。

4、发布服务,使用spring容器发布服务。

 

3.7.2       代码实现

3.7.2.1    SEI

rest风格的服务

[java]  v iew plain  copy

  1. @Path(“/mobile”)  
  2. public interface MobileRest {  
  3.   
  4.     @Path(“/code/{code}”)  
  5.     @GET  
  6.     @Produces({MediaType.APPLICATION_JSON+“;charset=utf-8”, MediaType.APPLICATION_XML})  
  7.     Mobile queryMobile(@PathParam(value = “code”)String code);  
  8. }  



3.7.2.2    SEI实现类

[java]  view plain  copy

  1. public class MobileRestImpl implements MobileRest {  
  2.       
  3.     //公网webservice的porttype  
  4.     private MobileCodeWSSoap mobileCodeWSSoap;  
  5.       
  6.     public void setMobileCodeWSSoap(MobileCodeWSSoap mobileCodeWSSoap) {  
  7.         this.mobileCodeWSSoap = mobileCodeWSSoap;  
  8.     }   
  9.   
  10.     @Override  
  11.     public Mobile queryMobile(String code) {  
  12.         String address = mobileCodeWSSoap.getMobileCodeInfo(code, “”);  
  13.         Mobile mobile = new Mobile();  
  14.         mobile.setAddress(address);  
  15.         mobile.setCode(code);  
  16.           
  17.         return mobile;  
  18.     }  
  19.   
  20. }  



 

3.7.2.3    发布服务

[html]  view plain  copy

  1.   
  2. <bean id=“mobileRestImpl” class=“com.itheima.mobile.rest.MobileRestImpl”>  
  3.     <property name=“mobileCodeWSSoap” ref=“mobileCodeWSSoap”>property>  
  4. bean>  
  5.   
  6. <jaxrs:server < span class="attribute" style="margin:0px; padding:0px; border:none; color:red; background-color:inherit">address=“/rest”>  
  7.     <jaxrs:serviceBeans>  
  8.         <ref bean=“mobileRestImpl”/>  
  9.     jaxrs:serviceBeans>  
  10. jaxrs:server>  



 

3. 7.2.4    Url的构成

 

使用jQuery调用cxf(ws)

[javascript]  view plain  copy

  1. $(function(){  
  2.         $(“#mybutton”).click(function(){  
  3.             var data =   
  4.                   +  
  5.                   +  
  6.                   +‘   sss  
  7.                   +‘ ‘  
  8.                   +‘‘  
  9.                   +‘‘;  
  10.                     
  11.                 $.ajax({  
  12.                     url:‘http://localhost:8080/cxf-web-server/services/hello’,  
  13.                     type:‘post’,  
  14.                     dataType:‘xml’,  
  15.                     contentType:‘text/xml;charset=UTF-8’,  
  16.                     data:dat a,  
  17.                     success:function(responseText){  
  18.                         alert($(responseText).find(‘return’).text());  
  19.                     },  
  20.                     error:function(){  
  21.                         alert(“error”);  
  22.                     }  
  23.                 })  
  24.         })  
  25.     })  

[java]  view plain  copy

  1. public  class WeatherModel {  
  2.   
  3.     private String info;  
  4.     private int maxTemp;  
  5.     private int minTemp;  
  6.     private Date date;  

[java]  view plain  copy

[java]  view plain  copy

[java]  view plain  copy

  1. @WebService  
  2. public interface WeatherInterface {  
  3.   
  4.     List queryWeather(String cityName);  
  5. }  

[java]  view plain  cop y

[java]  view plain  copy

[java]  view plain  copy

  1. @WebService(  
  2.         //endpointInterface=”com.itheima.weather.service.WeatherInterface” //可以指定SEI接口  
  3.         name=“WeatherInterface”//不使用SEI接口时规范portType的名称  
  4.         serviceName=“WeatherService”,   //服务视图的名称  
  5.         portName=“WeatherPort”,         //Service节点中port节点的name属性  
  6.         targetNamespace=“http://weather.itheima.com/”   //wsdl的命名空间  
  7. )  
  8. public class WeatherInterfaceImpl implements W eatherInterface {  
  9.   
  10.     @Override  
  11.     @WebMethod/*(exclude=true)*/  
  12.     @WebResult(name=“WeatherInfo”)  
  13.     public List queryWeather(@WebParam(name=“cityName”)String cityName) {  
  14.         System.out.println(“客户端发送的城市:” + cityName);  
  15.         //查询天气信息  
  16.         List info = getWeatherInfo(cityName);  
  17.         //返回天气信息  
  18.         return info;  
  19.     }  
  20.       
  21.     private List getWeatherInfo(String cityName) {  
  22.         List weatherList = new ArrayList<>();  
  23.         Calendar calendar = Calendar.getInstance();  
  24.         //第一天  
  25.         WeatherModel model1 = new WeatherModel();  
  26.         model1.setInfo(“雷阵雨”);  
  27.         model1.setMaxTemp(31);  
  28.         model1.setMinTemp(22);  
  29.         model1.setDate(calendar.getTime());  
  30.         weatherList.add(model1);  
  31.         //第二天  
  32.         WeatherModel model2 = new WeatherModel();  
  33.         model2.setInfo(“多云”);  
  34.         model2.setMaxTemp(33);  
  35.         model2.setMinTemp(25);  
  36.         calendar.set(Calendar.DA TE, calendar.get(Calendar.DATE) + 1);  
  37.         model2.setDate(calendar.getTime());  
  38.         weatherList.add(model2);  
  39.         //第三天  
  40.         WeatherModel model3 = new WeatherModel();  
  41.         model3.setInfo(“多云”);  
  42.         model3.setMaxTemp(35);  
  43.         model3.setMinTemp(25);  
  44.         calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + 1);  
  45.         model3.setDate(calendar.getTime());  
  46.         weatherList.add(model3);  
  47.           
  48.         return weatherList;  
  49.     }  
  50.   
  51. }  

[java]  view plain  copy

[java]  view plain  copy

[java]  view plain  copy

  1. public class WeatherClient {  
  2.   
  3.     public static void main(String[] args) throws Exception {  
  4.         //创建服务视图  
  5.         Service se rvice = Service.create(new URL(“http://127.0.0.1:12345/weather”),   
  6.                 new QName(“http://service.weather.itheima.com/”“WeatherInterfaceImplService”));  
  7.         //从服务视图获得protType对象  
  8.         WeatherInterfaceImpl weatherInterfaceImpl = service.getPort(WeatherInterfaceImpl.class);  
  9.         //调用服务端方法  
  10.         List list = weat herInterfaceImpl.queryWeather(“北京”);  
  11.         //显示天气信息  
  12.         for (WeatherModel weatherModel : list) {  
  13.             System.out.println(weatherModel.getDate().toGregorianCalendar().getTime().t oLocaleString());  
  14.             System.out.println(weatherModel.getInfo());  
  15.             System.out.println(weatherModel.getMaxTemp());  
  16.             System.out.println(weatherModel.getMinTemp());  
  17.               
  18.         }  
  19.     }  
  20. }  

[java]  view plain  copy

[java]  view plain  copy

[java]  view plain  copy

  1. @WebService  
  2. public interface WeatherInterface {  
  3.   
  4.     String queryWeather(String cityName);  
  5. }  

[java]  view plain  copy

[java]  view plain  copy

[java]  view plain  copy

  1. public class WeatherInterfaceImpl implements WeatherInterface {  
  2.   
  3.     @Override  
  4.     public String queryWeather(String cityName) {  
  5.           
  6.         System.out.println(“城市名称:” + cityName);  
  7.         String result = “多云”;  
  8.           
  9.         return result;  
  10.     }  
  11. }  

[java]  view plain  copy

[java]  view plain  copy

[java]  view plain  copy

  1. public class WeatherServer {  
  2.   
  3.     public static void main(String[] args) {  
  4.         //创建一个JaxWsServerFactoryBean对象  
  5.         JaxWsServerFactoryBean factoryBean = new JaxWsServerFactoryBean();  
  6.         //设置服务发布的地址  
  7.         factoryBean.setAddress(“http://127.0.0.1:12345/weather”);  
  8.         //设置SEI  
  9.         factoryBean.setServiceClass(WeatherInterface.class);  
  10.         //设置实现类对象  
  11.         factoryBean.setServiceBean(new WeatherInterfaceImpl());  
  12.         //发布服务  
  13.         factoryBean.create();  
  14.     }  
  15. }  

[java]  view plain  copy

[java]  view plain  copy

[java]  view plain  copy

  1. public class WeatherClient {  
  2.   
  3.     public static void main(String[] args) {  
  4.         //创建一个JaxWsProxyFactoryBean对象  
  5.         JaxWsProxyFactoryBean factoryBean = new JaxWsProxyFactoryBean();  
  6.         //设置服务的url  
  7.         factoryBean.setAddress(“http://127.0.0.1:12345/weather?wsdl”);  
  8.         //设置SEI的类型  
  9.         factoryBean.setServiceClass(WeatherInterface.class);  
  10.         //获得porttype对象  
  11.         WeatherInterface portType = (WeatherInterface) factoryBean.create() ;  
  12.         //调用服务端方法  
  13.         String result = portType.queryWeather(“北京”);  
  14.         System.out.println(result);  
  15.     }  
  16. }  

[java]  view plain  copy

[java]  view plain  copy< /span>

[java]  view plain  copy

  1. @XmlRootElement  
  2. public class WeatherModel {  
  3.   
  4.     private String info;  
  5.     private int maxTemp;  
  6.     private int minTemp;  
  7.     private Date date;  

[java]  view plain  copy

[java]  view plain  copy

[java]  view plain  copy

  1. //窄化请求映射  
  2. @Path(“/weather”)  
  3. public interface WeatherInterface {  
  4.     //方法的请求路径{}中的内容就是参数,需要对应的使用@PathParam注解取参数  
  5.     @Path(“/city/{cityName}”)  
  6.     //请求的方法  
  7.     @GET  
  8.     //返回结果的数据类型,可以是xml也可以是json  
  9.     @Produces({MediaType.APPLICATION_JSON+“;charset=utf-8”, MediaType.APPLICATION_XML})  
  10.     List queryWeather(@PathParam(value=“cityName”)String cityName);  
  11. }  

[java]  view plain  copy

[java]  view plain  copy

[java]  view plain  copy

  1. public class WeatherInterfaceImpl implements WeatherInterface{  
  2.   
  3.     @Override  
  4.     public List queryWeather(String cityName) {  
  5.           
  6.         List weatherInfo = getWeatherInfo(cityName);  
  7.           
  8.         return weatherInfo;  
  9.     }  
  10. …  

[java]  view plain  copy

[java]  view plain  copy

[java]  view plain  copy

  1. public class WeatherServer {  
  2.   
  3.     public static void main(String[] args) {  
  4.         //创建一个JAXRSServerFactoryBean对象  
  5.         JAXRSServerFactoryBean factoryBean = new JAXRSServerFactoryBean();  
  6.         //设置服务发布的地址  
  7.         factoryBean.setAddress(“http://127.0.0.1:12345/rest”);  
  8.         //设置实现类对象  
  9.         factoryBean.setServiceBean(new WeatherInterfaceImpl());  
  10.         //发布服务  
  11.         factoryBean.create();         
  12.     }  
  13. }  

[java]  view plain  copy

[java]  view plain  copy

[html]  view p lain  copy

  1. xml version=“1.0” encoding=“UTF-8”?>  
  2. <beans xmlns=“http://www.springframework.org/schema/beans”  
  3.     xmlns:xsi=“htt p://www.w3.org/2001/XMLSchema-instance”   
  4.     xmlns:jaxws=“http://cxf.apache.org/jaxws”  
  5.     xmlns:jaxrs=“http://cxf.apache.org/jaxrs”   
  6.     xmlns:cxf=“http://cxf.apache.org/core”  
  7.     xsi:schemaLocation=”http://www.springframework.org/schema/beans   
  8.                             http://www.springframework.org/schema/beans/spring-beans.xsd  
  9.                             http://cxf.apache.org/jaxrs   
  10.                             http://cxf.apache.org/schemas/jaxrs.xsd  
  11.                             http://cxf.apache.org/jaxws   
  12.                             http://cxf.apache.org/schemas/jaxws.xsd  
  13.                             http://cxf.apache.org/core   
  14.                             http://cxf.apache.org/schemas/core.xsd”>  
  15.       
  16.       
  17.     <jaxws:client id=“mobileCodeWSSoap” address=“http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx”   
  18.             serviceClass=“cn.com.webxml.MobileCodeWSSoap”/>  
  19.       
  20.     <bean id=“mobileInterfaceImpl” class=“com.itheima.mobile.service.MobileInterfaceImpl”>  
  21.         <property name=“mobileCodeWSSoap” ref=“mobileCodeWSSoap”>property>  
  22.     be an>  
  23. beans>  

[html]  view plain  copy

[html]  view plain  copy

解决方法:添加FaultListener。

[html]  view plain  copy

  1. <cxf:bus>  
  2.        <cxf:properties>  
  3.            <entry key=“org.apache.cxf.logging.FaultListener”>  
  4.                           
  5.                <bean class=“org.apache.cxf.logging.NoOpFaultListener”/>  
  6.            entry>  
  7.        cxf:properties>  
  8.    cxf:bus>  

需要的xmlns和xsd

[html]  view plain  copy

  1. <cxf:bus>  
  2.        <cxf:properties>  
  3.            <entry key=“org.apache.cxf.logging.FaultListener”>  
  4.                           
  5.                <bean class=“org.apache.cxf.logging.NoOpFaultListener”/>  
  6.            entry>  
  7.        cxf:properties>  
  8.    cxf:bus>  

[html]  view plain  copy

[html]  view plain  co py

[html]  view plain  copy

  1. xmlns:cxf=”http://cxf.apache.org/core  
  2. http://cxf.apache.org/core  
  3. http://cxf.apache.org/schemas/core.xsd  

[html]  view plain  copy

  1. xmlns:cxf=”http://cxf.apache.org/core  
  2. http://cxf.apache.org/core  
  3. http://cxf.apache.org/schemas/core.xsd  

[html]   view plain  copy

[html]  view plain  copy

[java]  view plain  copy

  1. @WebService  
  2. public interface MobileInterface {  
  3.   
  4.     Mobile queryMobile(String code);  
  5.       
  6. }  

[java]  view plain  copy

[java]  view plain  copy

[java]  view plain  copy

  1. public class MobileInterfaceImpl implements MobileInterface {  
  2.   
  3.     //公网webservice的porttype配置注入  
  4.     private MobileCodeWSSoap mobileCodeWSSoap;    
  5.     public vo id setMobileCodeWSSoap(MobileCodeWSSoap mobileCodeWSSoap) {  
  6.         this.mobileCodeWSSoap = mobileCodeWSSoap;  
  7.     }  
  8.   
  9.     @Override  
  10.     public Mobile queryMobile(String code) {  
  11.         //第一个参数:手机号  
  12.         //第二个参数:免费用户是空串  
  13.         String info = mobileCodeWSSoap.getMobileCodeInfo(code, “”);  
  14.         Mobile mobile = new Mobile();  
  15.         mobile.setAddress(info);  
  16.         mobile.setCode(code);  
  17.         return mobile;  
  18.     }  
  19. }  

[java]  view plain  copy

[java]  view plain  copy

[html]  view plain  copy

  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” xmlns:web=“http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd”  
  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>B06_spring_cxfdisplay-name>  
  7.   
  8.       
  9.       
  10.     <context-param>  
  11.         <param-name>contextConfigLocationparam-name>  
  12.         <param-value>classpath:applicationContext.xmlparam-value>  
  13.     context-param>  
  14.     <listener>  
  15.         <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>  
  16.     listener>  
  17.       
  18.       
  19.       
  20.       
  21.     <servlet>  
  22.         <servlet-name>cxfservlet-name>  
  23.         <servlet-class>org.apache.cxf.transport.servlet.CXFServletservlet-class>  
  24.           
  25.         <load-on-startup>1load-on-startup>  
  26.     servlet>  
  27.     <servlet-mapping>  
  28.         <servlet-name>cxfservlet-name>  
  29.         <url-pattern>/ws/*< /url-pattern>  
  30.     servlet-mapping>  
  31. web-app>  

[html]  view plain  copy

[html]  view plain  copy

[html]  view plain  copy

  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” xmlns:jaxws=“http://cxf.apache.org/jaxws”  
  4.     xmlns:jaxrs=“http://cxf.apache.org/jaxrs” xmlns:cxf=“http://cxf.apache.org/core”  
  5.     xsi:schemaLocation=”http://www.springframework.org/schema/beans   
  6.                             http://www.springframework.org/schema/beans/spring-beans.xsd  
  7.                             http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd  
  8.                             http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd  
  9.                             http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd”>  
  10.       
  11.       
  12.     <jaxws:client id=“mobileCodeWSSoap” address=“http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx”   
  13.             serviceClass=“cn.com.webxml.MobileCodeWSSoap”/>  
  14.       
  15.     <bean id=“mobileInterfaceImpl” class=“com.itheima.mobile.service.MobileInterfaceImpl”>  
  16.         <property name=“mobileCodeWSSoap” ref=“mobileCodeWSSoap”>property>  
  17.     bean>  
  18.       
  19.       
  20.       
  21.     <jaxws:server address=“/mobile” serviceClass=“com.itheima.mobile.service.MobileInterface”>  
  22.         <jaxws:serviceBean>  
  23.             <ref bean=“mobileInterfaceImpl”< /span>/>  
  24.         jaxws:serviceBean>  
  25.     jaxws:server>  
  26.       
  27.       
  28.     <bean id=“mobileRestImpl” class=“com.itheima.mobile.rest.MobileRestImpl”>  
  29.         <property name=“mobileCodeWSSoap” ref=“mobileCodeWSSoap”>property>  
  30.     bean>  
  31.       
  32.     <jaxrs:server address=“/rest”>  
  33.         <jaxrs:serviceBeans>  
  34.             <ref bean=“mobileRestImpl”/>  
  35.         jaxrs:serviceBeans>  
  36.     jaxrs:server>  
  37.                             
  38. beans>  

[html]  view plain  copy

[html]  view plain  copy

[java]  view plain  copy

  1. @Path(“/mobile”)  
  2. public interface MobileRest {  
  3.   
  4.     @Path(“/code/{code}”)  
  5.     @GET  
  6.     @Produces({MediaType.APPLICATION_JSON+“;charset=utf-8”, MediaType.APPLICATION_XML})  
  7.     Mobile queryMobile(@PathParam(value = “code”)String code);  
  8. }  

[java]  view plain  copy

[java]  view plain  copy

[java]  view plain  copy

  1. public class MobileRestImpl implements MobileRest {  
  2.       
  3.     //公网webservice的porttype  
  4.     private MobileCodeWSSoap mobileCodeWSSoap;  
  5.       
  6.     public void setMobileCodeWSSoap(MobileCodeWSSoap mobileCodeWSSoap) {  
  7.         this.mobileCodeWSSoap = mobileCodeWSSoap;  
  8.     }   
  9.   
  10.     @Override  
  11.     public Mobile queryMobile(String code) {  
  12.         String address = mobileCodeWSSoap.getMobileCodeInfo(code, “”);  
  13.         Mobile mobile = new Mobile();  
  14.         mobile.setAddress(address);  
  15.         mobile.setCode(code);  
  16.           
  17.         return mobile;  
  18.     }  
  19.   
  20. }  

[java]  view plain  copy

[java]  view plain  copy

[html]  view plain  copy

  1.   
  2. <bean id=“mobileRestImpl” class=“com.itheima.mobile.rest.MobileRestImpl”>  
  3.     <property name=“mobileCodeWSSoap” ref=“mobileCodeWSSoap”>property>  
  4. bean>  
  5.   
  6. <jaxrs:server address=“/rest”>  
  7.     <jaxrs:serviceBeans>  
  8.         <ref bean=“mobileRestImpl”/>  
  9.     jaxrs:serviceBeans>  
  10. jaxrs:server>  

[html]  view plain  copy

[html]  view plain  copy

[javascript]  view plain  copy

  1. $(function(){  
  2.         $(“#mybutton”).click(function(){  
  3.             var data =   
  4.                   +  
  5.                   +  
  6.                   +‘   sss  
  7.                   +‘ ‘  
  8.                   +‘‘  
  9.                   +‘‘;  
  10.                     
  11.                 $.ajax({  
  12.                     url:‘http://localhost:8080/cxf-web-server/services/hello’,  
  13.                     type:‘post’,  
  14.                     dataType:‘xml’< span style="margin:0px; padding:0px; border:none; background-color:inherit">,  
  15.                     contentType:‘text/xml;charset=UTF-8’,  
  16.                     data:data,  
  17.                     success:function(responseText){  
  18.                         alert($(responseText).find(‘return’).text());  
  19.                     },  
  20.                     error:function(){  
  21.                         alert( “error”);  
  22.                     }  
  23.                 })  
  24.         })  
  25.     })  

[javascript]  view plain  copy

[javascript]  view plain  copy

Leave a Comment

Your email address will not be published.