我有以下代码:
@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/