继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

使用cxf框架整合WebService和Sping

爱总结的小仙女
关注TA
已关注
手记 47
粉丝 57
获赞 437

项目路径(导入cxf的jar包)服务端
图片描述

使用@WebService和@WebMethod创建SEI接口

package com.test.spring;

import javax.jws.WebMethod;
import javax.jws.WebService;

import com.test.spring.bean.OrderModel;
@WebService
public interface OrderWs {
    @WebMethod
    public OrderModel getOrderMes(int id);

}

实体对象类

package com.test.spring.bean;

public class OrderModel {

    private Integer id;
    private String name;
    private double prices;
    public OrderModel(Integer id, String name, double prices) {
        super();
        this.id = id;
        this.name = name;
        this.prices = prices;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getPrices() {
        return prices;
    }
    public void setPrices(double prices) {
        this.prices = prices;
    }
    @Override
    public String toString() {
        return "OrderModel [id=" + id + ", name=" + name + ", prices=" + prices + "]";
    }

}

接口实现类

package com.test.spring.impl;

import javax.jws.WebService;

import com.test.spring.OrderWs;
import com.test.spring.bean.OrderModel;
@WebService
public class OrderWsImpl implements OrderWs {

    @Override
    public OrderModel getOrderMes(int id) {
        System.out.println("Server"+id);
        return new OrderModel(id,"飞机",234.6);
    }

}

创建服务端入拦截器

package com.test.interceptor;

import javax.xml.namespace.QName;

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;

public class InterceptorTest extends AbstractPhaseInterceptor<SoapMessage>{

    public InterceptorTest() {
        super(Phase.PRE_PROTOCOL);
    }

    @Override
    public void handleMessage(SoapMessage arg0) throws Fault {
        Header header=arg0.getHeader(new QName("root"));
        if (null!=header) {
            Element e =(Element) header.getObject();
            String name = e.getElementsByTagName("name").item(0).getTextContent();
            String pwd = e.getElementsByTagName("pwd").item(0).getTextContent();
            if ("lmy".equals(name) && "123".equals(pwd)) {

            }else{
                System.out.println("3244355");
            }
        }
        //服务端不能通过
        else{
            //throw new Fault(new RuntimeException("请求需要一个正确的用户名和密码"));
            System.out.println(111);
        }
    }

}

服务端配置文件beans.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"
 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">
 <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" /> 
 <jaxws:endpoint id="orderProcess" implementor="com.test.spring.impl.OrderWsImpl" address="/OrderProcess">
    <jaxws:inInterceptors>
            <bean class="com.test.interceptor.InterceptorTest"></bean>
     </jaxws:inInterceptors>  
 </jaxws:endpoint>
</beans>

服务端web.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_3_0.xsd" metadata-complete="false" version="3.0">

 <context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>classpath:beans.xml</param-value>
 </context-param>

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

