CXF 入门:创建一个基于SOAPHeader的安全验证(CXF拦截器使用)

CXF 入门:HelloWorld接口发布

CXF 入门: 远程接口调用

 

下面具体的webservice实现类直接用的是上面的,这里不再说明

 

Java代码   收藏代码
  1. CXF拦截器使用,创建一个使用SOAPHeader的安全验证  
  2. xml格式:  
  3. <soap:Header>  
  4.     <auth:authentication xmlns:auth="http://gd.chinamobile.com//authentication">  
  5.         <auth:systemID>1</auth:systemID>  
  6.         <auth:userID>test</auth:userID>  
  7.         <auth:password>test</auth:password>  
  8.     </auth:authentication>  
  9. </soap:Header>  
  10.   
  11. 一,首先在服务端创建一个拦截器(被调用端),需要继承org.apache.cxf.phase.AbstractPhaseInterceptor  
  12. 代码如下:  
  13.   
  14. import java.util.List;  
  15.   
  16. import javax.xml.soap.SOAPException;  
  17.   
  18. import org.apache.cxf.binding.soap.SoapHeader;  
  19. import org.apache.cxf.binding.soap.SoapMessage;  
  20. import org.apache.cxf.headers.Header;  
  21. import org.apache.cxf.helpers.XMLUtils;  
  22. import org.apache.cxf.interceptor.Fault;  
  23. import org.apache.cxf.phase.AbstractPhaseInterceptor;  
  24. import org.apache.cxf.phase.Phase;  
  25. import org.apache.log4j.Logger;  
  26. import org.w3c.dom.Element;  
  27. import org.w3c.dom.NodeList;  
  28.   
  29.   
  30. public class AuthIntercetpr extends AbstractPhaseInterceptor<SoapMessage> {  
  31.     private static final Logger logger = Logger.getLogger(AuthIntercetpr.class);  
  32.     public static final String xml_namespaceUR_att = "http://gd.chinamobile.com//authentication";  
  33.     public static final String xml_header_el = "soap:Header";  
  34.     public static final String xml_authentication_el = "auth:authentication";  
  35.     public static final String xml_systemID_el = "auth:systemID";  
  36.     public static final String xml_userID_el = "auth:userID";  
  37.     public static final String xml_password_el = "auth:password";  
  38.     public AuthIntercetpr() {  
  39.         // 指定该拦截器在哪个阶段被激发  
  40.         super(Phase.PRE_INVOKE);  
  41.     }  
  42.   
  43.     // 处理消息  
  44.     public void handleMessage(SoapMessage message) {  
  45.         logger.info("==================SoapMessage =" + message);  
  46.         // 获取SOAP消息的全部头  
  47.         List<Header> headers = message.getHeaders();  
  48.   
  49.         if (null == headers || headers.size() < 1) {  
  50.             throw new Fault(new SOAPException("SOAP消息头格式不对哦!"));  
  51.         }  
  52.         for (Header header : headers) {  
  53.             SoapHeader soapHeader = (SoapHeader) header;  
  54.             // 取出SOAP的Header元素  
  55.             Element element = (Element) soapHeader.getObject();  
  56.             logger.info("ELEMENT =" + element.toString());  
  57.             XMLUtils.printDOM(element);  
  58.             NodeList userIdNodes = element  
  59.                     .getElementsByTagName(xml_userID_el);  
  60.             NodeList pwdNodes = element  
  61.                     .getElementsByTagName(xml_password_el);  
  62.             NodeList systemIdNodes = element  
  63.                     .getElementsByTagName(xml_systemID_el);  
  64.             logger.info("############ 打印帐号信息 ##############");  
  65.             logger.info(userIdNodes.item(0) + "="  
  66.                     + userIdNodes.item(0).getTextContent());  
  67.             logger.info(systemIdNodes.item(0) + "="  
  68.                     + systemIdNodes.item(0).getTextContent());  
  69.             logger.info(pwdNodes.item(0) + "="  
  70.                     + pwdNodes.item(0).getTextContent());  
  71.             logger.info("############————————##############");  
  72.             if (null != userIdNodes  
  73.                     && userIdNodes.item(0).getTextContent().equels("test") ) {  
  74.                 if (null != pwdNodes  
  75.                         && pwdNodes.item(0).getTextContent().equals("test")) {  
  76.                     logger.info("$$$$$$$$ 认证成功");  
  77.                 } else {//认证失败则抛出异常,停止继续操作  
  78.                     SOAPException soapExc = new SOAPException("阁下可能不是合法用户!");  
  79.                     throw new Fault(soapExc);  
  80.                 }  
  81.             } else {//认证失败则抛出异常,停止继续操作  
  82.                 SOAPException soapExc = new SOAPException("阁下可能不是合法用户!");  
  83.                 throw new Fault(soapExc);  
  84.             }  
  85.               
  86.         }  
  87.     }  
  88. }  
  89.   
  90. 二,修改cxf-beans.xml  
  91.   
  92. <!--id:随意配,implementor:指定接口具体实现类,address:随意配,访问时会用到,下面会做说明-->  
  93. <!--拦截器-->  
  94. <bean id="authIntercetpr" class="unitTest.AuthIntercetpr"></bean>  
  95. <jaxws:endpoint id="HelloWorldService" implementor="com.ws.HelloWorldServiceImpl"  
  96.         address="/IHelloService">  
  97.         <!-- 在此配置调用当前ws所触发的拦截器-->  
  98.         <jaxws:inInterceptors><ref bean="authIntercetpr" /></bean>   
  99.               
  100.         <!--或者直接在这里写<bean  class="unitTest.AuthIntercetpr"></bean>-->  
  101.         </jaxws:inInterceptors>  
  102. </jaxws:endpoint>  
  103.   
  104. 到此服务端工作完毕!!!  
  105. 下面是客户端(调用端)  
  106. 三,这边同样创建一个拦截器,实现org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor  
  107.   
  108. import java.text.SimpleDateFormat;  
  109. import java.util.Date;  
  110. import java.util.List;  
  111.   
  112. import javax.xml.namespace.QName;  
  113.   
  114. import org.apache.cxf.binding.soap.SoapHeader;  
  115. import org.apache.cxf.binding.soap.SoapMessage;  
  116. import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor;  
  117. import org.apache.cxf.headers.Header;  
  118. import org.apache.cxf.helpers.DOMUtils;  
  119. import org.apache.cxf.helpers.XMLUtils;  
  120. import org.apache.cxf.interceptor.Fault;  
  121. import org.apache.cxf.phase.Phase;  
  122. import org.w3c.dom.Document;  
  123. import org.w3c.dom.Element;  
  124.   
  125. public class AddSoapHeader extends AbstractSoapInterceptor {  
  126.   
  127.     public static final String xml_namespaceUR_att = "http://gd.chinamobile.com//authentication";  
  128.     public static final String xml_header_el = "soap:Header";  
  129.     public static final String xml_authentication_el = "auth:authentication";  
  130.     public static final String xml_systemID_el = "auth:systemID";  
  131.     public static final String xml_userID_el = "auth:userID";  
  132.     public static final String xml_password_el = "auth:password";  
  133.   
  134.     public AddSoapHeader() {  
  135.     // 指定该拦截器在哪个阶段被激发  
  136.         super(Phase.WRITE);  
  137.     }  
  138.   
  139.     public void handleMessage(SoapMessage message) throws Fault {  
  140.         SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  141.         Date date = new Date();  
  142.         String time = sd.format(date);  
  143.         String userId = "test";  
  144.         String sysId = "1";  
  145.         String password = "test";  
  146.   
  147.         QName qname = new QName("RequestSOAPHeader");//这个值暂时不清楚具体做什么用,可以随便写  
  148.   
  149.         Document doc = (Document) DOMUtils.createDocument();  
  150.         Element root = doc.createElement(xml_header_el);  
  151.         Element eSysId = doc.createElement(xml_systemID_el);  
  152.         eSysId.setTextContent(sysId);  
  153.         Element eUserId = doc.createElement(xml_userID_el);  
  154.         eUserId.setTextContent(userId);  
  155.         Element ePwd = doc.createElement(xml_password_el);  
  156.         ePwd.setTextContent(password);  
  157.         Element child = doc.createElementNS(xml_namespaceUR_att,  
  158.                 xml_authentication_el);  
  159.         child.appendChild(eSysId);  
  160.         child.appendChild(eUserId);  
  161.         child.appendChild(ePwd);  
  162.         root.appendChild(child);  
  163.         XMLUtils.printDOM(root);// 只是打印xml内容到控制台,可删除  
  164.         SoapHeader head = new SoapHeader(qname, root);  
  165.         List<Header> headers = message.getHeaders();  
  166.         headers.add(head);  
  167.           
  168.     }  
  169.   
  170. }  
  171.   
  172. 四,具体调用ws的类代码  
  173.   
  174.   
  175.     private static final String webServiceConTimeout = "6000";  
  176.     private static final String webServiceRevTimeout = "6000";  
  177.     。。。。。。。  
  178.         HelloWorldServiceImplService hello = new HelloWorldServiceImplService();    
  179.         HelloWorldService service = hello.getHelloWorldServiceImplPort();  
  180.         //以上什么意思请参考:http://learning.iteye.com/admin/blogs/1333223  
  181.         Client clientProxy = ClientProxy.getClient(service);//通过目标ws获取代理  
  182.         //注入拦截器,getOutInterceptors代表调用服务端时触发,getInInterceptors就是被调用才触发  
  183.         clientProxy.getOutInterceptors().add(ash);  
  184.         // 超时时间设置  
  185.         HTTPConduit http = (HTTPConduit) clientProxy.getConduit();  
  186.         HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();  
  187.         httpClientPolicy.setConnectionTimeout(Integer  
  188.                 .valueOf(webServiceConTimeout));  
  189.         httpClientPolicy.setReceiveTimeout(Integer  
  190.                 .valueOf(webServiceRevTimeout));  
  191.         httpClientPolicy.setAllowChunking(false);  
  192.         http.setClient(httpClientPolicy);  
  193.         //以上插入点超时设置方式  
  194.         //下面这行代码是具体调用服务段的deleteTeskTask()  
  195.         CallResult cResult = service.deleteTeskTask("1223");  
  196.                   
  197.         。  
  198.         。  
  199.           
  200. 客户端代码到此结束  
  201.   
  202. 五,还有一种方式是通过JaxWsProxyFactoryBean方式,注册拦截器及实例化ws,代码如下:  
  203.   
  204. private static final JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();  
  205.   
  206. AddSoapHeader ash = new AddSoapHeader();  
  207.         ArrayList list = new ArrayList();  
  208.         // 添加soap header 信息  
  209.         list.add(ash);  
  210.         //注入拦截器,getOutInterceptors代表调用服务端时触发,getInInterceptors就是被调用才触发  
  211.          factory.setOutInterceptors(list);  
  212.          factory.setServiceClass(HelloWorldService.class);//实例化ws  
  213.          factory.setAddress("http://xxx.xxx.xxx.xxx:8004/services/IHelloService");  
  214.          Object obj = factory.create();  
  215.          HelloWorldService service = (HelloWorldService) obj;  
  216.          //下面这行代码是具体调用服务段的deleteTeskTask()  
  217.         CallResult cResult = service.deleteTeskTask("1223");  
  218.           
  219. ##########这段代码可替代步骤(四)#####  
  220.   
  221. 到此全部工作结束  
  222. 具体一些概念还请自己baidu/google  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值