簡體   English   中英

RESTful Web Service的返回值,考慮空值

[英]Return value of RESTful Web Service, taking a null value into account

我正在為我的RESTful Web服務創建一個客戶端。 在這種情況下,我的服務器不會總是返回預期的對象(例如,在給定參數上找不到任何內容,因此返回為NULL)。

@GET
@Path("/person/{name}")
@Produces("application/xml")
public Person getPerson(@PathParam("name") String name) {
    return people.byName(name);
}

如果找不到給定的名稱,byName()方法將返回NULL。 在解組給定對象時,這將引發異常。 什么是最常見和最簡潔的方法來導致if / else語句或以不同方式處理返回的東西?

JAXBContext jcUnmarshaller = JAXBContext.newInstance(Person.class);
Unmarshaller unmarshaller = jcUnmarshaller.createUnmarshaller();
return (Person) unmarshaller.unmarshal(connection.getInputStream());

getPerson( ) throws WebApplicationException { 
    throw new WebApplicationException(404);
}

處理此類情況的慣用方法是返回404 Not Found響應代碼。 使用您可以拋出WebApplicationException

@GET
@Path("/person/{name}")
@Produces("application/xml")
public Person getPerson(@PathParam("name") String name) {
    Person personOrNull = people.byName(name);
    if(personOrNull == null) {
      throw new WebApplicationException(404);
    }   
    return personOrNull;
} 

如果您正在尋找純REST服務,則應該返回HTTP響應代碼404 - 找不到某個人時找不到。 所以,它看起來像這樣:

public Person getPerson(@PathParam("name") String name) {
    Person person = people.byName(name);
    if (null != person) {
       return person
    }
    else {
       //return 404 response code (not sure how to do that with what you're using)
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM