微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

JAX-WS Handler使用

 

1.Handler和Servlet中的filter极为相似,我们可以对所有WebServicer进行拦截在这个Handler中我们可以记录日志、

   权限控制、对请求的SOAP消息进行加密,解密等。CXF也有Interceptor,不知道有什么区别,后面会学习

 

2.接口javax.xml.ws.handler.Handler和javax.xml.ws.handler.soap.soAPHandler

  定义自己Handler需要实现两个Handler其中一个SOAPHandler是Handler的子接口

  Handler的三个方法

 

 

 

void

 

 

 close(MessageContext context) :一个webService调用结束时会调用,通常会做释放资源的操作
          

 

  boolean 

 

handleFault(C context) :当handlerMessage发生异常时,会调用
          

 

 boolean

 

 handleMessage(C context):调用webService inbound和outbound时都会调用,一次webService调用

                                           会调用方法两次

 

 

 

3.实现一个用户身份验证的Handler来说明Handler使用

   3.1定义我们自己Handler

        public class AuthValidationHandler implements SOAPHandler<SOAPMessageContext> {

Java代码

复制代码

 

收藏代码

  1.     public Set<QName> getHeaders() {   
  2.         // Todo Auto-generated method stub   
  3.         return null;   
  4.     }   
  5.   
  6.     public void close(MessageContext context) {   
  7.            
  8.     }   
  9.   
  10.     public boolean handleFault(SOAPMessageContext context) {   
  11.         return false;   
  12.     }   
  13.   
  14.     public boolean handleMessage(SOAPMessageContext context) {   
  15.            
  16.         HttpServletRequest request = (HttpServletRequest)context.get(AbstractHTTPDestination.HTTP_Request);   
  17.            
  18.         System.out.println("客户端IP:"+request.getRemoteAddr());   
  19.            
  20.         Boolean outbound = (Boolean)context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);    
  21.   
  22.           if (!outbound.booleanValue())    
  23.           {   
  24.               SOAPMessage soapMessage = context.getMessage();   
  25.                  
  26.               try {   
  27.                 SOAPEnvelope soapEnvelope = soapMessage.getSOAPPart().getEnvelope();   
  28.                 SOAPHeader soapHeader = soapEnvelope.getHeader();   
  29.                    
  30.                 if(soapHeader == null)generateSoapFault(soapMessage, "No Message Header...");   
  31.                    
  32.                 Iterator it = soapHeader.extractHeaderElements(SOAPConstants.URI_SOAP_1_2_ROLE_NEXT);   
  33.                    
  34.                 if(it == null || !it.hasNext())generateSoapFault(soapMessage, "No Header block for role next");   
  35.                    
  36.                 Node node = (Node)it.next();   
  37.                    
  38.                 String value = node == null ? null : node.getValue();   
  39.                    
  40.                 if(value == null)generateSoapFault(soapMessage, "No authation info in header blocks");   
  41.                    
  42.                 String[] infos = value.split("&");   
  43.                    
  44.                 return authValidate(infos[0], infos[1]);   
  45.                    
  46.                    
  47.             } catch (SOAPException e) {   
  48.                 e.printstacktrace();   
  49.             }   
  50.                  
  51.           }   
  52.   
  53.              
  54.         return false;   
  55.     }   
  56.        
  57.        
  58.     private boolean authValidate(String userName,String password){   
  59.         if(userName == null || password == null){   
  60.             return false;   
  61.         }   
  62.            
  63.         if("admin".equals(userName) && "admin".equals(password)){   
  64.             return true;   
  65.         }   
  66.         return false;   
  67.     }   
  68.        
  69.     private void generateSoapFault(SOAPMessage soapMessage,String reasion){   
  70.         try {   
  71.             SOAPBody soapBody = soapMessage.getSOAPBody();   
  72.             SOAPFault soapFault = soapBody.getFault();   
  73.                
  74.             if(soapFault == null){   
  75.                 soapFault = soapBody.addFault();   
  76.             }   
  77.                
  78.             soapFault.setFaultString(reasion);   
  79.                
  80.             throw new SOAPFaultException(soapFault);   
  81.                
  82.         } catch (SOAPException e) {   
  83.             // Todo Auto-generated catch block   
  84.             e.printstacktrace();   
  85.         }   
  86.     }   
  87.   
  88.        
  89. }  

   HttpServletRequest request = (HttpServletRequest)context.get(AbstractHTTPDestination.HTTP_Request);

   可以获取request对象,从而拿到客户端Ip,可以进行非法地址ip排除

 

  Boolean outbound = (Boolean)context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

  判断当前是Inbound还是outbound

  只在inbound时做用户校验

 

  我们将用户相信放在soapheader里

 

   3.2在SEI实现类UserServiceImpl上添加@HandlerChain(file = "handlers.xml")

 

   3.3在UserServiceImpl所在包下编写handlers.xml

       <handler-chains xmlns="http://java.sun.com/xml/ns/javaee"

