当前位置: 代码网 > it编程>编程语言>Java > Spring MVC处理HTTP状态码、响应头和异常的完整示例

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的资料请关注代码网其它相关文章!

(0)

相关文章:

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

发表评论

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