spring mvc 处理 http 状态码、响应头和异常的完整示例
1. 正常响应处理
通过 responseentity
可以灵活控制 http 状态码、响应头和响应体。
代码示例:创建资源返回 201 并设置 location 头
import org.springframework.http.httpheaders; import org.springframework.http.httpstatus; import org.springframework.http.responseentity; import org.springframework.web.bind.annotation.*; @restcontroller @requestmapping("/api/users") public class usercontroller { @postmapping public responseentity<user> createuser(@requestbody user user) { // 保存用户逻辑(假设已成功保存) user.setid(1l); // 假设生成的用户id为1 // 设置 location 头指向新资源的 uri httpheaders headers = new httpheaders(); headers.setlocation(servleturicomponentsbuilder .fromcurrentrequest() .path("/{id}") .buildandexpand(user.getid()) .touri()); return new responseentity<>(user, headers, httpstatus.created); // 201 created } }
代码示例:成功响应返回 200 并设置 cache-control 头
@getmapping("/{id}") public responseentity<user> getuser(@pathvariable long id) { user user = userservice.findbyid(id); // 假设用户存在 httpheaders headers = new httpheaders(); headers.setcachecontrol(cachecontrol.nocache()); // 禁止缓存 return new responseentity<>(user, headers, httpstatus.ok); // 200 ok }
2. 异常处理
通过 @responsestatus
和 @controlleradvice
实现异常状态码与响应控制。
自定义异常类(带 @responsestatus)
import org.springframework.http.httpstatus; import org.springframework.web.bind.annotation.responsestatus; @responsestatus(code = httpstatus.not_found, reason = "user not found") public class usernotfoundexception extends runtimeexception { public usernotfoundexception(string message) { super(message); } }
全局异常处理类(@controlleradvice)
import org.springframework.http.httpstatus; import org.springframework.http.responseentity; import org.springframework.web.bind.annotation.*; @controlleradvice public class globalexceptionhandler { @exceptionhandler(usernotfoundexception.class) public responseentity<errordetails> handleusernotfound( usernotfoundexception ex, webrequest request) { errordetails error = new errordetails( httpstatus.not_found.value(), ex.getmessage(), request.getdescription(false) ); return new responseentity<>(error, httpstatus.not_found); } @exceptionhandler(exception.class) public responseentity<errordetails> handlegeneralexception( exception ex, webrequest request) { errordetails error = new errordetails( httpstatus.internal_server_error.value(), "internal server error", request.getdescription(false) ); return new responseentity<>(error, httpstatus.internal_server_error); } // 辅助类:错误响应体 private static class errordetails { private int statuscode; private string message; private string path; public errordetails(int statuscode, string message, string path) { this.statuscode = statuscode; this.message = message; this.path = path; } // 省略 getter/setter } }
3. 响应头设置示例
@getmapping("/custom-headers") public responseentity<string> customheaders() { httpheaders headers = new httpheaders(); headers.add("x-custom-header", "custom-value"); headers.set("content-type", "text/plain"); headers.set("access-control-allow-origin", "*"); return new responseentity<>("response with custom headers", headers, httpstatus.ok); }
4. 关键注解与类说明
注解/类 | 作用 | 示例 |
---|---|---|
@responsestatus | 在异常类上定义默认 http 状态码和原因。 | @responsestatus(httpstatus.not_found) |
responseentity | 直接控制 http 状态码、响应头和响应体。 | new responseentity<>(data, headers, httpstatus.ok) |
@controlleradvice | 全局异常处理类,集中管理异常响应。 | @controlleradvice + @exceptionhandler |
httpstatus | http 状态码枚举(如 httpstatus.ok, httpstatus.created)。 | httpstatus.not_found |
5. 场景总结表格
场景 | 实现方式 | 状态码 | 响应头示例 | 适用情况 |
---|---|---|---|---|
成功创建资源 | responseentity + httpstatus.created | 201 | location: /api/users/1 | 新资源创建成功后返回位置 |
返回成功数据 | responseentity + httpstatus.ok | 200 | cache-control: no-cache | 正常业务响应 |
资源不存在异常 | @responsestatus(httpstatus.not_found) | 404 | 无 | 资源查询失败 |
全局异常处理(如服务器错误) | @controlleradvice + @exceptionhandler | 500 | 无 | 捕获通用未处理异常 |
自定义响应头 | responseentity 设置 httpheaders | 200 | x-custom-header: custom-value | 需要添加自定义响应头时 |
关键总结
- 状态码控制:
responseentity
直接指定状态码(如httpstatus.created
)。@responsestatus
在异常类上定义默认状态码。
- 响应头管理:
- 通过
httpheaders
对象添加任意头信息。
- 通过
- 异常处理:
- 自定义异常 +
@responsestatus
:针对特定异常返回状态码。 @controlleradvice
:全局统一处理异常,返回结构化错误信息。
- 自定义异常 +
- 最佳实践:
- 使用
responseentity
精确控制响应细节。 - 通过
errordetails
统一错误响应格式。 - 对于常见 http 状态码(如 404、500),优先使用标准枚举值。
- 使用
以上就是spring mvc处理http状态码、响应头和异常的完整示例的详细内容,更多关于spring mvc处理http的资料请关注代码网其它相关文章!
发表评论