Xml代码

复制代码

 

收藏代码

  1.                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
  2.                 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee">  
  3.   <handler-chain>  
  4.   
  5.     <handler>  
  6.       <handler-name>authHandler</handler-name>  
  7.       <handler-class>com.cxf.users.AuthValidationHandler</handler-class>  
  8.     </handler>  
  9.   </handler-chain>  
  10. </handler-chains>  

 

  这样我们服务端就编写好了,我们还有在客户端将我们用户信息加到soapHeader中

 

4.客户端将我们用户信息加到soapHeader中

   4.1客户端Handler

        public class AuthenticationHandler implements SOAPHandler<SOAPMessageContext> {

Java代码

复制代码

 

收藏代码

  1.     public Set<QName> getHeaders() {   
  2.         // Todo Auto-generated method stub   
  3.         return null;   
  4.     }   
  5.   
  6.     public void close(MessageContext arg0) {   
  7.         // Todo Auto-generated method stub   
  8.            
  9.     }   
  10.   
  11.     public boolean handleFault(SOAPMessageContext arg0) {   
  12.         // Todo Auto-generated method stub   
  13.         return false;   
  14.     }   
  15.   
  16.     public boolean handleMessage(SOAPMessageContext ctx) {   
  17.         Boolean request_p=(Boolean)ctx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);   
  18.            
  19.        if(request_p){   
  20.            try {    
  21.               SOAPMessage msg=ctx.getMessage();   
  22.               SOAPEnvelope env=msg.getSOAPPart().getEnvelope();   
  23.               SOAPHeader hdr=env.getHeader();   
  24.                  
  25.               if(hdr==null)hdr=env.addHeader();   
  26.              
  27.               //添加认证信息   
  28.               QName qname_user=new QName("http://com/auth/","auth");   
  29.               SOAPHeaderElement helem_user=hdr.addHeaderElement(qname_user);   
  30.               helem_user.setActor(SOAPConstants.URI_SOAP_1_2_ROLE_NEXT);   
  31.               helem_user.addTextNode("admin&admin");   
  32.               msg.saveChanges();   
  33.               //把SOAP消息输出到System.out,即控制台   
  34.               msg.writeto(System.out);   
  35.               return true;   
  36.            } catch (Exception e) {   
  37.               e.printstacktrace();   
  38.            }   
  39.        }   
  40.            return false;   
  41.     }   
  42.   
  43.        
  44. }  

 

  4.2将Handler加到HandlerResolver中

      public class UserClient {

Java代码

复制代码

 

收藏代码

  1.     /**  
  2.      * @param args  
  3.      */  
  4.     public static void main(String[] args) {   
  5.         UserServiceImplService userServiceImpl = new UserServiceImplService();   
  6.            
  7.         userServiceImpl.setHandlerResolver(new HandlerResolver(){   
  8.   
  9.             public List<Handler> getHandlerChain(PortInfo arg0) {   
  10.                    
  11.                 List<Handler> handlerList = new ArrayList<Handler>();   
  12.                 //添加认证信息   
  13.                 handlerList.add(new AuthenticationHandler());   
  14.                   return handlerList;   
  15.             }   
  16.                
  17.         });   
  18.            
  19.            
  20.         IUserService service = userServiceImpl.getUserServiceImplPort();   
  21.            
  22.            
  23.         User u = new User();   
  24.         u.setId(110);   
  25.         u.setUserName("张三");   
  26.         u.setAddress("杭州");   
  27.         u.setSex(0);   
  28.         System.out.println();   
  29.         System.out.println(service.addUser(u));   
  30.            
  31.     }   
  32.   
  33. }  

 

   这样验证就做好了

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