说明:过滤器使用范围还是挺广泛的,比如webservice中的安全认证、数字签名、Token认证都可以使用过滤器来做;下面纯粹是一个小例子,以方便后期使用时查询,仅供参考。以服务端和客户端两部分介绍(所需要包自己导入):
【服务端】
一、定义接口
import javax.jws.WebService; @WebService public interface HelloWorld { public String sayHello(String inputXML); }
二、定义实现类
@WebService(endpointInterface = "com.dyc.dao.HelloWorld") public class HelloWorldImpl implements HelloWorld { @WebMethod public String sayHello(@WebParam(name = "inputXML") String inputXML) { // TODO Auto-generated method stub String name = ParseXml.parseElement(inputXML, "name"); System.out.println("Server接收到输入参数为-->" + name); return "How are you ?-->" + name; } }
三、XML解析类(dom4j,请自导入包)
public class ParseXml { public static String parseElement(String inputXML, String objStr) { InputStream in = null; String str = null; Element rootElement = null; try { in = new ByteArrayInputStream(inputXML.getBytes("UTF-8")); SAXReader reader = new SAXReader(); Document document = reader.read(in); // 把流转成document对象。 rootElement = document.getRootElement(); Element tokenNode = rootElement.element(objStr); if (tokenNode != null) { str = tokenNode.getTextTrim(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } return str; } }
四、过滤器
public class TokenInFilter extends AbstractPhaseInterceptor<SoapMessage> { public TokenInFilter(String phase) { super(Phase.PRE_INVOKE); } public void handleMessage(SoapMessage message) throws Fault { // 获取SOAP消息的全部头 List<Header> headers = message.getHeaders(); if (null == headers || headers.size() < 1) { throw new Fault(new SOAPException("SOAP消息头格式不对哦!")); } try{ for (Header header : headers) { SoapHeader soapHeader = (SoapHeader) header; // 取出SOAP的Header元素 /*解析soap的头信息*/ Element element = (Element) soapHeader.getObject(); XMLUtils.printDOM(element); NodeList tokenList = element .getElementsByTagName("tns:token"); /*NodeList nameList = element .getElementsByTagName("tns:name"); NodeList passList = element .getElementsByTagName("tns:pass");*/ String token = tokenList.item(0).getTextContent(); System.out.println("Token------>"+token); //在此验证Token的合法性 /* System.out.println(nameList.item(0).getTextContent()); System.out.println(passList.item(0).getTextContent());*/ } }catch(Exception e){ throw new Fault(new SOAPException("解析Soap信息出错!")); } } }
五、XML配置
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <context-param> <param-name>contextConfigLocation</param-name> <param-value>WEB-INF/beans_*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <display-name>cxf</display-name> <servlet> <servlet-name>cxf</servlet-name> <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>cxf</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> <session-config> <session-timeout>60</session-timeout> </session-config> </web-app>
六、bean_1.xml:用来发布服务的配置
<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" /> <!-- 自定义拦截器 --> <bean id="authIntercetpr" class="com.dyc.filter.TokenInFilter"> <constructor-arg value="receive" /> </bean> <jaxws:endpoint id="helloWorld" implementor="com.dyc.impl.HelloWorldImpl" address="/HelloWorld"> <jaxws:inInterceptors> <!-- 进入webservice之前的拦截器 --> <ref bean="authIntercetpr" /> </jaxws:inInterceptors> </jaxws:endpoint>
【客户端】
一、利用wsdl2java生成客户端代码(省略,代码太多了)
例:wsdl2java -p com.dyc.client -d d:/ws -verbose http://localhost:6888/webgisplatform/BaseService?wsdl
二、将生成的代码导入一个工程,可以建任意一个java工程
三、生成AddSoapHeader,模拟生成一个soap的头信息
public class AddSoapHeader extends AbstractSoapInterceptor { private static String nameURI="http://localhost:8080/cxf_filter/HelloWorld"; public AddSoapHeader(){ super(Phase.WRITE); } public void handleMessage(SoapMessage message) throws Fault { String token="12345678956789123344444"; QName qname=new QName("RequestSOAPHeader"); Document doc=DOMUtils.createDocument(); //自定义节点 Element spId=doc.createElement("tns:token"); spId.setTextContent(token); Element username=doc.createElement("tns:name"); username.setTextContent("gary"); Element password=doc.createElement("tns:pass"); password.setTextContent("123456"); Element root=doc.createElementNS(nameURI, "tns:RequestSOAPHeader"); root.appendChild(spId); root.appendChild(username); root.appendChild(password); SoapHeader head=new SoapHeader(qname,root); List<Header> headers=message.getHeaders(); headers.add(head); System.out.println(">>>>>添加header<<<<<<<"); } }
四、写一个调试入口main方法
public void testSend() { try { JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); List<Interceptor<? extends Message>> list = new ArrayList<Interceptor<? extends Message>>(); // 添加soap header list.add(new AddSoapHeader()); // 添加soap消息日志打印 list.add(new org.apache.cxf.interceptor.LoggingOutInterceptor()); factory.setOutInterceptors(list); factory.setServiceClass(HelloWorld.class); factory .setAddress("http://localhost:8080/cxf_filter/HelloWorld"); Object obj = factory.create(); System.out.println(obj == null ? "NULL" : obj.getClass().getName()); if (obj != null) { HelloWorld ws = (HelloWorld) obj; String name = Dom4jDemo.createDocument(""); System.out.println(name); // 1、获取连接 String str = ws.sayHello(name) ; System.out.println("res--->" + str); } } catch (Exception ex) { ex.printStackTrace(); } } public static void main(String[] args) { Test tc = new Test(); tc.testSend(); }
OK!发布好服务端,启动服务,可以测试了!