 <!-- 所有请求都会经过CXFServlet -->
 <servlet>
 <servlet-name>CXFServlet</servlet-name>
 <display-name>CXF Servlet</display-name>
 <servlet-class>
 org.apache.cxf.transport.servlet.CXFServlet
 </servlet-class>
 <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
 <servlet-name>CXFServlet</servlet-name>
 <url-pattern>/*</url-pattern>
 </servlet-mapping>
</web-app>

客户端项目路径
图片描述

使用jdk生成客户端代码步骤
1.输入cmd
2.切换到项目的src目录下
3.wsimport -keep wsdl路径 生成(环境变量要配置成功)
4.刷新项目,出现客户端代码
使用cxf生成客户端代码
一、设置环境变量

1、CXF_HOME=D:\apache-cxf-2.7.10

2、在path后面加上 %CXF_HOME%/bin;

在cmd命令中输入wsdl2java,如果有提示usage,就表明配置成功

二、运行wsdl2java工具

在cmd命令中输入:wsdl2java -d D:\src -client http://api.xxx.cn/xxxAPI/service/auditResBatchQueryService?wsdl

(D:\src 是客户端程序代码所在的目录,http://api.xxx.cn/xxxAPI/service/auditResBatchQueryService?wsdl 是 定义webservice的地址)

附wsdl2java用法:

wsdl2java -p com -d D:\src -all xx.wsdl

-p 指定其wsdl的命名空间,也就是要生成代码的包名:

-d 指定要产生代码所在目录

-client 生成客户端测试web service的代码

-server 生成服务器启动web service的代码

-impl 生成web service的实现代码

-ant 生成build.xml文件

-all 生成所有开始端点代码:types,service proxy,,service interface, server mainline, client mainline, implementation object, and an Ant build.xml file.

client-beans.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"
   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/jaxws">
<jaxws:client id="orderClient" serviceClass="com.test.spring.impl.OrderWs" address="http://localhost:8080/WsSpringServer/OrderProcess" >
    <jaxws:outInterceptors>
            <bean class="org.apache.cxf.interceptor.LoggingOutInterceptor"/>
            <bean class="com.test.interseptor.InterseptorTest">
                <constructor-arg  name="name" value="lmy"></constructor-arg>
                <constructor-arg  name="pwd"  value="123"/>
            </bean>
    </jaxws:outInterceptors>
</jaxws:client>
</beans>

发送请求的类

package com.test.spring.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.test.spring.OrderModel;
import com.test.spring.impl.OrderWs;

public class WsSpringClientTest {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context  = new ClassPathXmlApplicationContext(new String[]{"client-beans.xml"});
        OrderWs orderWs=(OrderWs)context.getBean("orderClient");
        //发送请求
        OrderModel orderModel =orderWs.getOrderMes(24);
        System.out.println(orderModel);
    }

}

客户端出拦截器

package com.test.interseptor;

import java.util.List;

import javax.xml.bind.annotation.DomHandler;
import javax.xml.namespace.QName;

import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.xml.utils.DOMHelper;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class InterseptorTest extends AbstractPhaseInterceptor<SoapMessage> {
    private String name;
    private String pwd;
    public InterseptorTest(String name,String pwd) {
        super(Phase.PRE_PROTOCOL);//确定了拦截的时间,准备协议化的时候调用
        this.name=name;
        this.pwd=pwd;
    }
    @Override
    public void handleMessage(SoapMessage arg0) throws Fault {
        List<Header> list  = arg0.getHeaders();
        Document d =DOMHelper.createDocument();
        Element e =d.createElement("root");
        Element nameEle =d.createElement("name");
        nameEle.setTextContent(name);
        e.appendChild(nameEle);
        Element pwdEle =d.createElement("pwd");
        pwdEle.setTextContent(pwd);
        e.appendChild(pwdEle);
        list.add(new Header(new QName("root"),e));
    }

}

使用ajax请求和jquery请求(页面代码)

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!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="jquery-1.7.2.js"></script>
<script type="text/javascript">

    $(function(){

    /*  $("#btn2").click(function(){
            var name = document.getElementById("name").value;
            $.post(
                "HttpURLConnectionServlet",
                "name="+name,
                function(msg) {
                    //alert(msg);
                    var $Result = $(msg);
                    var value = $Result.find("return").text();
                    alert(value);
                },
                "xml"
            );
        }); */

        $("#btn").click(function(){ //回调函数
            var name = document.getElementById("name").value;
            var data = ' <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ns2:getOrderMes xmlns:ns2="http://spring.test.com/"><arg0>'+name+'</arg0></ns2:getOrderMes></soap:Body></soap:Envelope>';
            $.ajax({
                type : "post",
                url : "http://localhost:8080/WsSpringServer/OrderProcess",
                data : data,
                success : function(msg){
                    alert("------");
                    var $Result = $(msg);
                    var value = $Result.find("return").children("id").text();
                    alert(value);
                },
                error : function(msg) {
                    //alert("-----"+msg);
                },
                dataType : "xml"
            });
        });
    });

     function reqWebService() {
        var name = document.getElementById("name").value;
//请求的数据
        var data = ' <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ns2:getOrderMes xmlns:ns2="http://spring.test.com/"><arg0>'+name+'</arg0></ns2:getOrderMes></soap:Body></soap:Envelope>';
        //XMLHttpRequest对象
        var request = getRequest();
        request.onreadystatechange = function(){
            if(request.readyState==4 && request.status==200) {
                var result = request.responseXML;
                console.log(result);
                var returnEle = result.getElementsByTagName("return")[0];
                var value = returnEle.childNodes[0];
                alert(value.childNodes[0].nodeValue);
            }
        };

        request.open("POST", "http://localhost:8080/WsSpringServer/OrderProcess");//请求的路径

        request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

        request.send(data);
    }

    function getRequest() {
        var xmlHttp = null;
        try {
            // Firefox, Opera 8.0+, Safari  chrome
            xmlHttp = new XMLHttpRequest();
        } catch (e) {
            // Internet Explorer
            try {
                xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
        }
        return xmlHttp;
    } 
</script>
</head>
<body>
    用户名:
    <input id="name" name="username" value="" />
    <br>
    <button onclick="reqWebService()">AJax请求webservice</button>
    <button id="btn">Jquery请求webservice</button>
    <!-- <button id="btn2">HttpURLConnection请求webservice</button> -->

</body>
</html>
打开App,阅读手记
6人推荐
发表评论
随时随地看视频慕课网APP