1 注解
@RestController
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
2 统一返回json格式的返回值
使用ResponseEntity就可以返回统一格式的返回值。
可以通过ResponseEntity返回响应的状态、响应体和响应头。
2.1 返回响应状态
第一种方法,在构造函数种指定,
public ResponseEntity(HttpStatus status)
public ResponseEntity(T body, MultiValueMap<String, String> headers, HttpStatus status)
public ResponseEntity(T body, HttpStatus status)
public ResponseEntity(MultiValueMap<String, String> headers, HttpStatus status)
第二种方法,通过status静态方法指定
public static ResponseEntity.BodyBuilder status(HttpStatus status)
第三种方法,通过具体的静态方法指定
public static ResponseEntity.BodyBuilder ok()
public static ResponseEntity.BodyBuilder accepted()
2.2 返回响应体
第一种方法,在构造函数中指定
public ResponseEntity(T body, MultiValueMap<String, String> headers, HttpStatus status)
public ResponseEntity(T body, HttpStatus status)
第二种方法,在静态函数中指定
public static <T> ResponseEntity<T> ok(T body)
ResponseEntity.ok() .header("Custom-Header", "foo") .body("Custom header set");
ResponseEntity.status(HttpStatus.OK) .body("Your age is " + calculateAge(yearOfBirth));
2.3 返回响应头
第一种方法,在构造函数中指定
public ResponseEntity(T body, MultiValueMap<String, String> headers, HttpStatus status)
public ResponseEntity(MultiValueMap<String, String> headers, HttpStatus status)
第二种方法,通过静态函数指定
ResponseEntity.ok() .header("Custom-Header", "foo") .body("Custom header set");
ResponseEntity.status(HttpStatus.OK).header("Custom-Header", "foo");
3 接口认证
使用OAuth即可。
4 HttpStatus
这是一个enum类型,所有的http状态都有,比如200、404等等。
5 设置该服务的主路径
在application.properties文件中,用
server.servlet.context-path=/home
来设置,这样,所有controller的路径都在该路径的下来了。
6 关于get参数
7 关于post参数
参考资料: