cxf+soap验证 简单例子(TOMCAT+SPRING)

实现效果:
1、在tomcat下通过集成spring和CXF与项目一同发布webservice
2、调用时启用soap访问验证

准备工作:
发布WS的工程需要集成spring,并且是在tomcat下发布;
因为CXF的包里也有spring的包,为了避免spring的包的冲突,将CXF中spring*.jar全部丢弃。


一、发布WS的工程配置

1、webservice代码
WShello.java
import javax.jws.WebService;

    /**
	 * webservice
	 */
	@WebService(targetNamespace = "${url}/${projectName}/ws")
         //例:http://site/hello/ws
	@SOAPBinding(style = SOAPBinding.Style.DOCUMENT)
	public class WSHello {

		/**
		 * 返回c125543072
		 */
		@WebMethod
		public String hello(BaseShopInfo shop) throws DBException,
				DaoException, ServiceException, WebServiceException {
			return "c125543072";
		}
	}



2、soap头验证器
SoapHander.java
import java.util.Set;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
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;

/**
	 * soap头验证器
	 */
	public class SoapHander implements SOAPHandler<SOAPMessageContext> {

		public boolean handleMessage(SOAPMessageContext messageContext) {
			try {
				Boolean outMessageIndicator = (Boolean) messageContext
						.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
				if (!outMessageIndicator.booleanValue()) {
					SOAPHeader soapHeader = messageContext.getMessage()
							.getSOAPHeader();
					if (soapHeader != null) {
						NodeList nodeList = soapHeader.getChildNodes();
						// 定义key 接受验证码
						String key = "";

						// 从soap头中取得权限验证码
						for (int i = 0; i < nodeList.getLength(); i++) {
							Node node = nodeList.item(i);

							if (node.getNodeName().equals("header")) {
								NodeList childNodeList = node.getChildNodes();
								for (int c = 0; c < childNodeList.getLength(); c++) {
									if (childNodeList.item(c).getNodeName().equals(
											"header")) {
										key = childNodeList.item(c)
												.getTextContent();
									}
								}
								break;
							}
							
							if(key.equals("c125543072")){
								return true;
							}else{
								return false;
								}
							}
						}
					}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return false;
		}

		public boolean handleFault(SOAPMessageContext messageContext) {

			// messageContext.getHeaders(header, context, allRoles)
			return true;
		}

		public Set<QName> getHeaders() {
			// TODO Auto-generated method stub
			return null;
		}

		public void close(MessageContext context) {
			// TODO Auto-generated method stub

		}
	}


3、cxfBeans.xml
	<?xml version="1.0" encoding="UTF-8"?>
	<!-- START SNIPPET: beans -->
<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">
	
	<bean id="wsSoapHander" class="****.SoapHander" />

	<!-- WS -->
	<jaxws:endpoint id="wsHello"
		implementor="*****.WSHello"
		address="/WSHello">
		<jaxws:handlers>
			<ref bean="wsSoapHander" />
		</jaxws:handlers>
	</jaxws:endpoint>
</beans>



4、applicationContext.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:context="http://www.springframework.org/schema/context"
		xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
		xsi:schemaLocation="http://www.springframework.org/schema/beans   
	           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
	           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd   
	           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
	           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.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" />
import resource="cxfBeans.xml" />
	</beans>


5、web.xml
	<!-- Spring Context文件 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>WEB-INF/classes/applicationContext.xml</param-value>
	</context-param>
	<!-- Spring 监听器 -->
	<listener>
		<listener-class>
			org.springframework.web.context.ContextLoaderListener
		</listener-class>
	</listener>
	<!-- CXF 处理器Servlet 定义-->
	<servlet>
		<servlet-name>CXFServlet</servlet-name>
		<servlet-class>
			org.apache.cxf.transport.servlet.CXFServlet
		</servlet-class>
	</servlet>
	<!-- CXF 处理器Servlet 映射 -->
	<servlet-mapping>
		<servlet-name>CXFServlet</servlet-name>
		<url-pattern>/ws/*</url-pattern>
	</servlet-mapping>



二、调用WS

编写:ws.bat文件以便下载WS,内容:
wsimport -d ./src -p webservice.remote.wsHello -keep -Xnocompile  http://${ip}:{port}/${projectName}/ws/WSHello?wsdl

6、启动tomcat后,下载WS到项目中
   将WS.BAT放到工程的根目录下(和SRC,WEBROOT同级),运行


7、创建访问验证内容

7.1:SoapHeaderHandler.java
import java.util.Set;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
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 SoapHeaderHandler implements SOAPHandler<SOAPMessageContext> {
	
	public boolean handleMessage(SOAPMessageContext messageContext) {
		try {
			Boolean outMessageIndicator = (Boolean) messageContext
					.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
			if (outMessageIndicator.booleanValue()) {
				SOAPEnvelope evelope = messageContext.getMessage()
						.getSOAPPart().getEnvelope();
				SOAPHeader header = evelope.addHeader();
				SOAPElement authHeaderEle = header.addChildElement(
						"header", "",
						"${url}/${projectName}/ws");

				
				SOAPElement keyEle = authHeaderEle
						.addChildElement("header");
				keyEle.addTextNode("c125543072");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}

	public boolean handleFault(SOAPMessageContext messageContext) {

		// messageContext.getHeaders(header, context, allRoles)
		return true;
	}

	public Set<QName> getHeaders() {
		// TODO Auto-generated method stub
		return null;
	}

	public void close(MessageContext context) {
		// TODO Auto-generated method stub

	}
	


7.2:HeaderHandlerResolver.java

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

import javax.xml.ws.handler.Handler;
import javax.xml.ws.handler.HandlerResolver;
import javax.xml.ws.handler.PortInfo;

public class HeaderHandlerResolver implements HandlerResolver {

	@SuppressWarnings("unchecked")
	@Override
	public List<Handler> getHandlerChain(PortInfo portInfo) {
		List<Handler> handlerChain=new ArrayList<Handler>();
		SoapHeaderHandler handler=new SoapHeaderHandler();
		
		handlerChain.add(handler);
		return handlerChain;
	}

}




8、创建WS调用
WebServiceFactory.java
import java.net.URL;
	import java.util.Properties;

	import javax.xml.namespace.QName;
	public class WebServiceFactory {

	/**
	 * 创建WSHELLO调用
	 */
	public static WSHello createWSHello() {
			WSHelloService ws = new WSHelloService(getServiceUrl("WSHello"),
				getServiceQName("WSHello"));
		ws.setHandlerResolver(new HeaderHandlerResolver());
		return ws.getWSHelloPort();
	}

	/**
	 * 获取ServiceUrl
	 * 
	 * @param WebServiceName
	 * @return Java.net.ULR
	 */
	public static URL getServiceUrl(String wsName) {
		URL url = null;
		try {
			url = new URL("${url} + /${projectName}/ws/"
					+ wsName + "?wsdl");
		} catch (Exception e) {
			e.printStackTrace();
		}

		return url;
	}

	/**
	 * 获取ServiceQName
	 * 
	 * @param WebServiceName
	 * @return javax.xml.namespace.QName
	 */
	public static QName getServiceQName(String wsName) {
		return new QName("${url} + /${projectName}/ws", wsName + "Service");
	}


9、调用ws
system.out.println(WebServiceFactory.createWSHello.hello());
	
	输出结果:c125543072

你可能感兴趣的:(spring,tomcat,xml,webservice,SOAP)