CXF 简单创建Webserver 例子

最近在弄webserver,因为公司需要用到,来说说,webserver的常用方式吧

1.什么是webservice

1.1   什么是远程调用技术

远程调用数据定义:是系统和系统之间的调用

先说一说常用的webserver 的客户端方式吧

      Webservice的四种客户端调用方式

公网服务地址:

http://www.webxml.com.cn/zh_cn/index.aspx

1.1   第一种生成客户端调用方式

1.1.1  Wsimport命令介绍

l  Wsimport就是jdk提供的的一个工具,他作用就是根据WSDL地址生成客户端代码

l  Wsimport位置JAVA_HOME/bin

l  Wsimport常用的参数:

  • -s,生成java文件的
  • -d,生成class文件的,默认的参数
  • -p,指定包名的,如果不加该参数,默认包名就是wsdl文档中的命名空间的倒序

l  Wsimport仅支持SOAP1.1客户端的生成

1.1.2  调用公网手机号归属地查询服务

l  第一步:wsimport生成客户端代码

wsimport -p cn.itcast.mobile -s . http://webservice.we

bxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl

l  第二步:阅读使用说明书,使用生成客户端代码调用服务端

package cn.itcast.mobile.client;

 

import cn.itcast.mobile.MobileCodeWS;

import cn.itcast.mobile.MobileCodeWSSoap;

 

/**

 *

 * <p>Title: MobileClient.java</p>

 * <p>Description:公网手机号查询客户端</p>

 * <p>Company: www.itcast.com</p>

 * @author  at

 * @date    2015年11月26日下午3:16:05

 * @version 1.0

 */

public class MobileClient {

 

   public static void main(String[] args) {

      //创建服务视图

      MobileCodeWS mobileCodeWS = new MobileCodeWS();

      //获取服务实现类

      MobileCodeWSSoap mobileCodeWSSoap = mobileCodeWS.getPort(MobileCodeWSSoap.class);

      //调用查询方法

      String reuslt = mobileCodeWSSoap.getMobileCodeInfo("13888888", null);

      System.out.println(reuslt);

   }

}

1.1.3  公网天气服务端查询

package cn.itcast.mobile.client;

 

import java.util.List;

 

import cn.itcast.weather.ArrayOfString;

import cn.itcast.weather.WeatherWS;

import cn.itcast.weather.WeatherWSSoap;

 

/**

 *

 * <p>Title: WeatherClient.java</p>

 * <p>Description:公网天气查询客户端</p>

 * <p>Company: www.itcast.com</p>

 * @author at

 * @date    2015年11月26日下午3:24:12

 * @version 1.0

 */

public class WeatherClient {

 

   public static void main(String[] args) {

      WeatherWS weatherWS = new WeatherWS();

      WeatherWSSoap weatherWSSoap = weatherWS.getPort(WeatherWSSoap.class);

      ArrayOfString  arrayOfString = weatherWSSoap.getWeather("北京", "");

      List<String> list = arrayOfString.getString();

     

      for(String str : list){

         System.out.println(str);

      }

   }

}

1.1.4  特点

该种方式使用简单,但一些关键的元素在代码生成时写死到生成代码中,不方便维护,所以仅用于测试。

2       第二种:service编程调用方式

package cn.itcast.mobile.client;

 

import java.io.IOException;

import java.net.MalformedURLException;

import java.net.URL;

 

import javax.xml.namespace.QName;

import javax.xml.ws.Service;

 

import cn.itcast.mobile.MobileCodeWSSoap;

 

/**

 *

 * <p>Title: ServiceClient.java</p>

 * <p>Description:Service编程实现服务端调用</p>

 * <p>Company: www.itcast.com</p>

 * @author at

 * @date    2015年11月26日下午3:43:55

 * @version 1.0

 */

public class ServiceClient {

 

   public static void main(String[] args) throws IOException {

      //创建WSDL的URL,注意不是服务地址

      URL url = new URL("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl");

     

      //创建服务名称

      //1.namespaceURI - 命名空间地址

      //2.localPart - 服务视图名

      QName qname = new QName("http://WebXml.com.cn/", "MobileCodeWS");

     

      //创建服务视图

      //参数解释:

      //1.wsdlDocumentLocation - wsdl地址

      //2.serviceName - 服务名称

      Service service = Service.create(url, qname);

      //获取服务实现类

      MobileCodeWSSoap mobileCodeWSSoap = service.getPort(MobileCodeWSSoap.class);

      //调用查询方法

      String result = mobileCodeWSSoap.getMobileCodeInfo("1866666666", "");

      System.out.println(result);

   }

}

2.1   特点

该种方式可以自定义关键元素,方便以后维护,是一种标准的开发方式

3       第三种:HttpURLConnection调用方式

