前后端传值的注解
@PathVariable和@RequestParam
@PathVariable用于获取路径参数,@RequestParam用于获取查询参数。
@GetMapping("/klasses/{klassId}/teachers")
public List<Teacher> getKlassRelatedTeachers(@PathVariable("klassId") Long klassId,@RequestParam(value = "type", required = false) String type ) {
...
}
如果我们请求的 url 是:/klasses/{123456}/teachers?type=web
那么我们服务获取到的数据就是:klassId=123456,type=web。
@RequstBody
用于读取 Request 请求(可能是 POST,PUT,DELETE,GET 请求)的 body 部分并且Content-Type 为 application/json 格式的数据,接收到数据之后会自动将数据绑定到 Java 对象上去。系统会使用HttpMessageConverter或者自定义的HttpMessageConverter将请求的 body 中的 json 字符串转换为 java 对象。
我用一个简单的例子来给演示一下基本使用!
我们有一个注册的接口:
@PostMapping("/sign-up")
public ResponseEntity signUp(@RequestBody @Valid UserRegisterRequest userRegisterRequest) {userService.save(userRegisterRequest);return ResponseEntity.ok().build();
}
@Autowired 依赖注入
> @Service
public class UserService {......
}@RestController
@RequestMapping("/users")
public class UserController {@Autowiredprivate UserService userService;......
}
读取配置信息的
@value()
使用 @Value(“${property}”) 读取比较简单的配置信息:
@Value("${wuhan2020}")
String wuhan2020;
@ConfigurationProperties(常用)
通过@ConfigurationProperties读取配置信息并与 bean 绑定。
@Component
@ConfigurationProperties(prefix = "library")
class LibraryProperties {@NotEmptyprivate String location;private List<Book> books;@Setter@Getter@ToStringstatic class Book {String name;String description;}省略getter/setter......
}
@RestController
@RestController注解是@Controller和@ResponseBody的合集,表示这是个控制器 bean,并且是将函数的返回值直 接填入 HTTP 响应体中,是 REST 风格的控制器。
5 种常见的请求类型:
GET :请求从服务器获取特定资源。举个例子:GET /users(获取所有学生)
POST :在服务器上创建一个新的资源。举个例子:POST /users(创建学生)
PUT :更新服务器上的资源(客户端提供更新后的整个资源)。举个例子:PUT /users/12(更新编号为 12 的学生)
DELETE :从服务器删除特定的资源。举个例子:DELETE /users/12(删除编号为 12 的学生)
PATCH :更新服务器上的资源(客户端提供更改的属性,可以看做作是部分更新),使用的比较少,这里就不举例子了