繁体   English   中英

检查JAXBElement参数是否为null

[英]Check if JAXBElement parameter is null

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

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

谢谢!

索林

尝试这个:

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

JAXBElement本身可能不为null,但其有效载荷为。 检查bookParam.getValue()以及bookParam

我发现了一个可以完成的小技巧:而不是发送MediaType.APPLICATION_XML ,而是发送仅由一个参数表示的application / x-www-form-urlencoded ,并且此参数将包含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();
    }

暂无
暂无

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

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