(二)CXF使用HANDLER处理头信息

使用CXF可以很方便的在客户端使用Handler增加头信息,只需在调用服务前设置到proxyBean中即可;

在服务端也可以很方便的使用Handler来解析头信息,只需要在开启服务前设置到factoryBean中即可;

 

服务端:

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.hqh.ws.cxf</groupId>
	<artifactId>cxf-first</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>cxf-first</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<cxf.version>2.6.0</cxf.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.10</version>
			<scope>test</scope>
		</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>
		<!-- Jetty is needed if you're are not using the CXFServlet -->
		<dependency>
			<groupId>org.apache.cxf</groupId>
			<artifactId>cxf-rt-transports-http-jetty</artifactId>
			<version>${cxf.version}</version>
		</dependency>
	</dependencies>

</project>

 

接口

package com.hqh.ws.cxf;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;

@WebService
public interface IMyService {

	@WebMethod
	@WebResult(name="sayResult")
	public String sayHello(@WebParam(name="name") String name);
}

 

实现类

package com.hqh.ws.cxf;

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

@WebService(endpointInterface="com.hqh.ws.cxf.IMyService")
public class MyServiceImpl implements IMyService {

	@Override
	@WebMethod
	public String sayHello(String name) {
		return  "你好:"+name ;
	}

}

 

解析头信息的Handler

package com.hqh.ws.cxf.handler;

import java.util.Iterator;
import java.util.Set;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPHeaderElement;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

public class LicenseHandler implements SOAPHandler<SOAPMessageContext> {

	@Override
	public boolean handleMessage(SOAPMessageContext context) {
		boolean out = (Boolean)context.get(SOAPMessageContext.MESSAGE_OUTBOUND_PROPERTY);
		try {
			//进入的消息,则检查HEADER
			if(!out) {
				SOAPEnvelope env = context.getMessage().getSOAPPart().getEnvelope();
				SOAPHeader header = env.getHeader();
				SOAPBody body = env.getBody();
				if(header == null) {
					return true;
				}
				//Iterator<SOAPHeaderElement> iter = header.getChildElements();
				Iterator<SOAPHeaderElement> iter = header.extractAllHeaderElements();
				String license = "";
				while(iter.hasNext()) {
					SOAPHeaderElement headerEle = iter.next();
					if(headerEle.getLocalName().equals("license")) {
						license = headerEle.getTextContent();
						System.out.println("获取到头信息:"+license);
						break;
					}
				}
				System.out.println(license);
			}
		} catch (SOAPException e) {
			e.printStackTrace();
		}
		return true;
	}

	@Override
	public boolean handleFault(SOAPMessageContext context) {
		return false;
	}

	@Override
	public void close(MessageContext context) {
		
	}

	@Override
	public Set<QName> getHeaders() {
		return null;
	}

}

 

开启服务

package com.hqh.ws.cxf;

import java.util.ArrayList;
import java.util.List;

import javax.xml.ws.Endpoint;
import javax.xml.ws.handler.Handler;

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

import com.hqh.ws.cxf.handler.LicenseHandler;

public class MyServer {

	public static void main(String[] args) {
		//startServer();
		startServerByCXF(); 
	}
	/**
	 * 基于JAX-WS的方式发布服务
	 * @param args
	 */
	public static void startServer() {
		Endpoint.publish("http://localhost:8888/cxf/ws", new MyServiceImpl());
	}
	
	/**
	 * 使用CXF发布服务
	 */
	public static void startServerByCXF() {
		JaxWsServerFactoryBean svrFactory = new JaxWsServerFactoryBean();
		svrFactory.setServiceClass(IMyService.class);
		svrFactory.setAddress("http://localhost:8888/cxf/ws");
		svrFactory.setServiceBean(new MyServiceImpl());
		//打印发出的消息
		svrFactory.getInInterceptors().add(new LoggingInInterceptor());
		//打印进入的消息
		svrFactory.getOutInterceptors().add(new LoggingOutInterceptor());
		
		/**
		 * 加入服务端的Handler处理客户端传递的头信息
		 */
		List<Handler> handlers = new ArrayList<Handler>();
		handlers.add(new LicenseHandler());
		svrFactory.setHandlers(handlers);
		
		svrFactory.create();
	}
}

 

 

 

客户端:

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.hqh.ws.cxf</groupId>
  <artifactId>cxf-client</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>cxf-client</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <cxf.version>2.6.0</cxf.version>
  </properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.10</version>
			<scope>test</scope>
		</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>
	</dependencies>
  
  	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.cxf</groupId>
				<artifactId>cxf-codegen-plugin</artifactId>
				<version>${cxf.version}</version>
				<executions>
					<execution>
						<id>generate-sources</id>
						<phase>generate-sources</phase>
						<configuration>
							<sourceRoot>${project.build.directory}/generated/cxf</sourceRoot>
							<wsdlOptions>
								<wsdlOption>
									<wsdl>http://localhost:8888/cxf/ws?wsdl</wsdl>
								</wsdlOption>
							</wsdlOptions>
						</configuration>
						<goals>
							<goal>wsdl2java</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>

 

通过wsdl2java转换wsdl为本地java文件

 

通过Handler加入头信息

package com.hqh.ws.cxf.handler;

import java.util.Set;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;


public class LicenseHandler implements SOAPHandler<SOAPMessageContext> {

	@Override
	public boolean handleMessage(SOAPMessageContext context) {
		try {
			boolean out = (Boolean)context.get(SOAPMessageContext.MESSAGE_OUTBOUND_PROPERTY);
			//发送消息则加入头信息
			if(out) {
				SOAPEnvelope soapEnv = context.getMessage().getSOAPPart().getEnvelope();
				SOAPBody soapBody = soapEnv.getBody();
				//获取当前访问服务的哪个方法
				String localName = soapBody.getChildNodes().item(0).getLocalName();
				//指定对哪些方法需要加入头信息
				if(localName != "") {
					System.out.println("当前调用的方法:"+localName);
					SOAPHeader soapHeader = soapEnv.getHeader();
					if(soapHeader==null) {
						soapHeader = soapEnv.addHeader();
					}
					//创建QName
					String namespaceURI = "http://ws.cxf.hqh.com";
					String localPart = "license";
					String prefix = "nn";
					QName qname = new QName(namespaceURI,localPart,prefix);
					//加入消息到HEADER中
					soapHeader.addHeaderElement(qname).setValue("EJ8923D");
				}
			}
			return true;
		} catch (SOAPException e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean handleFault(SOAPMessageContext context) {
		return false;
	}

	@Override
	public void close(MessageContext context) {
		
	}

	@Override
	public Set<QName> getHeaders() {
		return null;
	}

}

 

测试单元

@Test
	public void test02() {
		JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
		factory.setServiceClass(IMyService.class);
		factory.setAddress("http://localhost:8888/cxf/ws?wsdl");
		//打印发出的消息
		factory.getInInterceptors().add(new LoggingInInterceptor());
		//打印进入的消息
		factory.getOutInterceptors().add(new LoggingOutInterceptor());
		
		/**
		 * 加入HANDLER
		 */
		List<Handler> licenseHandlerList = new ArrayList<Handler>();
		licenseHandlerList.add(new LicenseHandler());
		factory.setHandlers(licenseHandlerList);
		
		//获取服务对象
		IMyService service = (IMyService)factory.create();
		//调用服务
		String reply = service.sayHello("李思思");
		
		System.out.println(reply);
		System.exit(0);
	}

 

 

你可能感兴趣的:(handler)