引言
Spring MVC 作为连接前端与后端的桥梁,赋予了开发者构建复杂业务逻辑和流畅用户体验的能力。在掌握了请求处理之后,接下来我们重点探讨如何规范地返回响应内容。
目录
- 设置响应状态码
- 配置报文格式
- 加法器示例(略)
一、设置响应状态码
在上篇中,我们学习了控制层如何处理请求,现在来看看如何自定义响应的 HTTP 状态码。默认情况下,Spring MVC 会根据业务逻辑返回 200 OK,但在某些场景下(如参数校验失败),我们需要返回特定的错误码。
1. 代码实现
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@RequestMapping("/response")
@Controller
public class ResponseController {
/**
* 设置状态码,利用 HttpServletResponse 来设置
*
* @param response 响应对象
* @return 返回数据
*/
@RequestMapping("/setStatus")
@ResponseBody
public Student setStatus(HttpServletResponse response) {
Student student = new Student();
student.setName("dalao");
student.setAge(18);
student.setGender("nv");
// 设置为 400 Bad Request
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return student;
}
}

关键点说明:



