检查JAXBElement参数是否为null

时间:2012-11-30 18:50:01

标签: java web-services jaxb jersey jax-rs

我有以下方法,它接收XML并在数据库中创建一本新书:

@PUT
@Path("/{isbn}")
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public SuccessfulRequestMessage createBook(JAXBElement<Book> bookParam,
        @PathParam("isbn") String isbn) {

    if(bookParam == null)
    {
        ErrorMessage errorMessage = new ErrorMessage(
                "400 Bad request",
                "To create a new book you must provide the corresponding XML code!");
        throw new MyWebServiceException(Response.Status.BAD_REQUEST,
                errorMessage);
    }
        ....................................................................
}

问题是,当我不在邮件正文中发送任何内容时,不会抛出异常。我怎么能检查邮件正文是否为空?

谢谢!

索林

3 个答案:

答案 0 :(得分:0)

试试这个:

public SuccessfulRequestMessage createBook(JAXBElement<Book> bookParam, 
                      @PathParam("isbn") String isbn) throws MyWebServiceException

答案 1 :(得分:0)

JAXBElement本身可能不是null,而是其有效负载。请检查bookParam.getValue()以及bookParam

答案 2 :(得分:0)

我发现了一个可以完成的小技巧:我发送 application / x-www-form-urlencoded ,而不是发送 MediaType.APPLICATION_XML ,代表只有一个参数,此参数将包含XML代码。然后我可以检查参数是null还是空。然后,从参数的内容,我构造一个JAXBElement。 代码如下:

@PUT
@Path("/{isbn}")
@Consumes("application/x-www-form-urlencoded")
@Produces(MediaType.APPLICATION_XML)
public SuccessfulRequestMessage createBook(@FormParam("code") String code,
        @PathParam("isbn") String isbn) throws MyWebServiceException {

    if(code == null || code.length() == 0)
    {
        ErrorMessage errorMessage = new ErrorMessage("400 Bad request",
                "Please provide the values for the book you want to create!");
        throw new MyWebServiceException(Response.Status.BAD_REQUEST,
                errorMessage);
    }

    //create the JAXBElement corresponding to the XML code from inside the string
    JAXBContext jc = null;
    Unmarshaller unmarshaller;
    JAXBElement<Book> jaxbElementBook = null;
    try {
        jc = JAXBContext.newInstance(Book.class);
        unmarshaller = jc.createUnmarshaller();
        StreamSource source = new StreamSource(new StringReader(code));
        jaxbElementBook = unmarshaller.unmarshal(source, Book.class);
    } catch (JAXBException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }