当前位置: 首页> 教育> 就业 > 长春网站制作套餐_网站编辑岗位_营销模式有几种_百度电话查询

长春网站制作套餐_网站编辑岗位_营销模式有几种_百度电话查询

时间:2025/7/8 20:53:54来源:https://blog.csdn.net/weixin_37646636/article/details/148741710 浏览次数:0次
长春网站制作套餐_网站编辑岗位_营销模式有几种_百度电话查询

典型用法

基本用法:返回 JSON 数据

@GetMapping("/users/{id}")
@ResponseBody
public User getUser(@PathVariable Long id) {return userService.findById(id);
}

Spring 自动使用 Jackson(或其他 HttpMessageConverter)将 User 对象序列化为 JSON。
响应头 Content-Type 默认为 application/json。

结合 @Controller 使用(等价于 @RestController)

@RestController = @Controller + 所有方法默认加 @ResponseBody

@Controller
public class UserController {@GetMapping("/users")@ResponseBodypublic List<User> getAllUsers() {return userService.findAll();}
}等价于使用
@RestController
public class UserController {@GetMapping("/users")public List<User> getAllUsers() {return userService.findAll();}
}

返回统一响应结构(推荐做法)

实际项目中通常会封装统一的响应格式,如:

public class ApiResponse<T> {private int code;private String message;private T data;// 构造器、getter/setter
}@GetMapping("/users/{id}")
@ResponseBody
public ApiResponse<User> getUser(@PathVariable Long id) {User user = userService.findById(id);return ApiResponse.success(user);
}// 响应示例(JSON):
{"code": 200,"message": "OK","data": {"id": 1,"name": "Alice"}
}

支持 XML 输出(需配置 Jackson XML 模块)

如果客户端请求头指定 Accept: application/xml,Spring 可以自动返回 XML 格式:

@GetMapping(value = "/users", produces = MediaType.APPLICATION_XML_VALUE)
@ResponseBody
public List<User> getAllUsersInXml() {return userService.findAll();
}// 响应示例(XML):
<user><id>1</id><name>Alice</name>
</user>

返回字符串原始内容(不序列化)

如果你希望直接返回字符串内容而不是 JSON,可以这样做:

@GetMapping("/hello")
@ResponseBody
public String sayHello() {return "Hello, World!";
}

结合 ResponseEntity 使用(更灵活控制响应)

虽然 @ResponseBody 很方便,但如果你需要控制状态码或响应头,建议使用 ResponseEntity:

@GetMapping("/users")
public ResponseEntity<List<User>> getAllUsers() {List<User> users = userService.findAll();return ResponseEntity.ok().header("X-Custom-Header", "value").body(users);
}
关键字:长春网站制作套餐_网站编辑岗位_营销模式有几种_百度电话查询

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: