【笔记】 WebService之自定义拦截器

一、服务端

【Server】

factoryBean.getInInterceptors().add(new MyInterceptor());

【MyInterceptor】

package com.jul_11th.server;

import java.util.List;

import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class MyInterceptor extends AbstractPhaseInterceptor {

    public MyInterceptor() {
        super(Phase.PRE_INVOKE);//在调用方法之前调用自定义拦截器
    }

    @SuppressWarnings("null")
    @Override
    public void handleMessage(SoapMessage message) throws Fault {
        List
headers = message.getHeaders(); if(headers==null && headers.size()==0){ throw new Fault(new IllegalArgumentException("没有Header,拦截器实施拦截")); } Header firstHeader = headers.get(0); Element ele = (Element)firstHeader.getObject(); NodeList uList = ele.getElementsByTagName("userName"); NodeList pList = ele.getElementsByTagName("password"); if(uList.getLength()!=1){ throw new Fault(new IllegalArgumentException("用户名错误!")); } if(pList.getLength()!=1){ throw new Fault(new IllegalArgumentException("密码错误!")); } String userName=uList.item(0).getTextContent(); String password=pList.item(0).getTextContent(); System.out.println(userName+"++++++++"+password); if(!userName.equals("admin") || !password.equals("admin")){ throw new Fault(new IllegalArgumentException("用户名、密码错误!")); } } }

二、客户端

【Client】

org.apache.cxf.endpoint.Client client=ClientProxy.getClient(hw);
client.getOutInterceptors().add(new AddHeaderInterceptor("admin","admin"));

【AddHeaderInterceptor】

package com.jul_11th.client;

import java.util.List;

import javax.xml.namespace.QName;

import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.helpers.DOMUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class AddHeaderInterceptor extends AbstractPhaseInterceptor {

    private String userName;
    private String password;

    public AddHeaderInterceptor(String userName,String password) {
        super(Phase.PREPARE_SEND);//准备发送SOAP消息时调用拦截器
        this.userName=userName;
        this.password=password;
    }

    @Override
    public void handleMessage(SoapMessage message) throws Fault {
        List
headerList = message.getHeaders(); Document doc=DOMUtils.createDocument(); Element ele = doc.createElement("authHeader"); Element uElement=doc.createElement("userName"); uElement.setTextContent(userName); Element pElement=doc.createElement("password"); pElement.setTextContent(password); ele.appendChild(uElement); ele.appendChild(pElement); headerList.add(new Header(new QName("jul_11th"),ele)); } }

源码下载:http://download.csdn.net/detail/jul_11th/9890448

谢谢支持!

你可能感兴趣的:(web,service,自定义拦截器,WebService)