问题
I have a Jersey REST API that returns 204 No content instead of 404 when the entity to be returned back is null.
To address this issue, I'm currently planning to throw an exception within the resource method so that it could force Jersey to return 404 like below.
if (feature == null) throw new WebApplicationException(404);
But I have various REST URIs that suffer from the same problem. Is there a way to address all of them without touching each and every resource method?
My resource methods look like this:
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.example.webapi.domain.Feature;
import com.example.webapi.service.FeatureService;
@Component
@Path("features")
@Produces(MediaType.APPLICATION_JSON)
public class FeatureResource {
@Autowired
private FeatureService featureService;
@GET
public List<Feature> getFeatures() {
return featureService.listAllFeatures();
}
@GET
@Path("{featureCode}")
public Feature getFeature(@PathParam("featureCode") Integer featuresCode) {
return featureService.findFeatureByFeatureCode(featuresCode);
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response addFeature(Feature feature, @Context UriInfo uriInfo) {
Integer id = (Integer) featureService.createFeature(feature);
return Response.created(uriInfo.getAbsolutePathBuilder().path(id.toString()).build()).entity(feature).build();
}
}
回答1:
you can implement ContainerResponseFilter and customise the response based on your requirement.
ex:
@Provider
public class LoggingResponseFilter
implements ContainerResponseFilter {
private static final Logger logger = LoggerFactory.getLogger(LoggingResponseFilter.class);
public void filter(ContainerRequestContext requestContext,
ContainerResponseContext responseContext) throws IOException {
String method = requestContext.getMethod();
logger.debug("Requesting " + method + " for path " + requestContext.getUriInfo().getPath());
Object entity = responseContext.getEntity();
if (entity != null) {
logger.debug("Response " + new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(entity));
}
}
}
Customize the above code and implement your business logic.
回答2:
You can use Request or Response filters depends on what you want to check for null.
check the docs here
来源:https://stackoverflow.com/questions/37327582/how-to-return-http-404-instead-of-http-204-response-code-for-null-values-in-jers