我如何在Tomcat上的JAX-RS(Jersey)中返回HTTP 404 JSON/XML响应?

IJR*_*IJR 31 java rest tomcat http-status-code-404 jersey-2.0

我有以下代码:

@Path("/users/{id}")
public class UserResource {

    @Autowired
    private UserDao userDao;

    @GET
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public User getUser(@PathParam("id") int id) {
        User user = userDao.getUserById(id);
        if (user == null) {
            throw new NotFoundException();
        }
        return user;
    }
Run Code Online (Sandbox Code Playgroud)

如果我请求不存在的用户,例如/users/1234" Accept: application/json",则此代码返回一个HTTP 404人们期望的响应,但返回Content-Type设置为text/htmlhtml的正文消息.注释@Produces被忽略.

这是代码问题还是配置问题?

Sve*_*rev 32

您的@Produces注释被忽略,因为jax-rs运行时使用预定义(默认)处理未捕获的异常ExceptionMapper如果要在特定异常的情况下自定义返回的消息,您可以创建自己的异常ExceptionMapper来处理它.在您的情况下,您需要一个处理NotFoundException异常并查询所请求的响应类型的"accept"标头:

@Provider
public class NotFoundExceptionHandler implements ExceptionMapper<NotFoundException>{

    @Context
    private HttpHeaders headers;

    public Response toResponse(NotFoundException ex){
        return Response.status(404).entity(yourMessage).type( getAcceptType()).build();
    }

    private String getAcceptType(){
         List<MediaType> accepts = headers.getAcceptableMediaTypes();
         if (accepts!=null && accepts.size() > 0) {
             //choose one
         }else {
             //return a default one like Application/json
         }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 尝试不同的解决方案后,这是最好的和正确的解决方案。映射 *NotFoundException* 不是强制性的。只需使用 Exception 并执行您需要的操作 (2认同)

Tia*_*ago 15

您可以使用响应返回.示例如下:

@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response get(@PathParam("id") Long id) {
    ExampleEntity exampleEntity = getExampleEntityById(id);

    if (exampleEntity != null) {
        return Response.ok(exampleEntity).build();
    }

    return Response.status(Status.NOT_FOUND).build();
}
Run Code Online (Sandbox Code Playgroud)