WebService-CXF-Spring+自定义拦截器

首先在服务器和客户端都导入CXF和Spring相关的jar包
这里写图片描述
服务器端实现:

服务器目录:
这里写图片描述

实体类:

public class Order {
    private int id;
    private String name;
    private double price;
    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;
    }
    public Order(int id, String name, double price) {
        super();
        this.id = id;
        this.name = name;
        this.price = price;
    }
    public Order() {
        super();
    }
    @Override
    public String toString() {
        return "Order [id=" + id + ", name=" + name + ", price=" + price + "]";
    }


}

WS接口

@WebService
public interface OrderWS {
    @WebMethod
    public Order getOrderById(int id);
}

WS实现类

@WebService
public class OrderWSImpl implements OrderWS {

    public OrderWSImpl() {
        System.out.println("OrderWSImpl()");
    }

    @Override
    public Order getOrderById(int id) {
        System.out.println("Server getOrderById()"+id);
        return new Order(id,"飞机",1000000);
    }

}

自定义检查用户拦截器

package com.lin.ws.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 CherkUserInterceptor extends AbstractPhaseInterceptor<SoapMessage> {

    public CherkUserInterceptor() {
        super(Phase.PRE_PROTOCOL);
        System.out.println("CherkUserInterceptor()...");
    }

    /*
    <Envelope>
        <head>
            <sea>
                <name>jack</name>
                <password>123</password>
            <sea>
        </head>
        <Body>
            <sayHello>
                <arg0>KOK</arg0>
            </sayHello>
        </Body>
    </Envelope>
  */
    @Override
    public void handleMessage(SoapMessage message) throws Fault {
        Header header= message.getHeader(new QName("sea"));
        if(header!=null){
            Element seaEle=(Element) header.getObject();
            String name=seaEle.getElementsByTagName("name").item(0).getTextContent();
            String password=seaEle.getElementsByTagName("password").item(0).getTextContent();
            if("jack".equals(name)&&"123".equals(password)){
                System.out.println("Server 通过拦截器...");
                return;
            }   
        }
        //不能通过
        System.out.println("Server 没有通过拦截器...");
        throw new Fault(new RuntimeException("请求需要一个正确的用户名和密码"));
    }

}

bean.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="orderWS" 
     implementor="com.cxf_spring.ws.OrderWSImpl" 
     address="/orderws">
        <jaxws:inInterceptors>
            <bean class="com.lin.ws.interceptor.CherkUserInterceptor"></bean>
        </jaxws:inInterceptors>
     </jaxws:endpoint>


</beans>

web.xml添加CXF框架和Spring配置

<?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">


  <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>

   <!-- 
    所有请求都会经过CXF框架
    -->
   <servlet>
      <servlet-name>CXFServlet</servlet-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>

客户端实现:
新建一个web工程
创建一个

<?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">
    <jaxws:client id="orderClient" 
        serviceClass="com.cxf_spring.ws.OrderWS" 
        address="http://localhost:8080/WS_cxf_spring/orderws" >
        <jaxws:outInterceptors>
            <bean class="com.lin.ws.interceptor.AddUserInterceptor">
                <constructor-arg name="name" value="jack"/>
                <constructor-arg name="password" value="123"/>
            </bean>
        </jaxws:outInterceptors>
    </jaxws:client>
</beans>

cmd进入客户端的src目录下,运用wsimport -keep http://localhost:8080/WS_cxf_spring/orderws 生成客户端代码
这里写图片描述

客户端拦截器:

package com.lin.ws.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 AddUserInterceptor extends AbstractPhaseInterceptor<SoapMessage> {

    private String name;
    private String password;


    public AddUserInterceptor(String name,String password) {
        super(Phase.PRE_PROTOCOL);//准备协议化时拦截
        this.name=name;
        this.password=password;
        System.out.println("AddUserInterceptor()....");
    }

    /*
        <Envelope>
            <head>
                <sea>
                    <name>jack</name>
                    <password>123</password>
                <sea>
            </head>
            <Body>
                <sayHello>
                    <arg0>KOK</arg0>
                </sayHello>
            </Body>
        </Envelope>
      */
    @SuppressWarnings("deprecation")
    @Override
    public void handleMessage(SoapMessage message) throws Fault {
        /*
         <sea>
            <name>jack</name>
            <password>123</password>
        <sea>
         * */

        List<Header> headers=message.getHeaders();

        Document document=DOMUtils.createDocument();
        Element rootEle=document.createElement("sea");
        Element nameEle=document.createElement("name");
        System.out.println(name);
        nameEle.setTextContent(name);
        rootEle.appendChild(nameEle);

        Element passwordEle=document.createElement("password");
        System.out.println(password);
        passwordEle.setTextContent(password);
        rootEle.appendChild(passwordEle);


        headers.add(new Header(new QName("sea"), rootEle));

        System.out.println("Client handleMessage()....");
    }

}

编写测试类

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.cxf_spring.ws.Order;
import com.cxf_spring.ws.OrderWS;

public class ClientTest {
    public static void main(String[] args) {
         ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]  {"client-beans.xml"});
         OrderWS client = (OrderWS) context. getBean("orderClient");
         Order order=client.getOrderById(24);
         System.out.println(order);
    }

}

运行结果:

服务器:

这里写图片描述

客户端测试:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Radom7

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值