欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

CXF拦截器和自定义拦截器

程序员文章站 2022-04-02 16:15:44
...
1. CXF添加拦截器

webservice分服务端和客户端,服务端和客户端都是可以加拦截器的,无论是服务端还是客户端,都分进,出(In,Out)拦截器;

Server.java

package com.andrew.server;

import javax.xml.ws.Endpoint;

import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.JaxWsServerFactoryBean;

import com.andrew.webservice.HelloWorld;
import com.andrew.webservice.impl.HelloWorldImpl;

public class Server {
    public static void main(String[] args) {
        System.out.println("web service start");
        HelloWorld implementor = new HelloWorldImpl();
        String address = "http://192.168.18.2/helloWorld";
        // 1. 使用JDK实现
        // Endpoint.publish(address, implementor);
        // 2. 使用CXF实现
        JaxWsServerFactoryBean factoryBean = new JaxWsServerFactoryBean();
        factoryBean.setAddress(address); // 设置暴露地址
        factoryBean.setServiceClass(HelloWorld.class); // 接口类
        factoryBean.setServiceBean(implementor); // 设置实现类
        factoryBean.getInInterceptors().add(new LoggingInInterceptor()); // 添加in拦截器 日志拦截器
        factoryBean.getOutInterceptors().add(new LoggingOutInterceptor()); // 添加out拦截器
        factoryBean.create();
        System.out.println("web service started");
    }
}

Inbound进信息,Outbound是出信息


pom.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.andrew.webservice</groupId>
  <artifactId>WS_Client</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <dependencies>
      <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-core</artifactId>
        <version>3.1.5</version>
    </dependency>
      <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-frontend-jaxws</artifactId>
        <version>3.1.5</version>
    </dependency>
    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-transports-http-jetty</artifactId>
        <version>3.1.5</version>
    </dependency>
  </dependencies>
</project>

Client.java

package com.andrew.client;

import java.util.List;

import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;

import com.andrew.webservice.HelloWorld;
import com.andrew.webservice.HelloWorldService;
import com.andrew.webservice.MyRole;
import com.andrew.webservice.MyRoleArray;
import com.andrew.webservice.Role;
import com.andrew.webservice.User;

public class Client {
    public static void main(String[] args) {
        HelloWorldService service = new HelloWorldService();
        HelloWorld helloWorld = service.getHelloWorldPort();
        org.apache.cxf.endpoint.Client client = ClientProxy.getClient(helloWorld);
        client.getInInterceptors().add(new LoggingInInterceptor()); // 添加in拦截器 日志拦截器
        client.getOutInterceptors().add(new LoggingOutInterceptor()); // 添加out拦截器
        System.out.println(helloWorld.say("andrew"));
        User user = new User();
        user.setUserName("tony");
        user.setPassword("123456");
        List<Role> roleList = helloWorld.getRoleByUser(user);
        for (Role role : roleList) {
            System.out.println(role.getId() + "," + role.getRoleName());
        }
        MyRoleArray array = helloWorld.getRoles();
        List<MyRole> roleList2 = array.getItem();
        for(int i = 0; i < roleList2.size(); i++){
            MyRole my = roleList2.get(i);
            System.out.print(my.getKey() + ":");
            for(Role r : my.getValue()){
                System.out.print(r.getId() + "," + r.getRoleName() + " ");
            }
            System.out.println();
        }
    }
}

Inbound进信息,Outbound是出信息


2. CXF添加自定义拦截器

MyInterceptor.java

package com.andrew.interceptor;

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 MyInterceptor extends AbstractPhaseInterceptor<SoapMessage>{

    public MyInterceptor() {
        super(Phase.PRE_INVOKE);
    }
 
    public void handleMessage(SoapMessage message) throws Fault {
        List<Header> headers = message.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("userName");
        NodeList userPasses = ele.getElementsByTagName("password");
        if (userIds.getLength() != 1) {
            throw new Fault(new IllegalArgumentException("用户名格式不对"));
        }
        if (userPasses.getLength() != 1) {
            throw new Fault(new IllegalArgumentException("密码格式不对"));
        }
        String userId = userIds.item(0).getTextContent();
        String userPass = userPasses.item(0).getTextContent();
        if (!userId.equals("tony") || ! userPass.equals("123456")) {
            throw new Fault(new IllegalArgumentException("用户名或者密码不正确"));
        }
    }
}

