Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在Tomcat上返回JAX-RS(Jersey)格式的HTTP404JSON/XML响应?_Java_Rest_Tomcat_Http Status Code 404_Jersey 2.0 - Fatal编程技术网

Java 如何在Tomcat上返回JAX-RS(Jersey)格式的HTTP404JSON/XML响应?

Java 如何在Tomcat上返回JAX-RS(Jersey)格式的HTTP404JSON/XML响应?,java,rest,tomcat,http-status-code-404,jersey-2.0,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 use

我有以下代码:

@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
,并带有“
Accept:application/json
”,则此代码会像预期的那样返回一个
http404
响应,但会返回
Content-Type
设置为
text/html
,并返回一条html正文消息。注释
@products
被忽略


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

您的服务器返回404,因为预期您将以以下形式传递内容

/users/{id}
但你把它当作

/users/user/{id}
哪种资源根本不存在

尝试以
/users/1234

编辑:

创建一个类,如

class RestResponse<T>{
private String status;
private String message;
private List<T> objectList;
//gettrs and setters
}
您的rest方法的签名如下

RestResponse<User> resp = new RestResponse<User>();
resp.setStatus("400");
resp.setMessage("User does not exist");
public RestResponse<User> getUser(@PathParam("id") int id)
public response getUser(@PathParam(“id”)int-id)
如果响应成功,您可以设置如下内容

RestResponse<User> resp = new RestResponse<User>();
List<User> userList = new ArrayList<User>();
userList.add(user);//the user object you want to return
resp.setStatus("200");
resp.setMessage("User exist");
resp.setObjectList(userList);
response resp=new response();
List userList=new ArrayList();
添加(用户)//要返回的用户对象
分别为固定状态(“200”);
相应设置消息(“用户存在”);
分别为setObjectList(用户列表);

您的
@生成的
注释被忽略,因为未捕获的异常由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
         }
    }
}
@Provider
公共类NotFoundExceptionHandler实现ExceptionMapper{
@上下文
私有HttpHeader;
公众对响应的响应(非发现异常){
返回Response.status(404).entity(yourMessage).type(getAcceptType()).build();
}
私有字符串getAcceptType(){
List accepts=headers.getAcceptableMediaTypes();
if(accepts!=null&&accepts.size()>0){
//选一个
}否则{
//返回一个默认值,如Application/json
}
}
}

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

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

URI请求更新,我键入URI时出错。正确的URI是users/1234,以获取404响应,html格式,而不是JSON格式。我的问题不是响应代码,而是响应的格式(内容类型)。请从产品中删除MediaType.APPLICATION_XML并重试,同时确保在用户不存在的情况下给出正确的消息。通常我们创建一个rest响应,其中包含用户请求的状态和消息,当有人尝试访问资源时,我们返回的响应与我尝试从annotation@Products中删除MediaType.APPLICATION_XML时的响应相同,我得到的结果是相同的,一个文本/html内容类型的404响应。这就像Tomcat被内容类型和正文消息覆盖一样…正如我在上面的评论中提到的,如果用户不存在,您需要传递一个类的对象,该类包含状态和消息,您需要显式设置状态将编辑Ans,可能我会混合使用两种方法(VD’&Svetlin Zarev),将ExceptionMapper与实体一起使用,该实体不仅是字符串消息,而且是具有某些属性(如状态代码、消息等)的对象。谢谢!我测试过了。我继续抛出NotFoundException,但现在使用ExceptionMapper将该异常映射到设置状态代码和媒体类型。它起作用了!在此之前,我试图返回一个等价的响应,而不是抛出NotFoundException,但我得到了相同的结果,一个text/HTML404响应。这种行为是因为如果我的应用程序抛出NotFoundException,则默认(隐式)ExceptionMapper将进入并覆盖我返回到html响应的响应吗?谢谢在尝试了不同的解决方案后,这是最好和正确的解决方案。映射NotFoundException不是必须的。只需使用Exception并执行您需要的操作need@Provider这是非常重要的