用戶詳情請求
使用@PathVariable注解去綁定url中的參數(shù)
@RequestMapping(value="user/{id}",method = RequestMethod.GET)
public User getInfo(@PathVariable(required = false) String id) {
User user=new User();
user.setUsername("tom");
return user;
}
測試用例
@Test
public void whenGenInfoSuccess() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/user/1")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.username").value("tom"));
}
需求:傳來的必須是數(shù)字
@RequestMapping(value="user/{id:\\d+}",method = RequestMethod.GET)
public User getInfo(@PathVariable(required = false) String id) {
User user=new User();
user.setUsername("tom");
return user;
}
@Test
public void whenGenInfoFail() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/user/a")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().is4xxClientError());
}
需求:query接口不能將password字段返回給前端隐解,getInfo接口要將password字段返回給前端
解析:使用@JsonView
@Data
public class User {
@JsonView(UserSimpleView.class)
private String username;
@JsonView(UserDetailView.class)
private String password;
public interface UserSimpleView{};
public interface UserDetailView extends UserSimpleView{};
}
@RestController
public class UserController {
@RequestMapping(value = "/user",method = RequestMethod.GET)
@JsonView(User.UserSimpleView.class)
public List<User> query(@RequestParam(required = false) String username,@PageableDefault(page = 1,size = 10,sort = "username,asc") Pageable pageable){
System.out.println(pageable.getPageSize()+"---"+pageable.getPageNumber()+"---"+pageable.getSort());
List<User> users=new ArrayList<User>(3);
users.add(new User());
users.add(new User());
users.add(new User());
return users;
}
@JsonView(User.UserDetailView.class)
@RequestMapping(value="user/{id:\\d+}",method = RequestMethod.GET)
public User getInfo(@PathVariable(required = false) String id) {
User user=new User();
user.setUsername("tom");
return user;
}
}
用戶創(chuàng)建請求
@PostMapping
public User createUser(User user) {
System.out.println("user==>"+user);
user.setId("1");
return user;
}
@Test
public void whenCreateSuccess() throws Exception {
String content = "{\"username\":\"tom\",\"password\":null}";
String res = mockMvc
.perform(MockMvcRequestBuilders.post("/user").contentType(MediaType.APPLICATION_JSON_UTF8)
.content(content))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1)).andReturn().getResponse()
.getContentAsString();
System.out.println(res);
}
發(fā)現(xiàn)controller類的參數(shù)User內(nèi)并沒有傳過來的值稿黍。
需要加一個@RequestBody
@PostMapping
public User createUser(@RequestBody User user) {
System.out.println("user==>"+user);
user.setId("1");
return user;
}
之前并沒有接觸過@RequestBody注解霸妹,網(wǎng)上查詢了一下該注解的作用https://blog.csdn.net/justry_deng/article/details/80972817
簡單的說就是:參數(shù)放在請求體中,必須用@RequestBody注解接收。
需求:處理日期類型的參數(shù)
(視頻上所說,由于現(xiàn)在前后端分離的情況阁吝,可能后臺一個接口會被不同的渠道調(diào)用棠耕,app余佛,網(wǎng)頁端。這些渠道可能顯示的格式不同窍荧,所以一般而言后端傳給前端會是時間戳格式,然后再由前端選擇顯示的格式恨憎。但我們現(xiàn)在并不是= =蕊退,而是傳格式化好了的時間,可以用@DateTimeFormat 和 @JsonFormat 注解憔恳,@DateTimeFormat 在RequestBody中不生效)
需求:校驗參數(shù)的合法性瓤荔,并處理校驗的結(jié)果
解析:使用@vaild注解和BindingResult注解
@Data
@ToString
public class User {
@JsonView(UserSimpleView.class)
private String id;
@JsonView(UserSimpleView.class)
private String username;
@NotBlank(message = "密碼不能為空")
@JsonView(UserDetailView.class)
private String password;
private Date birthDate;
public interface UserSimpleView {
};
public interface UserDetailView extends UserSimpleView {
};
}
@PostMapping
public User createUser(@Valid @RequestBody User user,BindingResult errors) {
if(errors.hasErrors()) {
errors.getAllErrors().stream().forEach(error-> System.out.println(error.getDefaultMessage()));
}
System.out.println("user==>"+user);
user.setId("1");
return user;
}
(這里我使用的參數(shù)校驗和視頻上的略有出入,看我的實現(xiàn)可以看常用功能文章系列的參數(shù)校驗?zāi)且黄孔椤#?/p>
用戶修改請求
@Data
@ToString
public class User {
@JsonView(UserSimpleView.class)
private String id;
@JsonView(UserSimpleView.class)
private String username;
@NotBlank(message = "密碼不能為空")
@JsonView(UserDetailView.class)
private String password;
@Past(message = "生日必須是過去的時間")
private Date birthDate;
public interface UserSimpleView {
};
public interface UserDetailView extends UserSimpleView {
};
}
@PutMapping(value="/{id:\\d+}")
public User updateUser(@Valid @RequestBody User user,BindingResult errors) {
if(errors.hasErrors()) {
errors.getAllErrors().stream().forEach(error-> System.out.println(error.getDefaultMessage()));
}
System.out.println("user==>"+user);
user.setId("1");
return user;
}
@Test
public void whenUpdateSuccess() throws Exception {
Date date=new Date(LocalDateTime.now().plusYears(1).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
String content = "{\"id\":\"1\",\"username\":\"tom\",\"password\":null,\"birthDate\":"+date.getTime()+"}";
String res = mockMvc
.perform(MockMvcRequestBuilders.put("/user/1").contentType(MediaType.APPLICATION_JSON_UTF8)
.content(content))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1)).andReturn().getResponse()
.getContentAsString();
System.out.println(res);
}
需求:自定義校驗注解
public class MyConstraintValidator implements ConstraintValidator<MyConstraint, Object> {
@Override
public void initialize(MyConstraint constraintAnnotation) {
System.out.println("MyConstraintValidator init");
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
System.out.println("value==》"+value);
// TODO 寫具體的校驗邏輯输硝,true驗證通過,false驗證不過
return false;
}
}
@Target({ElementType.METHOD,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MyConstraintValidator.class)
public @interface MyConstraint {
String message() default "";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
@MyConstraint(message = "自定義校驗不過")
@JsonView(UserSimpleView.class)
private String username;
服務(wù)器異常處理
spring boot的默認(rèn)異常處理機(jī)制是程梦,瀏覽器返回錯誤頁面点把,客戶端返回json數(shù)據(jù)。
1屿附、在src/main/resources下建立resources文件夾郎逃,然后再建error文件夾,再建立相應(yīng)的錯誤頁面挺份。如404.hmtl褒翰,500.html
多線程提高接口性能
使用swagger生成文檔
1、引入pom依賴
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
2匀泊、使用@EnableSwagger2開啟swagger
@SpringBootApplication
@EnableSwagger2
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
3优训、使用注解
@Api注解:說明這個controller是干什么的
@Api("用戶服務(wù)")
public class UserController
@ApiOperation:說明這個方法是干什么的
@ApiOperation(value = "用戶創(chuàng)建服務(wù)")
@PostMapping
public User createUser(@Valid @RequestBody User user,BindingResult errors)
@ApiModelProperty :參數(shù)是對象時,說明對象的屬性
@ApiModelProperty("用戶名")
@JsonView(UserSimpleView.class)
private String username;
@ApiModelProperty("用戶密碼")
@NotBlank(message = "密碼不能為空")
@JsonView(UserDetailView.class)
private String password;
@ApiModelProperty("用戶生日")
@Past(message = "生日必須是過去的時間")
private Date birthDate;
@ApiParam:參數(shù)是單獨的一個時各聘,說明揣非。
public List<User> query(@ApiParam("用戶名")@RequestParam(required = false) String username,@PageableDefault(page = 1,size = 10,sort = "username,asc") Pageable pageable){
參考鏈接:http://www.reibang.com/p/a66cf3acd29a