簡體   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