MessageContext和传输头之续一(实例演示:SIB中访问消息上下文)

我们还是以HelloWord为例,在SIB中访问消息上下文。

服务端

HelloWord.java

package ch03.ts;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.xml.ws.Holder;

@WebService
public interface HelloWord {

    @WebMethod
    void sayHello(@WebParam(name="name") String name,
            @WebParam(name="wh",mode=WebParam.Mode.INOUT) Holder<String> wh,
            @WebParam(name="hf",mode=WebParam.Mode.OUT) Holder<String> hf);
}

HelloWordImpl.java(注意访问上下文那段代码,还有@Resource注解的WebServiceContext

package ch03.ts;

import hw5.MapDump;
import java.util.Map;
import javax.annotation.Resource;
import javax.jws.HandlerChain;
import javax.jws.WebService;
import javax.xml.ws.BindingType;
import javax.xml.ws.Holder;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;

@WebService(endpointInterface = "ch03.ts.HelloWord")
@HandlerChain(file = "handler-chain-server.xml")
@BindingType(value = "http://java.sun.com/xml/ns/jaxws/2003/05/soap/bindings/HTTP/")
public class HelloWordImpl implements HelloWord {
    
    @Resource
    WebServiceContext wsContext;

    @SuppressWarnings("rawtypes")
    @Override
    public void sayHello(String name, Holder<String> wh, Holder<String> hf) {
        System.out.println(name + "!" + wh.value);
        wh.value = "你们好";
        hf.value = "同学们";
        System.out.println("~~~~~~~~~~~~~~~访问MessageContext上下文~~~~~~~~~~~~~~~~~");
        MessageContext mc = wsContext.getMessageContext();
        Map req_header = (Map)mc.get(MessageContext.HTTP_REQUEST_HEADERS);
        MapDump.dump_map(req_header);
    }
}

MapDump.java

package ch03.ts;

import java.util.Map;
import java.util.Set;

/**
 * 用于解析打印head部分
 * @author fuhd
 */
public class MapDump {
    @SuppressWarnings("rawtypes")
    public static void dump_map(Map map) {
        Set keys = map.keySet();
        for(Object key : keys) {
            System.out.println(key + " =====> " + map.get(key));
            if(map.get(key) instanceof Map){
                dump_map((Map)map.get(key));
            }
        }
    }
}

handler-chain-server.java

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<javaee:handler-chains xmlns:javaee="http://java.sun.com/xml/ns/javaee" 
        xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <javaee:handler-chain>
        <javaee:handler>
            <javaee:handler-class>fibC.UUIDValidator</javaee:handler-class>
        </javaee:handler>
    </javaee:handler-chain>        
</javaee:handler-chains>

UUIDValidator.java

package fibC;

import java.util.Iterator;
import java.util.Set;
import java.util.UUID;
import javax.xml.namespace.QName;
import javax.xml.soap.Node;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPFault;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
import javax.xml.ws.soap.SOAPFaultException;

/**
 * 服务器端验证UUID值
 * @author fuhd
 */
public class UUIDValidator implements SOAPHandler<SOAPMessageContext> {
    
    private static final int UUIDVARIANT = 2;    //layout
    private static final int UUIDVERSION = 4;    //version

    @SuppressWarnings({ "rawtypes"})
    @Override
    public boolean handleMessage(SOAPMessageContext context) {
        Boolean resp = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
        if(!resp){
            try {
                SOAPMessage msg = context.getMessage();
                SOAPEnvelope env = msg.getSOAPPart().getEnvelope();
                SOAPHeader hdr = env.getHeader();
                if(hdr == null)
                    generateSOAPFault(msg, "No message header.");
                Iterator it = hdr.extractHeaderElements(SOAPConstants.URI_SOAP_ACTOR_NEXT);
                if(it == null || !it.hasNext())
                    generateSOAPFault(msg, "No header block for next actor.");
                Node next = (Node)it.next();
                String value = (next == null)?null:next.getValue();
                if(value == null)
                    generateSOAPFault(msg, "No UUID in header block.");
                UUID uuid = UUID.fromString(value.trim());
                if(uuid.variant() != UUIDVARIANT || uuid.version() != UUIDVERSION)
                    generateSOAPFault(msg, "Bad UUID variant or version");
                System.out.println(value.trim());
            } catch (SOAPException e) {
                e.printStackTrace();
            } 
        }
        return true;
    }

    @Override
    public boolean handleFault(SOAPMessageContext context) {
        return true;
    }

    @Override
    public void close(MessageContext context) {}

    @Override
    public Set<QName> getHeaders() {
        return null;
    }
    
    private void generateSOAPFault(SOAPMessage msg,String reason){
        try {
            SOAPBody body = msg.getSOAPPart().getEnvelope().getBody();
            SOAPFault fault = body.addFault();
            fault.setFaultString(reason);
            throw new SOAPFaultException(fault);
        } catch (SOAPException e) {
            e.printStackTrace();
        }
    }
}

HelloWordPublisher.java

package ch03.ts;

import javax.xml.ws.Endpoint;

public class HelloWordPublisher {
    public static void main(String[] args) {
        Endpoint.publish("http://localhost:7654/ts", new HelloWordImpl());
    }
}

客户端代码:

HelloWord.java

package hw5;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.Action;
import javax.xml.ws.Holder;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;

/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.2.4-b01
 * Generated source version: 2.2
 */
@WebService(name = "HelloWord", targetNamespace = "http://ts.ch03/")
@XmlSeeAlso({
    ObjectFactory.class
})
public interface HelloWord {
    /**
     * @param wh
     * @param name
     * @param hf
     */
    @WebMethod
    @RequestWrapper(localName = "sayHello", targetNamespace = "http://ts.ch03/", 
        className = "hw5.SayHello")
    @ResponseWrapper(localName = "sayHelloResponse", targetNamespace = "http://ts.ch03/", 
        className = "hw5.SayHelloResponse")
    @Action(input = "http://ts.ch03/HelloWord/sayHelloRequest", 
        output = "http://ts.ch03/HelloWord/sayHelloResponse")
    public void sayHello(
        @WebParam(name = "name", targetNamespace = "")
        String name,
        @WebParam(name = "wh", targetNamespace = "", mode = WebParam.Mode.INOUT)
        Holder<String> wh,
        @WebParam(name = "hf", targetNamespace = "", mode = WebParam.Mode.OUT)
        Holder<String> hf);
}

HelloWordImplService.java

package hw5;

import java.net.MalformedURLException;
import java.net.URL;
import javax.jws.HandlerChain;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.WebServiceFeature;

/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.2.4-b01
 * Generated source version: 2.2
 */
@WebServiceClient(name = "HelloWordImplService", targetNamespace = "http://ts.ch03/", 
    wsdlLocation = "http://localhost:7654/ts?wsdl")
@HandlerChain(file = "handler-chain.xml")
public class HelloWordImplService extends Service {

    private final static URL HELLOWORDIMPLSERVICE_WSDL_LOCATION;
    private final static WebServiceException HELLOWORDIMPLSERVICE_EXCEPTION;
    private final static QName HELLOWORDIMPLSERVICE_QNAME = 
        new QName("http://ts.ch03/", "HelloWordImplService");

    static {
        URL url = null;
        WebServiceException e = null;
        try {
            url = new URL("http://localhost:7654/ts?wsdl");
        } catch (MalformedURLException ex) {
            e = new WebServiceException(ex);
        }
        HELLOWORDIMPLSERVICE_WSDL_LOCATION = url;
        HELLOWORDIMPLSERVICE_EXCEPTION = e;
    }

    public HelloWordImplService() {
        super(__getWsdlLocation(), HELLOWORDIMPLSERVICE_QNAME);
    }

    public HelloWordImplService(WebServiceFeature... features) {
        super(__getWsdlLocation(), HELLOWORDIMPLSERVICE_QNAME, features);
    }

    public HelloWordImplService(URL wsdlLocation) {
        super(wsdlLocation, HELLOWORDIMPLSERVICE_QNAME);
    }

    public HelloWordImplService(URL wsdlLocation, WebServiceFeature... features) {
        super(wsdlLocation, HELLOWORDIMPLSERVICE_QNAME, features);
    }

    public HelloWordImplService(URL wsdlLocation, QName serviceName) {
        super(wsdlLocation, serviceName);
    }

    public HelloWordImplService(URL wsdlLocation, QName serviceName, 
        WebServiceFeature... features) {
        super(wsdlLocation, serviceName, features);
    }

    /**
     * @return
     * returns HelloWord
     */
    @WebEndpoint(name = "HelloWordImplPort")
    public HelloWord getHelloWordImplPort() {
        return super.getPort(new QName("http://ts.ch03/", "HelloWordImplPort"), 
            HelloWord.class);
    }

    /**
     * @param features
     * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy.  
     * Supported features not in the <code>features</code> parameter 
     * will have their default values.
     * @return
     * returns HelloWord
     */
    @WebEndpoint(name = "HelloWordImplPort")
    public HelloWord getHelloWordImplPort(WebServiceFeature... features) {
        return super.getPort(new QName("http://ts.ch03/", "HelloWordImplPort"), 
            HelloWord.class, features);
    }

    private static URL __getWsdlLocation() {
        if (HELLOWORDIMPLSERVICE_EXCEPTION!= null) {
            throw HELLOWORDIMPLSERVICE_EXCEPTION;
        }
        return HELLOWORDIMPLSERVICE_WSDL_LOCATION;
    }
}

handler-chain.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<javaee:handler-chains xmlns:javaee="http://java.sun.com/xml/ns/javaee" 
        xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <javaee:handler-chain>
        <javaee:handler>
            <javaee:handler-class>fibC.UUIDHandler</javaee:handler-class>
        </javaee:handler>
    </javaee:handler-chain>        
</javaee:handler-chains>

UUIDHandler.java

package fibC;

import java.io.IOException;
import java.util.Set;
import java.util.UUID;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPHeaderElement;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

/**
 * SOAP处理程序(Handler)
 * @author FUHD
 */
public class UUIDHandler implements SOAPHandler<SOAPMessageContext> {

    @Override
    public boolean handleMessage(SOAPMessageContext context) {
        Boolean request = (Boolean)context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
        if(request){
            UUID uuid = UUID.randomUUID();
            try {
                SOAPMessage msg = context.getMessage();
                SOAPEnvelope env = msg.getSOAPPart().getEnvelope();
                SOAPHeader hdr = env.getHeader();
                if(hdr == null) hdr = env.addHeader();
                QName qname = new QName("http://ts.ch03/","uuid");
                SOAPHeaderElement helem = hdr.addHeaderElement(qname);
                helem.setActor(SOAPConstants.URI_SOAP_ACTOR_NEXT);
                helem.setMustUnderstand(true);
                helem.addTextNode(uuid.toString());
                msg.saveChanges();
                msg.writeTo(System.out);
                System.out.println();
            } catch (SOAPException e1) {
                e1.printStackTrace();
            } catch (IOException e2) {
                e2.printStackTrace();
            }
        }
        return true;
    }

    @Override
    public boolean handleFault(SOAPMessageContext context) {
        try {
            context.getMessage().writeTo(System.out);
        } catch (SOAPException e1) {
            e1.printStackTrace();
        } catch (IOException e2) {
            e2.printStackTrace();
        }
        return true;
    }

    @Override
    public void close(MessageContext context) {
    }

    @Override
    public Set<QName> getHeaders() {
        return null;
    }
}

SayHello.java

package hw5;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 * <p>Java class for sayHello complex type.
 * <p>The following schema fragment specifies the expected content 
 * contained within this class.
 * <pre>
 * &lt;complexType name="sayHello">
 *   &lt;complexContent>
 *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       &lt;sequence>
 *         &lt;element name="name" type="{http://www.w3.org/2001/XMLSchema}string" 
 *            minOccurs="0"/>
 *         &lt;element name="wh" type="{http://www.w3.org/2001/XMLSchema}string" 
 *            minOccurs="0"/>
 *       &lt;/sequence>
 *     &lt;/restriction>
 *   &lt;/complexContent>
 * &lt;/complexType>
 * </pre>
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "sayHello", propOrder = {
    "name",
    "wh"
})
public class SayHello {

