欢迎来到徐庆高(Tea)的个人博客网站
磨难很爱我,一度将我连根拔起。从惊慌失措到心力交瘁,我孤身一人,但并不孤独无依。依赖那些依赖我的人,信任那些信任我的人,帮助那些给予我帮助的人。如果我愿意,可以分裂成无数面镜子,让他们看见我,就像看见自己。察言观色和模仿学习是我的领域。像每个深受创伤的人那样,最终,我学会了随遇而安。
当前位置: 日志文章 > 详细内容

Spring MVC处理HTTP状态码、响应头和异常的完整示例

2025年08月21日 Java
spring mvc 处理 http 状态码、响应头和异常的完整示例1. 正常响应处理通过 responseentity 可以灵活控制 http 状态码、响应头和响应体。代码示例:创建资源返回 201

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
httpstatushttp 状态码枚举(如 httpstatus.ok, httpstatus.created)。httpstatus.not_found

5. 场景总结表格

场景实现方式状态码响应头示例适用情况
成功创建资源responseentity + httpstatus.created201location: /api/users/1新资源创建成功后返回位置
返回成功数据responseentity + httpstatus.ok200cache-control: no-cache正常业务响应
资源不存在异常@responsestatus(httpstatus.not_found)404资源查询失败
全局异常处理(如服务器错误)@controlleradvice + @exceptionhandler500捕获通用未处理异常
自定义响应头responseentity 设置 httpheaders200x-custom-header: custom-value需要添加自定义响应头时

关键总结

  1. 状态码控制
    • responseentity 直接指定状态码(如 httpstatus.created)。
    • @responsestatus 在异常类上定义默认状态码。
  2. 响应头管理
    • 通过 httpheaders 对象添加任意头信息。
  3. 异常处理
    • 自定义异常 + @responsestatus:针对特定异常返回状态码。
    • @controlleradvice:全局统一处理异常,返回结构化错误信息。
  4. 最佳实践
    • 使用 responseentity 精确控制响应细节。
    • 通过 errordetails 统一错误响应格式。
    • 对于常见 http 状态码(如 404、500),优先使用标准枚举值。

以上就是spring mvc处理http状态码、响应头和异常的完整示例的详细内容,更多关于spring mvc处理http的资料请关注代码网其它相关文章!