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

标签 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;
    }

如果我使用“Accept: application/json”请求不存在的用户,例如 /users/1234,此代码将返回 HTTP 404 响应如预期的那样,但返回 Content-Type 设置为 text/html 和 html 的正文消息。注释 @Produces 被忽略。

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

最佳答案

您的 @Produces 注释将被忽略,因为 jax-rs 运行时使用预定义的(默认)ExceptionMapper 处理未捕获的异常。如果遇到特定异常,您可以创建自己的 ExceptionMapper 来处理它。在您的情况下,您需要一个处理 NotFoundException 异常并查询“接受” header 以获取所请求的响应类型:

@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
         }
    }
}

关于java - 如何在 Tomcat 上的 JAX-RS (Jersey) 中返回 HTTP 404 JSON/XML 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23858488/

相关文章:

angularjs - Spring Rest应用程序和异常本地化

rest - 微服务架构中UI数据聚合最好的地方在哪里

tomcat - 安全约束套管问题中的 url 模式

java - 在 spring boot 中使用现有的 http 服务器作为 Camel 端点

java - AngularJS/Spring MVC - 访问 Controller 中的表单数据时出现问题

java - Spring 用户事务与 hibernate

java - 非法状态异常 : getInputStream() has already been called for this request

tomcat - 如何将多个上下文映射到 Tomcat 中的同一个 war 文件?

java - 在运行时更改 CoreNLP 设置

java - 逐渐填充对象(正确的设计?)