    protected String name;
    protected String wh;

    /**
     * Gets the value of the name property.
     * @return
     * possible object is
     * {@link String }   
     */
    public String getName() {
        return name;
    }

    /**
     * Sets the value of the name property.
     * @param value
     * allowed object is
     * {@link String }  
     */
    public void setName(String value) {
        this.name = value;
    }

    /**
     * Gets the value of the wh property.
     * @return
     * possible object is
     * {@link String }  
     */
    public String getWh() {
        return wh;
    }

    /**
     * Sets the value of the wh property.
     * @param value
     * allowed object is
     * {@link String }   
     */
    public void setWh(String value) {
        this.wh = value;
    }
}

SayHelloResponse.java

package hw5;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 * <p>Java class for sayHelloResponse complex type.
 * <p>The following schema fragment specifies the expected content contained 
 * within this class.
 * <pre>
 * &lt;complexType name="sayHelloResponse">
 *   &lt;complexContent>
 *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       &lt;sequence>
 *         &lt;element name="wh" type="{http://www.w3.org/2001/XMLSchema}string" 
 *            minOccurs="0"/>
 *         &lt;element name="hf" type="{http://www.w3.org/2001/XMLSchema}string" 
 *            minOccurs="0"/>
 *       &lt;/sequence>
 *     &lt;/restriction>
 *   &lt;/complexContent>
 * &lt;/complexType>
 * </pre>
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "sayHelloResponse", propOrder = {
    "wh",
    "hf"
})
public class SayHelloResponse {

    protected String wh;
    protected String hf;

    /**
     * Gets the value of the wh property.
     * @return
     * possible object is
     * {@link String }   
     */
    public String getWh() {
        return wh;
    }

    /**
     * Sets the value of the wh property.
     * @param value
     * allowed object is
     * {@link String } 
     */
    public void setWh(String value) {
        this.wh = value;
    }

    /**
     * Gets the value of the hf property.
     * @return
     * possible object is
     * {@link String }
     */
    public String getHf() {
        return hf;
    }

    /**
     * Sets the value of the hf property.
     * @param value
     * allowed object is
     * {@link String }   
     */
    public void setHf(String value) {
        this.hf = value;
    }
}

ObjectFactory.java,package-info.java略。

HelloWordClient.java

package hw5;

import javax.xml.ws.Holder;

public class HelloWordClient {
    public static void main(String[] args) {
        String name = "老板";
        Holder<String> wh = new Holder<String>();
        wh.value = "你好";
        Holder<String> hf = new Holder<String>();
        HelloWordImplService service = new HelloWordImplService();
        HelloWord port = service.getPort(HelloWord.class);
        port.sayHello(name, wh, hf);
        System.out.println(hf.value + "," + wh.value);
    }
}

服务端SIB中的打印结果如下:

五月 16, 2014 9:05:21 下午 com.sun.xml.internal.ws.server.EndpointFactory generateWSDL
警告: Generating non-standard WSDL for the specified binding
6d6912c4-b85a-4c84-9044-d91098d9cff6
老板!你好
~~~~~~~~~~~~~~~访问MessageContext上下文~~~~~~~~~~~~~~~~~
Host =====> [localhost:7654]
Content-type =====> [application/soap+xml; charset=utf-8;action="http://ts.ch03/HelloWord/sayHelloRequest"]
Content-length =====> [449]
Connection =====> [keep-alive]
User-agent =====> [JAX-WS RI 2.2.4-b01]
Accept =====> [application/soap+xml, multipart/related]

注意:在HelloWordImpl.java这个SIB类中,有个类型为WebServiceContext的字段,该字段添加了一个@Resource注解。这个注解用来请求依赖注入,它是一个面向方面编程(AOP)的注解。字段 wsContext 未初始化,其默认值为null。然而不可思议的是,在sayHello方法中调用了 wsContext 的getMessageContext方法。这没什么好意外的,正是JWS容器向应用程序注入了一个WebServiceContext类型的对象,使得变量 wsContext 获得了该对象的引用。于是 WebServiceContext便用来访问MessageContext,然后通过MessageContext以Map方式获得传输层头信息。


你可能感兴趣的:(java-web服务)