我如何在Tomcat上的JAX-RS(Jersey)中返回HTTP 404 JSON / XML响应? [英] How I return HTTP 404 JSON/XML response in JAX-RS (Jersey) on Tomcat?

查看:127
本文介绍了我如何在Tomcat上的JAX-RS(Jersey)中返回HTTP 404 JSON / XML响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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

如果我要求不存在的用户,例如 / users / 1234 接受:application / json ,此代码返回 HTTP 404 响应就像人们期望的那样,但返回 Content-Type 设置为 text / html 和a html的正文消息。注释 @Produces 将被忽略。

If I request for a user that doesn't exists, like /users/1234, with "Accept: application/json", this code returns an HTTP 404 response like one would expect, but returns Content-Type sets to text/html and a body message of html. Annotation @Produces is ignored.

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

Is it a problem of code or a problem of configuration?

推荐答案

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

Your @Produces annotation is ignored because uncaught exceptions are processed by the jax-rs runtime using a predefined (default) ExceptionMapper If you want to customize the returned message in case of a specific exception you can create your own ExceptionMapper to handle it. In your case you need one to handle the NotFoundException exception and query the "accept" header for the requested type of the response:

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

这篇关于我如何在Tomcat上的JAX-RS(Jersey)中返回HTTP 404 JSON / XML响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