在传递给JAX-RS中的servlet时,对象值变为NULL

时间:2017-12-13 05:41:46

标签: java servlets jax-rs jersey-client

JAX-RS使用Jersey

我正在尝试从客户端向servlet发送一个对象“Broadcast”,并在servlet端打印值。但我的输出变为空。提前感谢帮助我解决问题: - )

的Servlet

@POST
@Path("/receiverMessage")
public Response sendMessage(Broadcast broadcast) {
    System.out.println(broadcast.getSenderName());
    System.out.println(broadcast.getReceiverName());
    System.out.println(broadcast.getTime());
    return Response.ok().status(200).entity("SUCCESS").build();
}

客户端

public class Client {
public static void main(String[] args) {
    Client client = ClientBuilder.newClient();
    Broadcast broadcast = new Broadcast("SENDER", "RECEIVER", new Timestamp(System.currentTimeMillis()));
    Response messagePost = client.target("http://localhost:8081/xyz/abc")
            .path("receiverMessage")
            .request()
            .post(Entity.entity(broadcast, MediaType.APPLICATION_JSON), Response.class);
    System.out.println(messagePost.getStatus());
}}

广播模式

public class Broadcast {
private String senderName;
private String receiverName;
private Timestamp time;
}

MessageBodyWriter

@Override
public void writeTo(Broadcast broadcast, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
    System.setProperty("javax.xml.bind.context.factory","org.eclipse.persistence.jaxb.JAXBContextFactory");
    try {
        JAXBContext context = JAXBContext.newInstance(type);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
        marshaller.marshal(broadcast, entityStream);
    } catch (JAXBException e) {
        e.printStackTrace();
    }
}

输出

null 
null
null

1 个答案:

答案 0 :(得分:0)

如果您使用泽西岛,那么您不需要做任何额外的事情。 Jersey有能力(de)序列化你的JSON。但是,您需要做一些更改。

  1. 您缺少服务器端的@Consumes@Produces注释

    @POST
    @Path("/receiverMessage")
    @Consumes ( { MediaType.APPLICATION_JSON })
    @Produces ( { MediaType.TEXT_PLAIN })
    public Response sendMessage(Broadcast broadcast) {
       System.out.println(broadcast.getSenderName());
       System.out.println(broadcast.getReceiverName());
       System.out.println(broadcast.getTime());
       return Response.ok().status(200).entity("SUCCESS").build();
    }
    
  2. 此外,您的POJO类没有注释来指示它是JAXB类。您可以找到Using JAX-RS with JAXB
  3. 的非常好的示例