当前位置: 首页 > news >正文

wordpress建地方门户seo网站优化详解

wordpress建地方门户,seo网站优化详解,工作室logo设计免费生成,北京时间网站建设Spring MVC 处理 HTTP 状态码、响应头和异常的完整示例 1. 正常响应处理 通过 ResponseEntity 可以灵活控制 HTTP 状态码、响应头和响应体。 代码示例:创建资源返回 201 并设置 Location 头 import org.springframework.http.HttpHeaders; import org.springfram…

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 {@PostMappingpublic ResponseEntity<User> createUser(@RequestBody User user) {// 保存用户逻辑(假设已成功保存)user.setId(1L); // 假设生成的用户ID为1// 设置 Location 头指向新资源的 URIHttpHeaders 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),优先使用标准枚举值。
http://www.dtcms.com/a/565651.html

相关文章:

  • 网站开发总体流程图厦门做网站哪家公司好
  • Windows11 C 盘空间不足如何无损扩展分区?
  • 上海住房和城乡建设厅网站怎么制作网站建设
  • Qt-VLC: 一个集成VLC的开源跨平台媒体播放库
  • 上海做网站哪里好163公司企业邮箱
  • UVa 11776 Oh Your Royal Greediness
  • 做网站的报价方案个人备案网站盈利
  • vue项目的项目结构
  • ASP Application
  • 网站建设费无形资产示范高职院校建设专题网站
  • 软件系统可行性分析深度解析:从题目到实战答案全解析
  • 香港高防云服务器的优劣势分析(相比普通云服务器)
  • xxljob定时任务三种方式的实现
  • 咸阳机场停车省钱攻略
  • 毕设网站开发需要做什么梅州建站推荐
  • 装饰行业网站建设公司网站开发人员的的工资多少
  • 网站后台系统的易用性网站域名实名认证
  • 国产化Word处理控件Spire.Doc教程:如何使用 Java 将 TXT 文本转换为 Excel 表格
  • 结构化类型VS标称类型:TS类型系统全解析
  • Git笔记之Git下载、拉取项目、Webstorm更新Git项目报错识别不到git
  • Linux之arm SMMUv3 控制器注册过程分析(7)
  • 临沧市住房和城乡建设网站企业咨询管理公司简介
  • 13-卷积神经网络(CNN):探讨CNN在图像处理中的应用和优势
  • Spring Boot3零基础教程,StreamAPI 的基本用法,笔记99
  • seo关键词排名优化教程seo网站架构设计
  • 宿州做企业网站公司咸阳网站制作公司
  • 一个空间建多个网站的方法wordpress显示用户列表
  • Java中的数组(续)
  • 2025年内蒙古自治区职业院校技能大赛高职组 “信息安全管理与评估”竞赛样题(一)
  • 嵌入式Linux电源管理实战 --深入解析CPU调频governor原理与优化