2012-11-30 33 views
1

我有以下方法,即接收XML,并创建一个新的书在数据库:检查JAXBElement的参数为空

@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); 
    } 
     .................................................................... 
} 

的问题是,当我没有在邮件正文发送任何东西,该异常不会被抛出。我如何检查邮件正文是否为空?

谢谢!

索林

+0

你想从客户端或服务器端得到错误信息? – bhuang3

+0

从服务器端 –

回答

0

我发现了一个小窍门,可以做的:不是发送MediaType.APPLICATION_XML,我送应用程序/ x-WWW窗体-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(); 
    } 
0

试试这个:

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

不起作用... –

0

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

+0

不起作用...我也试过与bookParam.isNil() –

+1

@SorinAdrianCarbunaru你确定这个方法被调用吗?在方法的顶部打印日志消息或其他内容来检查。 [这篇博文](http://theholyjava.wordpress.com/2012/01/31/troubleshooting-jersey-rest-server-and-client/)给出了一些关于如何调试事情的提示,以及如何计算球衣正在处理一个特定的请求。 –

+0

看来,当http消息正文为空时,该方法内部没有任何内容会被执行......我认为我应该只检查客户端是否发送了 –