如何从每个SOAP响应/请求添加/读取自定义标头抛出Java

时间:2013-10-08 13:26:35

标签: java web-services soap header

我必须在SOAP Request中添加一个自定义Header并从SOAP Request中读取Header 到目前为止,我所做的是指这个链接link1link2如下

网络服务类:

import javax.jws.WebMethod;
import javax.jws.WebService;

@WebService()
@HandlerChain(name = "SoapHandler", file = "soaphandler.xml")
public class FooService {

    @WebMethod()
    public String sayHello(String name) {
        System.out.println("Hello: " + name);
        return "Hello " + name + "!";
    }
}

SOAP处理程序类:

package com.webservice;

import java.util.Set;
import java.util.logging.Logger;
import javax.xml.namespace.QName;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

public class SoapHandler implements SOAPHandler<SOAPMessageContext> {

    private static final Logger LOGGER = Logger.getLogger(SoapHandler.class.getName());

    @Override
    public void close(MessageContext arg0) {
        System.out.println("Colse Method");
        LOGGER.info("Close Method");
    }

    @Override
    public boolean handleFault(SOAPMessageContext arg0) {
        System.out.println("handleFault Method");
        LOGGER.info("handleFault Method");
        return false;
    }

    @Override
    public boolean handleMessage(SOAPMessageContext arg0) {
        System.out.println("handleMessage Method");
        LOGGER.info("handleMessage Method");
        return false;
    }

    @Override
    public Set<QName> getHeaders() {
        System.out.println("getHeaders Method");
        LOGGER.info("getHeaders Method");
        return null;
    }
}

测试人员类

public class Tester {

    /**
     * @param args
     */
    public static void main(String[] args) {
        try {
            FooServiceServiceLocator locator = new FooServiceServiceLocator();
            FooService fooService = locator.getFooServicePort();
            System.out.println(fooService.sayHello("ashish"));
        } catch (ServiceException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

处理程序链配置:

<?xml version="1.0" encoding="UTF-8"?>
<jws:handler-chains xmlns:jws="http://java.sun.com/xml/ns/javaee">
  <jws:handler-chain>
    <jws:handler>
      <jws:handler-name>SoapHandler</jws:handler-name>
      <jws:handler-class>com.webservice.SoapHandler</jws:handler-class>
    </jws:handler>
  </jws:handler-chain>
</jws:handler-chains>

当我调用这个Tester类时,它给出了正确的输出“Hello ashish!” 和我的 handleMessage(SOAPMessageContext arg0) 当请求进入和退出时,方法正在执行,那么如何区分我的

中的传入请求和传出响应
handleMessage(SOAPMessageContext arg0) method ? so that when request comes in I can read Header and when response goes out then I can Add my header into it Thanks....

1 个答案:

答案 0 :(得分:2)

使用你在handleMessage

中获得的context参数
arg0.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

并检查retunred布尔值以将msg标识为请求/响应