繁体   English   中英

使用多态的JAX-WS Web服务参数

[英]Using polymorphic JAX-WS webservice parameters

我有这个简单的JAX-WS WebService:

@WebService
public class AnimalFeedingService {
    @WebMethod
    public void feed(@WebParam(name = "animal") Animal animal) {
        // Whatever
    }
}

@XmlSeeAlso({ Dog.class, Cat.class })
public abstract class Animal {
    private double weight;
    private String name;
    // Also getters and setters
}

public class Dog extends Animal {}

public class Cat extends Animal {}

我创建一个客户端,并使用Dog实例调用feed

Animal myDog = new Dog();
myDog .setName("Rambo");
myDog .setWeight(15);
feedingServicePort.feed(myDog);

SOAP调用主体中的动物看起来像这样:

<animal>
    <name>Rambo</name>
    <weight>15</weight>
</animal>

我得到一个UnmarshallException因为Animal是抽象的。

有没有办法将Rambo解组为Dog类的实例? 我有什么选择?

您可能已经猜到了,XML解析器无法确定您在请求时使用的动物的确切子类型,因为它看到的所有内容都是通用的<animal>和所有类型都通用的一组标记,因此会出现错误。 您使用哪种JAX-WS实现? 发送请求时,客户端有责任正确包装多态类型。 Apache CXF中 (我已针对最新的2.3.2版本检查了您的代码),SOAP请求主体如下所示:

<animal xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ns2:dog">
    <name>Rambo</name>
    <weight>15.0</weight>
</animal>

xsi:type="ns2:dog"在这里至关重要。 看来您的JAX-WS客户端发送了不正确的请求,使服务器感到困惑。 尝试与其他客户端(例如SoapUI)发送此请求,以查看服务器是否正常响应。

就像我说的那样,它在Spring / Apache CXF以及与您提供的代码完全相同的情况下都可以正常工作,我只提取了Java接口以使CXF满意:

public interface AnimalFeedingService {

    @WebMethod
    void feed(@WebParam(name = "animal") Animal animal);

}

@WebService
@Service
public class AnimalFeedingServiceImpl implements AnimalFeedingService {
    @Override
    @WebMethod
    public void feed(@WebParam(name = "animal") Animal animal) {
        // Whatever
    }
}

...以及服务器/客户端粘合代码:

<jaxws:endpoint implementor="#animalFeedingService" address="/animal"/>

<jaxws:client id="animalFeedingServiceClient"
              serviceClass="com.blogspot.nurkiewicz.test.jaxws.AnimalFeedingService"
              address="http://localhost:8080/test/animal">
</jaxws:client>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM