当前位置: 代码网 > it编程>编程语言>Java > 一文详解Spring中ResponseEntity包装器的使用

一文详解Spring中ResponseEntity包装器的使用

2025年02月13日 Java 我要评论
简介在 spring 中,responseentity 是 http 响应的包装器。它允许自定义响应的各个方面:http 状态码响应主体http 请求头使用 responseentity 允许完全控制

简介

spring 中,responseentityhttp 响应的包装器。它允许自定义响应的各个方面:

  • http 状态码
  • 响应主体
  • http 请求头

使用 responseentity 允许完全控制 http 响应,并且它通常用于 restful web 服务中从控制器方法返回响应。

基本语法

responseentity<t> response = new responseentity<>(body, headers, status);
  • t:响应主体的类型
  • body:想要作为响应主体发送的对象(如果不想返回主体,则可以为空)
  • headers:想要包含的任何其他 http 请求头
  • status:http 状态代码(如 httpstatus.ok、httpstatus.created等)

示例用法

基本用法:返回简单响应

@restcontroller
@requestmapping("/api/posts")
public class postcontroller {

    @getmapping("/{id}")
    public responseentity<post> getpost(@pathvariable long id) {
        post post = postservice.findbyid(id);
        if (post != null) {
            return new responseentity<>(post, httpstatus.ok);  // 200 ok
        } else {
            return new responseentity<>(httpstatus.not_found);  // 404 not found
        }
    }
}

返回带有请求头的 responseentity

@getmapping("/custom-header")
public responseentity<string> getwithcustomheader() {
    httpheaders headers = new httpheaders();
    headers.add("custom-header", "customvalue");

    return new responseentity<>("hello with custom header!", headers, httpstatus.ok);
}

返回具有创建状态的 responseentity

创建新资源时,通常希望返回 201 created 状态代码

@postmapping("/create")
public responseentity<post> createpost(@requestbody post post) {
    post createdpost = postservice.save(post);
    uri location = servleturicomponentsbuilder.fromcurrentrequest()
            .path("/{id}")
            .buildandexpand(createdpost.getid())
            .touri();

    return responseentity.created(location).body(createdpost);
}

返回没有内容的 responseentity

当成功处理一个请求但不需要返回任何内容(例如,一个 delete 请求)时,可以使用 204 no content

@deletemapping("/{id}")
public responseentity<void> deletepost(@pathvariable long id) {
    boolean isdeleted = postservice.delete(id);
    if (isdeleted) {
        return new responseentity<>(httpstatus.no_content);  // 204 no content
    } else {
        return new responseentity<>(httpstatus.not_found);   // 404 not found
    }
}

使用带有异常处理的 responseentity

可以在全局异常处理程序或控制器中使用 responseentity 来处理异常

@exceptionhandler(postnotfoundexception.class)
public responseentity<string> handlepostnotfound(postnotfoundexception ex) {
    return new responseentity<>(ex.getmessage(), httpstatus.not_found);
}

使用 map 返回 responseentity(例如,对于 json 响应)

@getmapping("/user/{id}")
public responseentity<map<string, object>> getuser(@pathvariable long id) {
    map<string, object> response = new hashmap<>();
    user user = userservice.findbyid(id);

    if (user != null) {
        response.put("status", "success");
        response.put("data", user);
        return new responseentity<>(response, httpstatus.ok);
    } else {
        response.put("status", "error");
        response.put("message", "user not found");
        return new responseentity<>(response, httpstatus.not_found);
    }
}

具有泛型类型的 responseentity

@getmapping("/posts/{id}")
public responseentity<post> getpostbyid(@pathvariable long id) {
    post post = postservice.findbyid(id);
    if (post != null) {
        return responseentity.ok(post);  // 200 ok with post object as body
    }
    return responseentity.status(httpstatus.not_found).build();  // 404 not found with no body
}

// responseentity.ok(post) 是 new responseentity<>(post, httpstatus.ok) 的简写

返回验证错误的 responseentity

@postmapping("/validate")
public responseentity<map<string, string>> validateuser(@requestbody user user, bindingresult result) {
    if (result.haserrors()) {
        map<string, string> errorresponse = new hashmap<>();
        result.getfielderrors().foreach(error -> errorresponse.put(error.getfield(), error.getdefaultmessage()));
        return new responseentity<>(errorresponse, httpstatus.bad_request);  // 400 bad request
    }
    userservice.save(user);
    return new responseentity<>(httpstatus.created);  // 201 created
}

使用统一的响应对象

1.定义统一响应对象

public class apiresponse<t> {

    private string status;
    private string message;
    private t data;
    private errordetails error;

    // constructor for success response
    public apiresponse(string status, string message, t data) {
        this.status = status;
        this.message = message;
        this.data = data;
    }

    // constructor for error response
    public apiresponse(string status, string message, errordetails error) {
        this.status = status;
        this.message = message;
        this.error = error;
    }

    // getters and setters
}

class errordetails {
    private string timestamp;
    private int status;
    private string error;
    private string path;

    // getters and setters
}

2.在控制器方法中使用统一响应

@getmapping("/posts/{id}")
public responseentity<apiresponse<post>> getpostbyid(@pathvariable long id) {
    post post = postservice.findbyid(id);
    if (post != null) {
        apiresponse<post> response = new apiresponse<>(
            "success", 
            "post retrieved successfully", 
            post
        );
        return new responseentity<>(response, httpstatus.ok);
    } else {
        return geterrorresponse(httpstatus.not_found, "post not found", "/api/posts/" + id);
    }
}
private responseentity<apiresponse<post>> geterrorresponse(httpstatus status, string message, string path) {
    errordetails errordetails = new errordetails();
    errordetails.settimestamp(localdatetime.now().tostring());
    errordetails.setstatus(status.value());
    errordetails.seterror(status.getreasonphrase());
    errordetails.setpath(path);

    apiresponse<post> response = new apiresponse<>(
        "error",
        message,
        errordetails
    );

    return new responseentity<>(response, status);
}

响应数据结构示例

1.success

{
  "status": "success",
  "message": "post retrieved successfully",
  "data": {
    "id": 1,
    "title": "hello world",
    "content": "this is my first post"
  }
}

2.error

{
  "status": "error",
  "message": "post not found",
  "error": {
    "timestamp": "2025-02-07t06:43:41.111+00:00",
    "status": 404,
    "error": "not found",
    "path": "/api/posts/1"
  }
}

3.使用 @controlleradvice 全局统一处理异常

@controlleradvice
public class globalexceptionhandler {

    // handle all exceptions
    @exceptionhandler(exception.class)
    public responseentity<apiresponse<object>> handlegeneralexception(exception ex) {
        errordetails errordetails = new errordetails();
        errordetails.settimestamp(localdatetime.now().tostring());
        errordetails.setstatus(httpstatus.internal_server_error.value());
        errordetails.seterror("internal server error");
        errordetails.setpath("/api/posts");

        apiresponse<object> response = new apiresponse<>("error", ex.getmessage(), errordetails);
        return new responseentity<>(response, httpstatus.internal_server_error);
    }
}

常用的 http 状态码

  • httpstatus.ok:200 ok
  • httpstatus.created:201 created
  • httpstatus.no_content:204 no content
  • httpstatus.bad_request:400 bad request
  • httpstatus.unauthorized:401 unauthorized
  • httpstatus.forbidden:403 forbidden
  • httpstatus.not_found:404 not found
  • httpstatus.internal_server_error:500 internal server error

到此这篇关于一文详解spring中responseentity包装器的使用的文章就介绍到这了,更多相关spring responseentity包装器内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com