Springboot 项目中的 Controller 层面,在处理器返回值里面如何添加响应报文中响应头的信息
时间: 2023-07-15 08:10:38 浏览: 295
可以在Controller方法中使用@ResponseStatus和@ResponseBody注解分别设置响应状态和返回值。另外,可以使用HttpServletResponse对象来设置响应头信息,例如设置Content-Type和Cache-Control等。以下是一个示例代码:
```
@Controller
public class MyController {
@RequestMapping("/hello")
@ResponseBody
@ResponseStatus(HttpStatus.OK)
public String hello(HttpServletResponse response) {
response.setHeader("Content-Type", "application/json;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
return "{\"message\":\"Hello, world!\"}";
}
}
```
在上面的例子中,@RequestMapping注解用于指定处理请求的URL路径。@ResponseBody注解用于告诉Spring MVC将方法返回的字符串作为响应体返回,而不是视图名称。@ResponseStatus注解用于指定响应状态码。在方法中通过HttpServletResponse对象设置响应头的信息。最后返回的是一个JSON字符串。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![7z](https://img-home.csdnimg.cn/images/20241231044736.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)