开发步骤:

第一步:创建服务地址

第二步:打开一个通向服务地址的连接

第三步:设置参数

设置POST,POST必须大写,如果不大写,报如下异常

如果不设置输入输出,会报如下异常

第四步:组织SOAP数据,发送请求

第五步:接收服务端响应,打印

package cn.itcast.mobile.client;

 

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.URL;

 

/**

 *

 * <p>Title: HttpClient.java</p>

 * <p>Description:HttpURLConnection调用方式</p>

 * <p>Company: www.itcast.com</p>

 * @author  at

 * @date    2015年11月26日下午3:58:57

 * @version 1.0

 */

public class HttpClient {

 

   public static void main(String[] args) throws IOException {

      //第一步:创建服务地址,不是WSDL地址

      URL url = new URL("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx");

      //第二步:打开一个通向服务地址的连接

      HttpURLConnection connection = (HttpURLConnection) url.openConnection();

      //第三步:设置参数

      //3.1发送方式设置:POST必须大写

      connection.setRequestMethod("POST");

      //3.2设置数据格式:content-type

      connection.setRequestProperty("content-type", "text/xml;charset=utf-8");

      //3.3设置输入输出,因为默认新创建的connection没有读写权限,

      connection.setDoInput(true);

      connection.setDoOutput(true);

 

      //第四步:组织SOAP数据,发送请求

      String soapXML = getXML("15226466316");

      OutputStream os = connection.getOutputStream();

      os.write(soapXML.getBytes());

      //第五步:接收服务端响应,打印

      int responseCode = connection.getResponseCode();

      if(200 == responseCode){//表示服务端响应成功

         InputStream is = connection.getInputStream();

         InputStreamReader isr = new InputStreamReader(is);

         BufferedReader br = new BufferedReader(isr);

        

         StringBuilder sb = new StringBuilder();

         String temp = null;

         while(null != (temp = br.readLine())){

            sb.append(temp);

         }

         System.out.println(sb.toString());

        

         is.close();

         isr.close();

         br.close();

      }

 

      os.close();

   }

  

   /**

    * <?xml version="1.0" encoding="utf-8"?>

<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">

  <soap:Body>

    <getMobileCodeInfo xmlns="http://WebXml.com.cn/">

      <mobileCode>string</mobileCode>

      <userID>string</userID>

    </getMobileCodeInfo>

  </soap:Body>

</soap:Envelope>

    * @param phoneNum

    * @return

    */

   public static String getXML(String phoneNum){

      String soapXML = "<?xml version="1.0" encoding="utf-8"?>"

      +"<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">"

         +"<soap:Body>"

          +"<getMobileCodeInfo xmlns="http://WebXml.com.cn/">"

             +"<mobileCode>"+phoneNum+"</mobileCode>"

            +"<userID></userID>"

          +"</getMobileCodeInfo>"

        +"</soap:Body>"

      +"</soap:Envelope>";

      return soapXML;

   }

}

4       Ajax调用方式

<!doctype html>

<html lang="en">

 <head>

  <meta charset="UTF-8">

  <title>Document</title>

  <script type="text/javascript">

         function queryMobile(){

                   //创建XMLHttpRequest对象

                   var xhr = new XMLHttpRequest();

                   //打开连接

                  xhr.open("post","http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx",true);

                   //设置数据类型

                   xhr.setRequestHeader("content-type","text/xml;charset=utf-8");

                   //设置回调函数

                   xhr.onreadystatechange=function(){

                            //判断是否发送成功和判断服务端是否响应成功

                            if(4 == xhr.readyState && 200 == xhr.status){

                                     alert(xhr.responseText);

                            }

                   }

                   //组织SOAP协议数据

                   var soapXML = "<?xml version="1.0" encoding="utf-8"?>"

                   +"<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">"

                            +"<soap:Body>"

                       +"<getMobileCodeInfo xmlns="http://WebXml.com.cn/">"

                                +"<mobileCode>"+document.getElementById("phoneNum").value+"</mobileCode>"

                         +"<userID></userID>"

                       +"</getMobileCodeInfo>"

                     +"</soap:Body>"

                   +"</soap:Envelope>";

                   alert(soapXML);

                   //发送数据

                   xhr.send(soapXML);

         }

  </script>

 </head>

 <body>

  手机号查询:<input type="text" id="phoneNum"/> <input type="button" value="查询" onclick="javascript:queryMobile();"/>

 </body>

</html>

当然是复制的啦,给我自己回忆看的,有兴趣一起来更深入的探讨啊!

cxf

1       CXF介绍、安装和配置

1.1   CXF介绍

l  CXF是一个开源的webservice框架,提供很多完善功能,可以实现快速开发

l  CXF支持的协议:SOAP1.1/1.2,REST

l  CXF支持数据格式:XML,JSON(仅在REST方式下支持)

1.2   CXF的安装和配置

l  下载地址

http://cxf.apache.org/download.html

l  包结构介绍

l  安装和配置

  • 第一步:安装JDK,建议1.7
  • 第二步:解压apache-cxf-2.7.11.zip到指定目录,创建CXF_HOME
  • 第三步:把CXF_HOME加入到Path路径下
  • 第四步:测试,在cmd下加入wsdl2java –h
  • 如果不想使用IDE(比如Eclipse),需要在环境变量下配置如下信息

2       CXF发布SOAP协议的服务

2.1   需求

服务端:发布服务,接收客户端的城市名,返回天气数据给客户端

客户端:发送城市名给服务端,接收服务端的响应信息,打印

2.2   实现

2.2.1  服务端

开发步骤:

第一步:导入Jar包

第二步:创建SEI接口,要加入@WebService

package cn.itcast.ws.cxf.server;

 

import javax.jws.WebService;

 

/**

 *

 * <p>Title: WeatherInterface.java</p>

 * <p>Description:SEI接口</p>

 * <p>Company: www.itcast.com</p>

 * @authorat

 * @date    2015年11月27日上午9:47:43

 * @version 1.0

 */

@WebService

public interface WeatherInterface {

 

   public String queryWeather(String cityName);

}

第三步:创建SEI实现类

package cn.itcast.ws.cxf.server;

 

/**

 *

 * <p>Title: WeatherInterfaceImpl.java</p>

 * <p>Description:SEI实现类</p>

 * <p>Company: www.itcast.com</p>

 * @authorat

 * @date    2015年11月27日上午9:50:59

 * @version 1.0

 */

public class WeatherInterfaceImpl implements WeatherInterface {

 

   @Override

   public String queryWeather(String cityName) {

      System.out.println("from client..."+cityName);

      if("北京".equals(cityName)){

         return "冷且霾";

      } else {

         return "暖且晴";

      }

   }

 

}

第四步:发布服务, JaxWsServerFactoryBean发布,设置3个参数,1.服务接口;2.服务实现类;3.服务地址;

endpoint仅支持发布实现类,JaxWsServerFactoryBean支持发布接口。

package cn.itcast.ws.cxf.server;

 

import org.apache.cxf.jaxws.JaxWsServerFactoryBean;

import org.apache.cxf.tools.java2wsdl.processor.internal.jaxws.generator.JaxwsServerGenerator;

 

/**

 *

 * <p>Title: WeatherServer.java</p>

 * <p>Description:服务端</p>

 * <p>Company: www.itcast.com</p>

 * @authorat

 * @date    2015年11月27日上午9:51:36

 * @version 1.0

 */

public class WeatherServer {

 

   public static void main(String[] args) {

      //JaxWsServerFactoryBean发布服务

      JaxWsServerFactoryBean jaxWsServerFactoryBean = new JaxWsServerFactoryBean();

      //设置服务接口

      jaxWsServerFactoryBean.setServiceClass(WeatherInterface.class);

      //设置服务实现类

      jaxWsServerFactoryBean.setServiceBean(new WeatherInterfaceImpl());

      //设置服务地址

      jaxWsServerFactoryBean.setAddress("http://127.0.0.1:12345/weather");

      //发布

      jaxWsServerFactoryBean.create();

   }

}

第五步:测试服务是否发布成功,阅读使用说明书,确定关键点

如果在CXF发布的服务下,直接访问服务地址,会如下异常

此时直接访问使用说明书地址即可

2.2.1.1        发布SOAP1.2的服务端

l  在接口上加入如下注解:

@BindingType(SOAPBinding.SOAP12HTTP_BINDING)

l  重新发布服务端

2.2.1.2        拦截器

l  原理:

  • 拦截器可以拦截请求和响应
  • 拦截器可以有多个
  • 拦截器可以根据需要自定义

l  使用

  • 拦截器必须加到服务端,在服务端发布之前
  • 获取拦截器列表,将自己的拦截器加入列表中

2.2.2  客户端

第一步:生成客户端代码

l  Wsdl2java命令是CXF提供的生成客户端的工具,他和wsimport类似,可以根据WSDL生成客户端代码

l  Wsdl2java常用参数:

         -d,指定输出目录

         -p,指定包名,如果不指定该参数,默认包名是WSDL的命名空间的倒序

l  Wsdl2java支持SOAP1.1和SOAP1.2

第二步:使用说明书,使用生成代码调用服务端

         JaxWsProxyFactoryBean调用服务端,设置2个参数,1.设置服务接口;2.设置服务地址

package cn.itcast.cxf.client;

 

import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;

 

import cn.itcast.cxf.weather.WeatherInterface;

 

/**

 *

 * <p>Title: WeatherClient.java</p>

 * <p>Description:客户端</p>

 * <p>Company: www.itcast.com</p>

 * @authorat

 * @date    2015年11月27日上午10:12:24

 * @version 1.0

 */

public class WeatherClient {

 

   public static void main(String[] args) {

      //JaxWsProxyFactoryBean调用服务端

      JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();

      //设置服务接口

      jaxWsProxyFactoryBean.setServiceClass(WeatherInterface.class);

      //设置服务地址

      jaxWsProxyFactoryBean.setAddress("http://127.0.0.1:12345/weather");

      //获取服务接口实例

      WeatherInterface weatherInterface = jaxWsProxyFactoryBean.create(WeatherInterface.class);

      //调用查询方法

      String weather = weatherInterface.queryWeather("保定");

      System.out.println(weather);

   }

}

接下来是整合spring

1       CXF+Spring整合发布SOAP协议的服务

1.1   服务端

开发步骤:

第一步:创建web项目(引入jar包)

第二步:创建SEI接口

第三步:创建SEI实现类

第四步:配置spring配置文件,applicationContext.xml,用<jaxws:server标签发布服务,设置1.服务地址;2.设置服务接口;3设置服务实现类

<?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:jaxws="http://cxf.apache.org/jaxws"

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

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

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

                        http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd

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

                        http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd">

   <!-- <jaxws:server发布SOAP协议的服务 ,对JaxWsServerFactoryBean类封装-->

   <jaxws:server address="/weather" serviceClass="cn.itcast.ws.cxf.server.WeatherInterface">

      <jaxws:serviceBean>

         <ref bean="weatherInterface"/>

      </jaxws:serviceBean>

   </jaxws:server>

   <!-- 配置服务实现类 -->

   <bean name="weatherInterface" class="cn.itcast.ws.cxf.server.WeatherInterfaceImpl"/>

</beans>

第五步:配置web.xml,配置spring配置文件地址和加载的listener,配置CXF的servlet

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

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

  <display-name>ws_2_cxf_spring_server</display-name>

 

  <!-- 设置spring的环境 -->

  <context-param>

  <!--contextConfigLocation是不能修改的  -->

  <param-name>contextConfigLocation</param-name>

  <param-value>classpath:applicationContext.xml</param-value>

  </context-param>

  <listener>

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

  </listener>

 

  <!-- 配置CXF的Servlet -->

  <servlet>

  <servlet-name>CXF</servlet-name>

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

  </servlet>

  <servlet-mapping>

  <servlet-name>CXF</servlet-name>

  <url-pattern>/ws/*</url-pattern>

  </servlet-mapping>

 

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>

</web-app>

第六步:部署到tomcat下,启动tomcat

第七步:测试服务,阅读使用说明书

         WSDL地址规则:http://ip:端口号/项目名称/servlet拦截路径/服务名称?wsdl

1.1.1  拦截器配置

配置applicationContext.xml中。

1.1.2  Endpoint标签发布服务

<jaxws:endpoint>标签

package cn.itcast.ws.cxf.server;

 

import javax.jws.WebService;

 

/**

 *

 * <p>Title: HelloWorld.java</p>

 * <p>Description:简单类</p>

 * <p>Company: www.itcast.com</p>

 * @author  at

 * @date    2015年11月27日上午11:11:10

 * @version 1.0

 */

@WebService

public class HelloWorld {

   public String sayHello(String name){

      return "hello,"+name;

   }

  

}

1.2   客户端

开发步骤:

第一步:引入jar包

第二步:生成客户端代码

第三步:配置spring配置文件,applicationContent.xml

<?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:jaxws="http://cxf.apache.org/jaxws"

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

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

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

                        http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd

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

                        http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd">

   <!-- <jaxws:client实现客户端 ,对JaxWsProxyFactoryBean类封装--> 

   <jaxws:client id="weatherClient" address="http://127.0.0.1:8080/ws_2_cxf_spring_server/ws/weather" serviceClass="cn.itcast.cxf.weather.WeatherInterface"/>

</beans>

第四步:从spring上下文件获取服务实现类

第五步:调用查询方法,打印

package cn.itcast.cxf.client;

 

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

 

import cn.itcast.cxf.weather.WeatherInterface;

 

public class WeatherClient {

 

   public static void main(String[] args) {

      //初始化spring的上下文

      ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");

      WeatherInterface  weatherInterface = (WeatherInterface) context.getBean("weatherClient");

      String weather = weatherInterface.queryWeather("保定");

      System.out.println(weather);

   }

}

 就先这样吧0.0

原文地址:https://www.cnblogs.com/nan1/p/7544822.html