Server.java

package com.andrew.server;

import javax.xml.ws.Endpoint;

import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.JaxWsServerFactoryBean;

import com.andrew.interceptor.MyInterceptor;
import com.andrew.webservice.HelloWorld;
import com.andrew.webservice.impl.HelloWorldImpl;

public class Server {
    public static void main(String[] args) {
        System.out.println("web service start");
        HelloWorld implementor = new HelloWorldImpl();
        String address = "http://192.168.18.2/helloWorld";
        // 1. 使用JDK实现
        // Endpoint.publish(address, implementor);
        // 2. 使用CXF实现
        JaxWsServerFactoryBean factoryBean = new JaxWsServerFactoryBean();
        factoryBean.setAddress(address); // 设置暴露地址
        factoryBean.setServiceClass(HelloWorld.class); // 接口类
        factoryBean.setServiceBean(implementor); // 设置实现类
        factoryBean.getInInterceptors().add(new LoggingInInterceptor()); // 添加in拦截器 日志拦截器
        factoryBean.getOutInterceptors().add(new LoggingOutInterceptor()); // 添加out拦截器
        factoryBean.getInInterceptors().add(new MyInterceptor()); // 添加自定义拦截器
        factoryBean.create();
        System.out.println("web service started");
    }
}


1) cmd
2) cd E:\studyWEBSERVICECXF\WS_Client\src\main\java
3) wsdl2java http://192.168.18.2/helloWorld?wsdl


AddHeaderInterceptor.java

package com.andrew.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 userName;
    private String password;
    public AddHeaderInterceptor(String userName, String password) {
        super(Phase.PREPARE_SEND); // 发送SOAP消息之前调用拦截器
        this.userName = userName;
        this.password = password;
    }
    public void handleMessage(SoapMessage message) throws Fault {
        List<Header> headers=message.getHeaders();
        Document doc=DOMUtils.createDocument();
        Element ele=doc.createElement("authHeader");
        Element idElement=doc.createElement("userName");
        idElement.setTextContent(userName);
        Element passElement=doc.createElement("password");
        passElement.setTextContent(password);
        ele.appendChild(idElement);
        ele.appendChild(passElement);
        headers.add(new Header(new QName("tony"),ele));
    }
}

Client.java

package com.andrew.client;

import java.util.List;

import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;

import com.andrew.interceptor.AddHeaderInterceptor;
import com.andrew.webservice.HelloWorld;
import com.andrew.webservice.HelloWorldService;
import com.andrew.webservice.MyRole;
import com.andrew.webservice.MyRoleArray;
import com.andrew.webservice.Role;
import com.andrew.webservice.User;

public class Client {
    public static void main(String[] args) {
        HelloWorldService service = new HelloWorldService();
        HelloWorld helloWorld = service.getHelloWorldPort();
        org.apache.cxf.endpoint.Client client = ClientProxy.getClient(helloWorld);
        // client.getInInterceptors().add(new LoggingInInterceptor()); // 添加in拦截器 日志拦截器
        client.getOutInterceptors().add(new AddHeaderInterceptor("tony","123456")); // 添加自定义拦截器
        client.getOutInterceptors().add(new LoggingOutInterceptor()); // 添加out拦截器
        System.out.println(helloWorld.say("andrew"));
        User user = new User();
        user.setUserName("tony");
        user.setPassword("123456");
        List<Role> roleList = helloWorld.getRoleByUser(user);
        for (Role role : roleList) {
            System.out.println(role.getId() + "," + role.getRoleName());
        }
        MyRoleArray array = helloWorld.getRoles();
        List<MyRole> roleList2 = array.getItem();
        for(int i = 0; i < roleList2.size(); i++){
            MyRole my = roleList2.get(i);
            System.out.print(my.getKey() + ":");
            for(Role r : my.getValue()){
                System.out.print(r.getId() + "," + r.getRoleName() + " ");
            }
            System.out.println();
        }
    }
}

如果密码改成123则报错
相关标签: webservice