我有一个Jersey REST API,当要返回的实体为null
时,返回204无内容而不是404。
为了解决这个问题,我目前正计划在资源方法中抛出一个异常,以便它可以强制Jersey返回404,如下所示。
if (feature == null) throw new WebApplicationException(404);
但我有各种各样的REST URI遭遇同样的问题。有没有办法解决所有这些问题而不涉及每种资源方法?
我的资源方法如下所示:
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();
}
}
答案 0 :(得分:1)
您可以使用请求或响应过滤器取决于您要检查的内容。
检查文档here
答案 1 :(得分:1)
您可以实施ContainerResponseFilter并根据您的要求自定义响应。
例如:
@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));
}
}
}
自定义上述代码并实现您的业务逻辑。