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

Men*_*nno 4 java rest unmarshalling

我正在为我的RESTful Web服务创建一个客户端.在这种情况下,我的服务器不会总是返回预期的对象(例如,在给定参数上找不到任何内容,因此返回为NULL).

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

如果找不到给定的名称,byName()方法将返回NULL.在解组给定对象时,这将引发异常.什么是最常见和最简洁的方法来导致if/else语句或以不同方式处理返回的东西?

JAXBContext jcUnmarshaller = JAXBContext.newInstance(Person.class);
Unmarshaller unmarshaller = jcUnmarshaller.createUnmarshaller();
return (Person) unmarshaller.unmarshal(connection.getInputStream());
Run Code Online (Sandbox Code Playgroud)

getPerson( ) throws WebApplicationException { 
    throw new WebApplicationException(404);
}
Run Code Online (Sandbox Code Playgroud)

Tom*_*icz 8

处理此类情况的惯用方法是返回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;
} 
Run Code Online (Sandbox Code Playgroud)