1

我有以下方法,它接收 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);
    }
        ....................................................................
}

问题是,当我在消息正文中不发送任何内容时,不会引发异常。如何检查邮件正文是否为空?

谢谢!

索林

4

3 回答 3

0

试试这个:

public SuccessfulRequestMessage createBook(JAXBElement<Book> bookParam, 
                      @PathParam("isbn") String isbn) throws MyWebServiceException
于 2012-11-30T19:31:01.723 回答
0

可能它JAXBElement本身不是空的,但它的有效负载是。检查bookParam.getValue()以及只是bookParam

于 2012-11-30T19:48:01.223 回答
0

我发现了一个可以做到的小技巧:我没有发送MediaType.APPLICATION_XML,而是发送application/x-www-form-urlencoded,仅由一个参数表示,该参数将包含 XML 代码。然后我可以检查参数是空还是空。然后,根据参数的内容,构造一个 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();
    }
于 2012-12-05T16:43:09.663 回答