SpringMVC开发RESTful API
2019-01-29 本文已影响0人
Burning_6c93
RESTful API
- 用URL描述资源
- 用http方法描述行为,使用http状态码来表示不同的结果。
- 使用json来交互数据
- RESTful只是一种风格,并不是强制的标准。
REST成熟模型
- Level 0:The Swamp of POX
- 使用http作为传输方式
- Level 1:Resources
- 引入资源概念。每个资源都有对应的URL
- Level 2:HTTP Verbs
- 使用http方法进行不同的操作。使用http状态码表示不同的结果
- Level 3:Hypermedia Controls
- 使用超媒体。在资源的表达中包含了链接信息。
常用注解
- @RestController
- 标明此Controller提供RestAPI
- @RequestMapping及其变体
- 映射http请求url到java方法
- @RequestParam
- 映射请求参数到java方法的参数
@GetMapping("/user/login")
public ResultDto<Object> login(@RequestParam String username,@RequestParam String password){
......
return ResultDto.success();
}
- @PageabelDefault
- 指定分页参数默认值(size,page,sort)
@RequestMapping(value = "/user", method = RequestMethod.GET) public List<User> query(UserQueryCondition condition, @PageableDefault(page = 0,size = 15,sort = "age,asc") Pageable pageable) { log.info(ReflectionToStringBuilder.toString(condition, ToStringStyle.MULTI_LINE_STYLE)); log.info(ReflectionToStringBuilder.toString(pageable, ToStringStyle.MULTI_LINE_STYLE)); ArrayList<User> list = Lists.newArrayList(); list.add(new User()); list.add(new User()); list.add(new User()); return list; }
- @PathVariable
- 映射url片段到java方法的参数
- 在url声明中使用正则表达式,剔除不规范请求
@GetMapping(value = "/user/{id:\\d+}")
public User getInfo(@PathVariable("id") String id){
User user = new User();
user.setUsername("dzg");
return user;
}
- @JsonView控制json输出内容
- @JsonView使用步骤
- 使用接口来声明多个视图
@Data public class User { public interface UserSimpleView {}; public interface UserDetailView extends UserSimpleView {}; @JsonView(UserSimpleView.class) private String username; @JsonView(UserDetailView.class) private String password; }
- 在值对象的get方法上指定视图
- 在Controller方法上指定视图
@GetMapping(value = "/user") @JsonView(User.UserSimpleView.class) public List<User> query(UserQueryCondition condition, @PageableDefault(page = 0,size = 15,sort = "age,asc") Pageable pageable) { ...... return list; } @GetMapping(value = "/user/{id:\\d+}") @JsonView(User.UserDetailView.class) public User getInfo(@PathVariable("id") String id){ User user = new User(); user.setUsername("dzg"); return user; }
- @JsonView使用步骤
处理创建请求
- @RequestBody映射请求体到java方法的参数
- @requestBody注解常用来处理content-type不是默认的application/x-www-form-urlcoded编码的内容,比如:application/json或application/xml等。一般情况下来说常用其来处理application/json类型。
- 通过@requestBody可以将请求体中的JSON字符串绑定到相应的bean上,当然,也可以将其分别绑定到对应的字符串上。
@Test public void whenCreateSuccess(){ try { String content = "{\"username\":\"dzg\",\"password\":\"123\"}"; mockMvc.perform(MockMvcRequestBuilders.post("/user").contentType(MediaType.APPLICATION_JSON_UTF8) .content(content)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.id").value("1")); } catch (Exception e) { e.printStackTrace(); } } @PostMapping public User create(@RequestBody User user){ log.info(ReflectionToStringBuilder.toString(user, ToStringStyle.MULTI_LINE_STYLE)); user.setId(1); return user; }
- 3、在一些特殊情况,@requestBody也可以用来处理content-type类型为application/x-www-form-urlcoded的内容,只不过这种方式不是很常用,在处理这类请求的时候,@requestBody会将处理结果放到一个MultiValueMap<String,String>中,这种情况一般在特殊情况下才会使用。
- 日期类型参数的处理
- @Valid注解和BindResult验证请求参数的合法性并处理校验结果
@NotBlank private String password; @PostMapping public User create(@Valid @RequestBody User user, BindingResult errors) { if (errors.hasErrors()) { errors.getAllErrors().stream().forEach(error -> log.info(error.getDefaultMessage())); } log.info(ReflectionToStringBuilder.toString(user, ToStringStyle.MULTI_LINE_STYLE)); user.setId(1); return user; }
常用的注解校验

