How to return HTTP 404 instead of HTTP 204 response code for null values in jersey
我有一个 Jersey REST API,当要返回的实体是
时,它返回 204 No content 而不是 404
为了解决这个问题,我目前计划在资源方法中抛出一个异常,以便它可以强制 Jersey 返回 404,如下所示。
1 | if (feature == null) throw new WebApplicationException(404); |
但是我有各种 REST URI 遇到同样的问题。有没有办法在不触及每一个资源方法的情况下解决所有这些问题?
我的资源方法如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | 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(); } } |
您可以实现 ContainerResponseFilter 并根据您的要求自定义响应。
例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | @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)); } } |
}
自定义以上代码,实现你的业务逻辑。
您可以使用请求或响应过滤器,具体取决于您要检查的内容是否为空。
在此处查看文档