ResponseEntity

ResponseEntity

ResponseEntity实现Rest风格的返回值

ResponseEntity
它是Spring提供的一个类,它内部封装了状态码,请求头,请求体等信息,用户可以根据自己的需要修改状态码、请求体的信息。ResponseEntity中的泛型用于指定请求体的类型,它的请求体和@ResponseBody的作用完全一致,并且ResponseEntity的优先级要高于@ResponseBody,即:如果返回值是ResponseEntity,即使存在ResponseBody或者@RestController注解,也默认不会生效,而是使用ResponseEntity。

HttpStatus
这是Spring提供的一个枚举类,其遵循RESTful风格封装了大量了响应状态码。详见org.springframework.http.HttpStatus;

如何使用ResponseEntity

使用构造返回,其中第一个参数为响应体,第二个为响应码


//使用构造参数构建
new ResponseEntity<String>("return info",HttpStatus.BAD_REQUEST);
//使用构造参数构建
new ResponseEntity<JavaBean>(javaBean,HttpStatus.BAD_REQUEST);
使用status设置响应码,body指定响应头

//使用status方法和body方法
ResponseEntity.status(HttpStatus.CREATED).body(javaBean);
//使用status方法和body方法
ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
//另外还可以设置响应头:

@GetMapping("/customHeader")
ResponseEntity<String> customHeader() {
    HttpHeaders headers = new HttpHeaders();
    headers.add("Custom-Header", "foo");

    return new ResponseEntity<>(
      "Custom header set", headers, HttpStatus.OK);
}

如果只是返回一个状态码为200的内容,可以简写为:

@GetMapping("/hello")
ResponseEntity<String> hello() {
    return ResponseEntity.ok("Hello World!");
}

简单的两种用法,分别是500和200、400、404

ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
ResponseEntity.ok(list);
ResponseEntity.badRequest().build();
ResponseEntity.notFound().build();
posted @ 2020-08-24 05:31  silence022  阅读(274)  评论(0)    收藏  举报