如何将超类对象传递给restful service(jersey)

时间:2013-10-30 10:32:56

标签: web-services jersey restful-architecture

我有两个POJO

 @XmlRootElement
 public class PojoBase {
 }

 @XmlRootElement
 public class PojoRequest extends PojoBase {

 private String strTemplate;

 public void setTemplate(String strTemplate) {
    this.strTemplate = strTemplate;
 }

 public String getTemplate() {
    return strTemplate;
 }

 }

 @XmlRootElement
 public class PojoResponse extends PojoBase {

private String strName;

public void setName(String strName) {
    this.strName = strName;
}

public String getName() {
    return strName;
}

}

我有服务接受基类并返回基类作为响应。

@POST
@Path("/start")
@Produces({MediaType.APPLICATION_JSON})
@Consumes(MediaType.APPLICATION_JSON)
public PojoBase registerNumber(JAXBElement<PojoBase> theRequest) {
        //does some work with theRequest.

        //here the theRequest object doesn't has pojoRequest data.
        PojoResponse pojoResponse = new PojoResponse();
        pojoResponse.setName("Sample");
        return pojoResponse;
    }

从客户端我发送pojo基础对象,但不确定为什么Restful不会获得实际的theRequest对象。

以下是客户端代码:

 public class HttpClient {
    static String _strServiceURL = "http://127.0.0.1:8080/middleware/rest/service/start";
    public static void main(String[] args) throws Exception {

        PojoRequest pojoRequest = new PojoRequest();
        pojoRequest.setTemplate("Somedata");

        PojoBase response = getResponse(pojoRequest);
        PojoResponse pojoresponse = (PojoResponse) response;
        System.out.println(response);
    }

    private static PojoBase getResponse(PojoBase request) {
         try {
             Client client = Client.create();
             WebResource webResource = client.resource(_strServiceURL);
             ClientResponse response = webResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, request);
             System.out.println(response.getStatus()); 
             if(response.getStatus() == 200){
                   PojoBase response =  response.getEntity(PojoBase.class);
                   return response;
             }      
          } catch(Exception e) {
              System.out.println(e.getMessage());
          }
          return null;
      }

}

你能告诉我如何在服务端获得PojoRequest吗?

感谢任何帮助。

由于

1 个答案:

答案 0 :(得分:0)

我认为你不能像这样把超级球员传给球衣。我相信,虽然我可能错了,因为registerNumber()有一个参数JAXBElement<PojoBase>,它会做类似的事情:

  1. 实例化PojoBase
  2. PojoBase(没有属性)进行反思,因此无需设置。
  3. 使用几乎为空的registerNumber()对象
  4. 来调用PojoBase

    那么为什么不尝试将签名更改为:

    public PojoBase registerNumber(JAXBElement< PojoRequest > theRequest) 
    

    或甚至(使用com.sun.jersey.api.json.POJOMappingFeature = true):

    public PojoBase registerNumber(PojoRequest theRequest)