zoukankan      html  css  js  c++  java
  • web service -- jdk spring cxf ajax 开发(2)

    1.JDK 开发web service

             1. 里面有自带Web Services Explorer浏览器 

              2.在javaEE  下点击右上角wsdlpage  即可  注意:jdk1.8 会报错 500

             3. 服务端代码

                       

    package com.bdqn.ws;
    
    import javax.jws.WebMethod;
    import javax.jws.WebService;
    
    
    @WebService
    public interface IholloTest {
       
        @WebMethod 
        String say(String str);
    }
    服务端接口
    package com.bdqn.ws;
    
    import javax.jws.WebService;
    
    
    @WebService
    public class IHolleTest implements IholloTest{
    
        @Override
        public String say(String str) {
            System.out.println("http://localhost:8989/FirstWS/adress"+str);
            return str;
        }
          
    }
    服务端实现类
    package com.bdqn.ws;
    
    import javax.xml.ws.Endpoint;
    
    public class Publishs {
    
        public static void main(String[] args) {
            String url="http://localhost:8989/FirstWS/adress" ; 
            Endpoint.publish(url,new IHolleTest());
            
            
        }
    
    }
    endpoint 发布
    <definitions xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsp="http://www.w3.org/ns/ws-policy" xmlns:wsp1_2="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://ws.bdqn.com/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://ws.bdqn.com/" name="IHolleTestService">
    <types>
    <xsd:schema>
    <xsd:import namespace="http://ws.bdqn.com/" schemaLocation="http://localhost:8989/FirstWS/adress?xsd=1"/>
    </xsd:schema>
    </types>
    <message name="say">
    <part name="parameters" element="tns:say"/>
    </message>
    <message name="sayResponse">
    <part name="parameters" element="tns:sayResponse"/>
    </message>
    <portType name="IHolleTest">
    <operation name="say">
    <input wsam:Action="http://ws.bdqn.com/IHolleTest/sayRequest" message="tns:say"/>
    <output wsam:Action="http://ws.bdqn.com/IHolleTest/sayResponse" message="tns:sayResponse"/>
    </operation>
    </portType>
    <binding name="IHolleTestPortBinding" type="tns:IHolleTest">
    <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/>
    <operation name="say">
    <soap:operation soapAction=""/>
    <input>
    <soap:body use="literal"/>
    </input>
    <output>
    <soap:body use="literal"/>
    </output>
    </operation>
    </binding>
    <service name="IHolleTestService">
    <port name="IHolleTestPort" binding="tns:IHolleTestPortBinding">
    <soap:address location="http://localhost:8989/FirstWS/adress"/>
    </port>
    </service>
    </definitions>
    WSDL 文档

              4. 在cmd 窗口用jdk 指令 生成客户端的代码

                     注意(这里发布的url 是自己本机的IP)

                      这里的wsdl文件 可以是 网络的http://localhost:8989/FirstWS/adress?wsdl  也可以是项目中本地wsdl文件(是在网络文件copy)

                     

             5.执行完指令后生成com.bdqn.ws包下所有的类,--这里的包名是来源于服务端的包名

                        

    package com.bdqn.client;
    
    import com.bdqn.ws.IHolleTest;
    import com.bdqn.ws.IHolleTestService;
    
    public class Clientws {
     public static void main(String[] args) {
         IHolleTestService holle=new IHolleTestService();
          IHolleTest test=holle.getIHolleTestPort();
          System.out.println(test.getClass());
          String say=test.say("xiaoli ");
          System.out.println(say);
    }
    }
    client 客户端

                 6   启动服务后客户端方可调用服务端的代码

     2.  spring/cxf/ajax 整合开发web service   加入自定义拦截器和日志拦截器

     a  客户端代码

       注意:ws包下的代码是jdk生成     wsimport -keep  http://localhost:8080/webservicesCXF-spring/orderws?wsdl 

    package com.zhouwuji.servlet;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLConnection;
    
     import javax.servlet.ServletException;
     import javax.servlet.ServletOutputStream;
     import javax.servlet.annotation.WebServlet;
     import javax.servlet.http.HttpServlet;
     import javax.servlet.http.HttpServletRequest;
     import javax.servlet.http.HttpServletResponse;
     
     import org.apache.jasper.tagplugins.jstl.core.Url;
     
     import com.sun.jndi.toolkit.url.Uri;
     
     /**
      * Servlet implementation class HttpURLConnectionServlet
      */
     @WebServlet("/HttpURLConnectionServlet")
     public class HttpURLConnectionServlet extends HttpServlet {
         private static final long serialVersionUID = 1L;
     
         /**
          * 跨域请求webService
          */
         protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
             String name = request.getParameter("name");
             
           //  String path = "http://192.168.140.86:8080/webservicesCXF-spring/orderws";
             String path = "http://localhost:8080/webservicesCXF-spring/orderws";
             String data = "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'><soap:Header><authHeader><userId>wl</userId><password>1985310</password></authHeader></soap:Header><soap:Body><ns2:getOrderById xmlns:ns2='http://ws.zhouwuji.com/'><arg0>"
                     + name + "</arg0></ns2:getOrderById></soap:Body></soap:Envelope>";
         
             URL url = new URL(path);
             HttpURLConnection connection = (HttpURLConnection) url.openConnection();
             connection.setRequestMethod("POST");
             connection.setDoOutput(true);
             connection.setDoInput(true);
             connection.setRequestProperty("Content-Type", "text/xml;charset=utf-8");
             
             OutputStream os = connection.getOutputStream();
             os.write(data.getBytes("utf-8"));
             os.flush();
             
             int code = connection.getResponseCode();
             if(code==200){
                 InputStream is = connection.getInputStream();
                 
                 response.setContentType("text/xml;charset=utf-8");
                 ServletOutputStream outputStream = response.getOutputStream();
                 
                 int len=0;
                 byte[] buff = new byte[1024];
                 
                 while((len = is.read(buff))>0){
                     outputStream.write(buff,0,len);
                 }
                 
                 outputStream.flush();
                 outputStream.close();
             }
         }
     }
    HttpURLConnectionServlet
    package com.zhouwuji.interceptor;
    
    import java.util.List;
    
    
    import javax.xml.namespace.QName;
    
    
    import org.apache.cxf.binding.soap.SoapMessage;
    import org.apache.cxf.headers.Header;
    import org.apache.cxf.helpers.DOMUtils;
    import org.apache.cxf.interceptor.Fault;
    import org.apache.cxf.phase.AbstractPhaseInterceptor;
    import org.apache.cxf.phase.Phase;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    
    public class AddHeaderInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
        
        private String userId;
        private String password;
    
    
        public AddHeaderInterceptor(String userId,String password) {
        //super(Phase.PRE_PROTOCOL);//准备协议化时拦截  
        super(Phase.PREPARE_SEND);//准备发送soap消息的时候
        this.userId=userId;
        this.password=password;
        System.out.println("客户端端拦截器初始化");
        }
       /*  
        <Envelope>  
            <head>  
                <head>  
                <authHeader>  
                    <userId>wl</userId>  
                    <password>1985310</password>  
                </authHeader>  
            <head>  
            <head>  
            <Body>  
                <sayHello>  
                    <arg0>wl</arg0>  
                <sayHello>  
            </Body>  
        </Envelope>  
     */   
        public void handleMessage(SoapMessage msg) throws Fault {
           System.out.println("客户端拦截器"+msg);
          
           List<Header>headers=msg.getHeaders();
           
           Document doc=DOMUtils.createDocument();
           Element ele=doc.createElement("authHeader");
         
           Element idEle=doc.createElement("userId");
            idEle.setTextContent(userId);
        Element passwordEle=doc.createElement("password");
        passwordEle.setTextContent(password);
    
        ele.appendChild(idEle);
        ele.appendChild(passwordEle);
        headers.add(new Header( new QName("www.xxx") ,ele));
        }
    
        
    
    }
    AddHeaderInterceptor
    package com.zhouwuji.servlet;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import com.zhouwuji.ws.Order;
    import com.zhouwuji.ws.impl.OrderWS;
    
    /**
     * 自动生成语句  wsimport -keep http://192.168.140.86:8080/webservicesCXF-sptring/orderws?wsdl
     * @author OU
     *
     */
    public class sdaf {
     public static void main(String[] args) {
          ApplicationContext  ap=new ClassPathXmlApplicationContext("classpath:application-cxf.xml");
          OrderWS orderWS=(OrderWS) ap.getBean("orders");
          Order order=orderWS.getOrderById(1);
          System.out.println(order.toString());
    }
    }
    sdaf
    <?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"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
          <!--引入 cxf 的一些核心配置-->
         <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" />
        
        <!--  Cxf WebService 服务端示例 
        <jaxws:endpoint id="orderWS" implementor="com.zhouwuji.ws.impl.OrderWSImpl" address="/orderws"/>
        -->
        <!--  Cxf WebService 客户端示例-->
        <jaxws:client id="orders" serviceClass="com.zhouwuji.ws.impl.OrderWS" address="http://192.168.140.86:8080/webservicesCXF-spring/orderws?wsdl" >
            <jaxws:outInterceptors  >
              <!-- 添加cxf日志出拦截器  -->  
                <bean class="org.apache.cxf.interceptor.LoggingOutInterceptor"/>  
               <!-- 添加自定义cxf拦截器 -->  
              <bean class="com.zhouwuji.interceptor.AddHeaderInterceptor">   
                 <constructor-arg name="userId" value="wl"/>
                 <constructor-arg name="password" value="1985310"/>
              </bean>
            </jaxws:outInterceptors>
             <jaxws:inInterceptors>  
                <!-- 添加cxf日志入拦截器  -->  
                <bean class="org.apache.cxf.interceptor.LoggingInInterceptor"/>   
            </jaxws:inInterceptors>  
        </jaxws:client>
         
    </beans>
    application-cxf.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app id="WebApp_ID" 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">
       <servlet>
            <servlet-name>connectionServlet</servlet-name>
            <servlet-class>com.zhouwuji.servlet.HttpURLConnectionServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>connectionServlet</servlet-name>
            <url-pattern>/httpURLConnectionServlet</url-pattern>
        </servlet-mapping>
    </web-app>
    web.xml
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
        <%
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://"
                + request.getServerName() + ":" + request.getServerPort()
                + path + "/";
    %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript" src="js/jquery-1.8.3.js"></script>
    <script type="text/javascript">
         $(function(){
             /* 解决跨域问题   发送请求到servlet 由servlet url 请求 webservice 客户端    
                java代码不存在跨域问题
               */
                $("#btn2").click(function() {
                var name = document.getElementById("name").value;
                $.post("httpURLConnectionServlet","name=" + name, 
                           function(msg) {
                           var $Result = $(msg);
                           var value = $Result.find("return").text();
                            alert(value);
                                }, "xml");
                });
            
                /* jquery 请求  */    
             $("#btn1").click(function() {
            var name = document.getElementById("name").value;
            var date = '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Header><authHeader><userId>wl</userId><password>1985310</password></authHeader></soap:Header><soap:Body><ns2:getOrderById xmlns:ns2="http://ws.zhouwuji.com/"><arg0>'
                + name + '</arg0></ns2:getOrderById></soap:Body></soap:Envelope>';
           alert(date);
            $.ajax({
              type : "POST",
              url : "http://localhost:8080/webservicesCXF-spring/orderws",
              data : date,
            success : function(msg) {
            alert("------");
            var $Result = $(msg);
            var value = $Result.find(
            "return").text();
            alert(value);
            },
            error : function(msg) {
            //alert("-----"+msg);
            },
            dataType : "xml"
            });
            });
        });
        /* 原生js 请求  */                    
        function reqWebService() {
            var name = document.getElementById("name").value;
            var date = '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Header><authHeader><userId>wl</userId><password>1985310</password></authHeader></soap:Header><soap:Body><ns2:getOrderById xmlns:ns2="http://ws.zhouwuji.com/"><arg0>'
                    + name + '</arg0></ns2:getOrderById></soap:Body></soap:Envelope>';
            var xmlhttp = getRequest();
            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    var result = xmlhttp.responseXML;
                    var returnEle1 = result.getElementsByTagName("id")[0];
                    var returnEle2 = result.getElementsByTagName("name")[0];
                    var returnEle3 = result.getElementsByTagName("price")[0];
                    var vale1 = returnEle1.firstChild.data;
                    var vale2 = returnEle2.firstChild.data;
                    var vale3 = returnEle3.firstChild.data;
                    alert(vale1+vale2+vale3);
    
                }
            };
           //localhost 不能用ip请求 对于js讲跨域请求  协议/ip/端口  保持一致 否则跨域
            xmlhttp.open("POST","http://localhost:8080/webservicesCXF-spring/orderws");
    
            xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    
            xmlhttp.send(date);
    
        }
    
        function getRequest() {
            var xmlhttp = null;
            if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            } else {// code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            return xmlhttp;
        } 
    </script>
    
    
    </head>
    <body>
        用户名:
        <input type="text" id="name" name="username" />
        <br />
        <div>
            <button onclick="reqWebService()">使用Ajax连接 webservice</button>
        </div>
        <button id="btn1">使用JQuery链接webService</button>
        <button id="btn2">使用Connection链接webService</button>
    
    </body>
    </html>
    inde.jsp
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.zhouwuji.webservices</groupId>
        <artifactId>webservicesCXF-sptring</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>war</packaging>
        <properties>
        <cxf.version>2.6.2</cxf.version>
       </properties>
         <dependencies>
           <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>3.2.3.RELEASE</version>
            </dependency>
          <dependency>
                    <groupId>org.apache.cxf</groupId>
                    <artifactId>cxf-api</artifactId>
                    <version>${cxf.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.apache.cxf</groupId>
                    <artifactId>cxf-rt-frontend-simple</artifactId>
                    <version>${cxf.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.apache.cxf</groupId>
                    <artifactId>cxf-rt-frontend-jaxws</artifactId>
                    <version>${cxf.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.apache.cxf</groupId>
                    <artifactId>cxf-rt-transports-http</artifactId>
                    <version>${cxf.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.apache.cxf</groupId>
                    <artifactId>cxf-rt-frontend-jaxrs</artifactId>
                    <version>${cxf.version}</version>
                </dependency>
         </dependencies>
    </project>
    pom.xml

    b web service 服务端

    package com.zhouwuji.bean;
    
    public class Order {
        private int id;
        private String name;
        private double price;
        
        
        public Order(int id, String name, double price) {
            super();
            this.id = id;
            this.name = name;
            this.price = price;
        }
        public Order() {
            super();
        }
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public double getPrice() {
            return price;
        }
        public void setPrice(double price) {
            this.price = price;
        }
        @Override
        public String toString() {
            return "Order [id=" + id + ", name=" + name + ", price=" + price + "]";
        }
        
    }
    Order
    package com.zhouwuji.intercepter;
    
    import java.util.List;
    
    import org.apache.cxf.binding.soap.SoapMessage;
    import org.apache.cxf.headers.Header;
    import org.apache.cxf.interceptor.Fault;
    import org.apache.cxf.phase.AbstractPhaseInterceptor;
    import org.apache.cxf.phase.Phase;
    import org.w3c.dom.Element;
    import org.w3c.dom.NodeList;
    
    public class AuthInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
        
        public AuthInterceptor() {
            //super(Phase.PRE_PROTOCOL);//准备协议化时拦截  
            super(Phase.PRE_INVOKE);// 调用之前拦截soap消息
            System.out.println("服务器端拦截器初始化");
        }
        /*  
        <Envelope>  
            <head>  
                <authHeader>  
                    <userId>wl</userId>  
                    <password>1985310</password>  
                </authHeader>  
            <head>  
            <Body>  
                <sayHello>  
                    <arg0>wl</arg0>  
                <sayHello>  
            </Body>  
        </Envelope>  
     */ 
    
        public void handleMessage(SoapMessage msg) throws Fault {
    //服务端拦截器={javax.xml.ws.wsdl.port={http://impl.ws.zhouwuji.com/}OrderWSImplPort, org.apache.cxf.service.model.MessageInfo=[MessageInfo INPUT: {http://ws.zhouwuji.com/}getOrderById], org.apache.cxf.message.Message.PROTOCOL_HEADERS={Accept=[text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2], cache-control=[no-cache], connection=[keep-alive], Content-Length=[295], content-type=[text/xml;charset=utf-8], host=[localhost:8080], pragma=[no-cache], user-agent=[Java/1.7.0_71]}, org.apache.cxf.interceptor.LoggingMessage.ID=1, HTTP_CONTEXT_MATCH_STRATEGY=stem, http.service.redirection=null, org.apache.cxf.request.url=http://localhost:8080/webservicesCXF-spring/orderws, javax.xml.ws.wsdl.interface={http://ws.zhouwuji.com/}OrderWS, org.apache.cxf.request.uri=/webservicesCXF-spring/orderws, HTTP.REQUEST=org.apache.catalina.connector.RequestFacade@6a3eb145, HTTP.CONFIG=org.apache.catalina.core.StandardWrapperFacade@39e85f81, org.apache.cxf.transport.https.CertConstraints=null, Accept=text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2, org.apache.cxf.headers.Header.list=[org.apache.cxf.binding.soap.SoapHeader@46d62bda], org.apache.cxf.message.Message.PATH_INFO=/webservicesCXF-spring/orderws, org.apache.cxf.message.Message.BASE_PATH=/webservicesCXF-spring/orderws, javax.xml.ws.wsdl.service={http://impl.ws.zhouwuji.com/}OrderWSImplService, org.apache.cxf.message.Message.IN_INTERCEPTORS=[org.apache.cxf.transport.https.CertConstraintsInterceptor@16d9198b], org.apache.cxf.binding.soap.SoapVersion=org.apache.cxf.binding.soap.Soap11@71c0065, org.apache.cxf.message.Message.ENCODING=UTF-8, org.apache.cxf.message.Message.QUERY_STRING=null, HTTP.RESPONSE=org.apache.catalina.connector.ResponseFacade@3f5dea88, org.apache.cxf.security.SecurityContext=org.apache.cxf.transport.http.AbstractHTTPDestination$2@2ed0a738, org.apache.cxf.request.method=POST, org.apache.cxf.async.post.response.dispatch=true, org.apache.cxf.configuration.security.AuthorizationPolicy=null, javax.xml.ws.wsdl.operation={http://ws.zhouwuji.com/}getOrderById, org.apache.cxf.message.MessageFIXED_PARAMETER_ORDER=false, org.apache.cxf.transport.Destination=org.apache.cxf.transport.servlet.ServletDestination@492658b, javax.xml.ws.wsdl.description=http://localhost:8080/webservicesCXF-spring/orderws?wsdl, http.base.path=http://localhost:8080/webservicesCXF-spring, org.apache.cxf.service.model.BindingMessageInfo=org.apache.cxf.service.model.BindingMessageInfo@27488b05, Content-Type=text/xml;charset=utf-8, HTTP.CONTEXT=org.apache.catalina.core.ApplicationContextFacade@b9f0969}
            System.out.println("服务端拦截器=" + msg);
            List<Header> headers = msg.getHeaders();
            if (headers == null || headers.size() <= 0) {
                throw new Fault(new IllegalArgumentException("没有header 不能调用"));
            }
    
            Header firstHeader = headers.get(0);
            Element ele = (Element) firstHeader.getObject();
            NodeList userIds = ele.getElementsByTagName("userId");
            NodeList passwards = ele.getElementsByTagName("password");
    
                 // 用户名个数=1
            System.out.println("用户名个数=" + userIds.getLength());
               //密码个数=1
            System.out.println("密码个数=" + passwards.getLength());
            if (userIds.getLength() != 1 || passwards.getLength() != 1) {
                throw new Fault(new IllegalArgumentException("格式不对"));
            }
            String userId = userIds.item(0).getTextContent();
            String passward = passwards.item(0).getTextContent();
                 //用户名=wl
            System.out.println("用户名=" + userId);
               //密码=1985310
            System.out.println("密码=" + passward);
            if (!"wl".equals(userId) || !"1985310".equals(passward)) {
                throw new Fault(new IllegalArgumentException("用户名或者密码不对"));
            }
                 //通过服务端拦截器
            System.out.println("通过服务端拦截器");
    
        }
    
    }
    AuthInterceptor
    package com.zhouwuji.ws.impl;
    
    import javax.jws.WebService;
    
    import com.zhouwuji.bean.Order;
    import com.zhouwuji.ws.OrderWS;
    
    @WebService
    public class OrderWSImpl  implements OrderWS{
         public OrderWSImpl(){
            System.out.println("OrderWSImpl"); 
         }
        public Order getOrderById(int id) {
            System.out.println("getOrderById"+id);
            return new Order(id, "飞机", 122112);
        }
    
    }
    OrderWSImpl
    package com.zhouwuji.ws;
    
    import javax.jws.WebMethod;
    import javax.jws.WebService;
    
    import com.zhouwuji.bean.Order;
    
    
    @WebService
    public interface OrderWS {
        @WebMethod
        Order getOrderById(int id);
    }
    OrderWS
    <?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"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
        <!--引入 cxf 的一些核心配置 -->
        <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" />
    
        <!-- Cxf WebService 服务端示例 -->
        <jaxws:endpoint id="orderWS" implementor="com.zhouwuji.ws.impl.OrderWSImpl"
            address="/orderws">
            <jaxws:inInterceptors>
                <!-- 添加cxf日志入拦截器 -->
                   <bean class="org.apache.cxf.interceptor.LoggingInInterceptor" />
                <!-- 自定义cxf拦截器 -->
                   <bean class="com.zhouwuji.intercepter.AuthInterceptor" />
            </jaxws:inInterceptors>
            <jaxws:outInterceptors>
                <ref bean="loggingOutInterceptor" />
            </jaxws:outInterceptors>
        </jaxws:endpoint>
    
        <!-- 添加cxf日志出拦截器 -->
        <bean id="loggingOutInterceptor" class="org.apache.cxf.interceptor.LoggingOutInterceptor" />
    
        <!-- Cxf WebService 客户端示例 <jaxws:client id="demoClient" serviceClass="com.comp.web.webservice.DemoWebservice" 
            address="http://localhost:8080/App/services/demo?wsdl" /> -->
    </beans>
    application-cxf.xml
    <?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_2_5.xsd" id="WebApp_ID" version="2.5">
        
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:application-cxf.xml</param-value>
        </context-param>
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
        <servlet>
            <description>CXF Endpoint</description>
            <display-name>cxf</display-name>
            <servlet-name>cxf</servlet-name>
            <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>cxf</servlet-name>
            <url-pattern>/*</url-pattern>
        </servlet-mapping>
    </web-app>
    web.xml
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.zhouwuji.webservices</groupId>
        <artifactId>webservicesCXF-sptring</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>war</packaging>
        <properties>
        <cxf.version>2.6.2</cxf.version>
       </properties>
         <dependencies>
           <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>3.2.3.RELEASE</version>
            </dependency>
          <dependency>
                    <groupId>org.apache.cxf</groupId>
                    <artifactId>cxf-api</artifactId>
                    <version>${cxf.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.apache.cxf</groupId>
                    <artifactId>cxf-rt-frontend-simple</artifactId>
                    <version>${cxf.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.apache.cxf</groupId>
                    <artifactId>cxf-rt-frontend-jaxws</artifactId>
                    <version>${cxf.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.apache.cxf</groupId>
                    <artifactId>cxf-rt-transports-http</artifactId>
                    <version>${cxf.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.apache.cxf</groupId>
                    <artifactId>cxf-rt-frontend-jaxrs</artifactId>
                    <version>${cxf.version}</version>
                </dependency>
         </dependencies>
    </project>
    pom.xml

    c   页面

    信息: Inbound Message
    ----------------------------
    ID: 1
    Address: http://localhost:8080/webservicesCXF-spring/orderws
    Encoding: UTF-8
    Http-Method: POST
    Content-Type: text/xml;charset=utf-8
    Headers: {Accept=[text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2], cache-control=[no-cache], connection=[keep-alive], Content-Length=[295], content-type=[text/xml;charset=utf-8], host=[localhost:8080], pragma=[no-cache], user-agent=[Java/1.7.0_71]}
    Payload: <soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'><soap:Header><authHeader><userId>wl</userId><password>1985310</password></authHeader></soap:Header><soap:Body><ns2:getOrderById xmlns:ns2='http://ws.zhouwuji.com/'><arg0>1</arg0></ns2:getOrderById></soap:Body></soap:Envelope>
    --------------------------------------


    一月 22, 2018 2:17:24 下午 org.apache.cxf.services.OrderWSImplService.OrderWSImplPort.OrderWS
    信息: Outbound Message
    ---------------------------
    ID: 1
    Encoding: UTF-8
    Content-Type: text/xml
    Headers: {}
    Payload: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ns2:getOrderByIdResponse xmlns:ns2="http://ws.zhouwuji.com/"><return><id>1</id><name>飞机</name><price>122112.0</price></return></ns2:getOrderByIdResponse></soap:Body></soap:Envelope>
    --------------------------------------

  • 相关阅读:
    移动app测试
    centos7中tomcat安装步骤
    linux下搭建数据库
    Linux 学习笔记
    vi编辑器 使用表
    python-Xml 实战
    python-Excel 实战
    手写HashMap
    volatile关键字解析
    两个栈实现队列——优化版
  • 原文地址:https://www.cnblogs.com/ou-pc/p/7497719.html
Copyright © 2011-2022 走看看