1.介绍
ResponseEntity继承了HttpEntity类,HttpEntity代表一个http请求或者响应实体,其内部有两个成员变量:header及body,代表http请求或响应的header及body,其中的body是泛化的。
ResponseEntity类,扩展了HttpEntity类,新增了status成员变量,这样,一个ResponseEntity基本可以代表完整的http的请求或响应了。
代码语言:java复制public class ResponseEntity<T> extends HttpEntity<T> {
private final Object status;
public ResponseEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers, HttpStatus status) {
super(body, headers);
Assert.notNull(status, "HttpStatus must not be null");
this.status = status;
}
// 省略其他代码
}
2. ResponseEntity常用方法
2.1 只响应:状态码,不响应数据,如insert、update、delete操作时:
代码语言:java复制//方式一,使用ResponseEntiry的静态方法
return ResponseEntity.status(HttpStatus.BAD_REQUEST);
//方式二,使用ResponseEntiry的静态方法
return ResponseEntity.status(400);
//方式三,使用ResponseEntity的构造函数,通过数字状态码解析
return new ResponseEntity<>(HttpStatus.resolve(400));
//方式四,使用ResponseEntity的构造函数,通过枚举类型获取
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
2.2 只响应:数据
代码语言:java复制//使用ResponseEntiry的静态方法,默认状态码200,pageinfo是分页数据
return ResponseEntity.ok(pageInfo);
2.3 响应:数据 和 状态码
代码语言:java复制//使用ResponseEntity的构造函数
return new ResponseEntity<>(pageInfo,HttpStatus.resolve(200));
2.4 响应:状态码 和 头信息
代码语言:java复制//创建响应头对象,并添加头信息
HttpHeaders headers = new HttpHeaders();
headers.add("Custom-Header", "foo");
//使用ResponseEntity的构造函数
return new ResponseEntity<>(headers,HttpStatus.resolve(200));
2.5 响应:状态码 、数据 和 头信息
- 方式一
//创建响应头对象,并添加头信息
HttpHeaders headers = new HttpHeaders();
headers.add("Custom-Header", "foo");
//使用ResponseEntity的构造函数
return new ResponseEntity<>(pageInfo,headers,HttpStatus.resolve(200));
- 方式二
//创建响应头对象,并添加头信息
HttpHeaders headers = new HttpHeaders();
headers.add("Custom-Header", "foo");
//使用ResponseEntiry的静态方法,默认状态码200
return ResponseEntity.ok().header("Custom-Header", "001").body(pageInfo);
3、HttpStatus状态码
- HttpStaus是一个枚举类,包含了所有的状态码信息
public enum HttpStatus
代码语言:java复制package org.example.common.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@NoArgsConstructor
@AllArgsConstructor
public enum ExceptionEnum {
PRICE_CANNOT_BE_NULL(400, "价格不能为空"),
CATEGORY_NOT_FOUND(404, "商品分类没查到"),
BRAND_NOT_FOUND(404, "品牌不存在"),
BRAND_SAVE_ERROR(500, "新增品牌失败"),
;
private int code;
private String msg;
}
- 常用状态码对应表:其他的自行去HttpStatus枚举中查看
枚举属性 | 状态码 |
---|---|
CONTINUE | 100 |
OK | 200 |
CREATED | 201 |
NO_CONTENT | 204 |
PARTIAL_CONTENT | 206 |
MOVED_PERMANENTLY | 301 |
FOUND | 302 |
NOT_MODIFIED | 304 |
BAD_REQUEST | 400 |
UNAUTHORIZED | 401 |
FORBIDDEN | 403 |
NOT_FOUND | 404 |
INTERNAL_SERVER_ERROR | 500 |
SERVICE_UNAVAILABLE | 503 |
4 其他使用方法
- 方法一
public class ResponseEntity<T> extends HttpEntity<T> {
public ResponseEntity(HttpStatus status) {
this((Object)null, (MultiValueMap)null, (HttpStatus)status);
}
public ResponseEntity(@Nullable T body, HttpStatus status) {
this(body, (MultiValueMap)null, (HttpStatus)status);
}
public ResponseEntity(MultiValueMap<String, String> headers, HttpStatus status) {
this((Object)null, headers, (HttpStatus)status);
}
public ResponseEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers, HttpStatus status) {
super(body, headers);
Assert.notNull(status, "HttpStatus must not be null");
this.status = status;
}
private ResponseEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers, Object status) {
super(body, headers);
Assert.notNull(status, "HttpStatus must not be null");
this.status = status;
}
}
这个类提供了五个构造方法,返回的状态码是必传的外,头部信息以及响应体内容都是可选择的。当我们需要使用的时候,直接new一个ResponseEntity对象作为API返回值即可,这就是它的第一种使用方式。
需要注意的是,在有headers作为参数的构造方法中,需要传入一个类型为MultiValueMap<String, String>的参数。MultiValueMap继承自Map这个抽象类,其中拥有一个叫做HttpHeaders的子类,我们可以当它为一个key和value都为String类型的HashMap使用。HttpHeaders里面保存了一些常用的Header的key值,例如"Accept-Charset"。当然也可以自定义一些特殊的key。
代码语言:java复制HttpHeaders headers = new HttpHeaders();
headers.add("Access-Control-Expose-Headers", "AMP-Access-Control-Allow-Source-Origin");
return new ResponseEntity<>(resultBody, headers, HttpStatus.OK);
- 方法二 继续分析源码
public static ResponseEntity.BodyBuilder status(HttpStatus status) {
Assert.notNull(status, "HttpStatus must not be null");
return new ResponseEntity.DefaultBuilder(status);
}
public static ResponseEntity.BodyBuilder status(int status) {
return new ResponseEntity.DefaultBuilder(status);
}
public static ResponseEntity.BodyBuilder ok() {
return status(HttpStatus.OK);
}
public static ResponseEntity.BodyBuilder created(URI location) {
ResponseEntity.BodyBuilder builder = status(HttpStatus.CREATED);
return (ResponseEntity.BodyBuilder)builder.location(location);
}
public static ResponseEntity.BodyBuilder accepted() {
return status(HttpStatus.ACCEPTED);
}
public static ResponseEntity.HeadersBuilder<?> noContent() {
return status(HttpStatus.NO_CONTENT);
}
public static ResponseEntity.BodyBuilder badRequest() {
return status(HttpStatus.BAD_REQUEST);
}
public static ResponseEntity.HeadersBuilder<?> notFound() {
return status(HttpStatus.NOT_FOUND);
}
public static ResponseEntity.BodyBuilder unprocessableEntity() {
return status(HttpStatus.UNPROCESSABLE_ENTITY);
}
//.........
可以用Builder的方式去生成ResponseEntity对象并返回:
代码语言:java复制Map<String, String> resultBody = new HashMap<>();
resultBody.put("name":"Lucas");
resultBody.put("school":"harvard university");
return ResponseEntity.status(HttpStatus.OK)
.body(resultBody);
与其他方式对比
- @RestController注解修饰controller层。
@RestController = @Controller @ResponseBody
@ResponseBody是将controller的方法返回的对象通过适当的转换器转换为指定的格式之后,写入到response对象的body区,通常用来返回JSON数据或者是XML数据。
注意:在使用此注解之后不会再走视图处理器(ModelAndView),而是直接将数据写入到输入流中,他的效果等同于通过response对象输出指定格式的数据。
- @ResponseStatus
这个注解主要用在自定义的Exception 上,或者直接用在controller层的API方法上也可,当发生异常/方法执行结束时,会返回相应的Http状态码和msg。
代码语言:java复制@ResponseStatus(value=HttpStatus.FORBIDDEN,reason="不允许访问")
补充
代码语言:java复制 //1. 没有返回值: delete update
//@GetMapping("/demos")
public ResponseEntity<Void> demos() {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
//2 .查询有返回值 查询
//@GetMapping("/demoss")
public ResponseEntity<Admin> demoss() {
return new ResponseEntity<>(new Admin(), HttpStatus.OK);
}
//3 . 创建 nodejs vue
//@PutMapping("/create")
public ResponseEntity<Void> create() {
//return new ResponseEntity<Void>(HttpStatus.CREATED);
MultiValueMap<String, String> headers = new HttpHeaders();
headers.set("token", "xiaoli");
return new ResponseEntity<>(headers, HttpStatus.CREATED);
}
Get请求时
代码语言:java复制return ResponseEntity.ok();
@GetMapping({"findAll"})
public ResponseEntity<PageResult<User>> findAll(
@RequestParam(name = "admin", required = false) String admin,
@RequestParam(name = "page", defaultValue = "1") Integer page,
@RequestParam(name = "rows", defaultValue = "10") Integer rows
) {
PageResult<User> userPageResult = this.userService.findAll(admin, page, rows);
return ResponseEntity.ok(userPageResult);
}
Post请求新增一条记录时,有返回值
代码语言:java复制return ResponseEntity.status(HttpStatus.CREATE).body();
@PostMapping("save")
public ResponseEntity save(@RequestBody User user) throws Exception {
return ResponseEntity.status(HttpStatus.CREATED).body(this.userService.save(user));
}
Post请求新增一条记录时,无返回值
return new ResponseEntity(HttpStatus.CREATED);
Delete删除请求,无返回
代码语言:java复制return new ResponseEntity(HttpStatus.NO_CONTENT);
@DeleteMapping({"delete"})
public ResponseEntity delete(@RequestParam(name = "ids") Integer[] ids) {
return ResponseEntity.ok(this.userService.delete(ids));
}
Put更新请求,无返回值
代码语言:java复制ResponseEntity.noContent().build();
@PutMapping({"update"})
public ResponseEntity update(@RequestBody User user) throws Exception {
return ResponseEntity.ok(this.userService.update(user));
}
1、查询
代码语言:java复制@GetMapping("queryall")
public ResponseEntity<List<Announceconsultsituation>> queryAll(){
try {
List<Announceconsultsituation> announceconsultsituations = announceconsultsituationService.queryList(new Announceconsultsituation());
if(CollUtil.isEmpty(announceconsultsituations)){
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
}
return ResponseEntity.ok(announceconsultsituations);
}catch (Exception e){
e.printStackTrace();
}
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
@GetMapping("queryone")
public ResponseEntity<List<Announceconsultsituation>> queryone(){
try {
Announceconsultsituation announceconsultsituation = announceconsultsituationService.queryOne(id);
if(announceconsultsituation==null){
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
}
return ResponseEntity.ok(announceconsultsituation);
}catch (Exception e){
e.printStackTrace();
}
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
2、添加
代码语言:java复制@PostMapping("add")
public ResponseEntity<Void> add(Announceconsultsituation announceconsultsituation){
try {
int count = announceconsultsituationService.add(announceconsultsituation);
// 添加数据成功,返回201
if(count == 1){
return ResponseEntity.status(HttpStatus.CREATED).build();
}
}catch (Exception e){
e.printStackTrace();
}
// 执行失败或者发生异常,返回500
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
3、修改
代码语言:java复制@PutMapping("update")
public ResponseEntity<Void> update(Announceconsultsituation announceconsultsituation){
try {
int count = announceconsultsituationService.update(announceconsultsituation);
// 正常更新数据,返回204
if(count == 1){
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
}
}catch (Exception e){
e.printStackTrace();
}
// 执行失败或者发生异常,返回500
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
4、删除
代码语言:java复制@DeleteMapping("del/{id}")
public ResponseEntity<Void> delete(@PathVariable("id") Integer id){
try {
//参数没有或者格式错误,返回400
if(id == null){
return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
}
int count = announceconsultsituationService.delete(id);
// 正常删除,返回204
if(count == 1){
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
}
}catch (Exception e){
e.printStackTrace();
}
// 执行失败或者发生异常,返回500
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
自定义ResponeBean进行CRUD
代码语言:java复制public class RespBean {
private Integer status;
private String msg;
private Object obj;
public static RespBean build() {
return new RespBean();
}
public static RespBean ok(String msg) {
return new RespBean(200, msg, null);
}
public static RespBean ok(String msg, Object obj) {
return new RespBean(200, msg, obj);
}
public static RespBean error(String msg) {
return new RespBean(500, msg, null);
}
public static RespBean error(String msg, Object obj) {
return new RespBean(500, msg, obj);
}
private RespBean() {
}
private RespBean(Integer status, String msg, Object obj) {
this.status = status;
this.msg = msg;
this.obj = obj;
}
public Integer getStatus() {
return status;
}
public RespBean setStatus(Integer status) {
this.status = status;
return this;
}
public String getMsg() {
return msg;
}
public RespBean setMsg(String msg) {
this.msg = msg;
return this;
}
public Object getObj() {
return obj;
}
public RespBean setObj(Object obj) {
this.obj = obj;
return this;
}
}
1、查询
代码语言:java复制@GetMapping("/")
public List<JobLevel> getAllJobLevels() {
return jobLevelService.getAllJobLevels();
}
2、增加
代码语言:java复制@PostMapping("/")
public RespBean addJobLevel(@RequestBody JobLevel jobLevel) {
if (jobLevelService.addJobLevel(jobLevel) == 1) {
return RespBean.ok("添加成功!");
}
return RespBean.error("添加失败!");
}
3、更新
代码语言:java复制@PutMapping("/")
public RespBean updateJobLevelById(@RequestBody JobLevel jobLevel) {
if (jobLevelService.updateJobLevelById(jobLevel) == 1) {
return RespBean.ok("更新成功!");
}
return RespBean.error("更新失败!");
}
4、删除
代码语言:java复制@DeleteMapping("/{id}")
public RespBean deleteJobLevelById(@PathVariable Integer id) {
if (jobLevelService.deleteJobLevelById(id) == 1) {
return RespBean.ok("删除成功!");
}
return RespBean.error("删除失败!");
}