基于springboot創(chuàng)建RESTful風(fēng)格接口
RESTful API風(fēng)格
特點(diǎn):
- URL描述資源
- 使用HTTP方法描述行為涝动。使用HTTP狀態(tài)碼來表示不同的結(jié)果
- 使用json交互數(shù)據(jù)
- RESTful只是一種風(fēng)格飒炎,并不是強(qiáng)制的標(biāo)準(zhǔn)
一、查詢請(qǐng)求
1.編寫單元測(cè)試
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
//查詢
@Test
public void whenQuerySuccess() throws Exception {
String result = mockMvc.perform(get("/user")
.param("username", "jojo")
.param("age", "18")
.param("ageTo", "60")
.param("xxx", "yyy")
// .param("size", "15")
// .param("sort", "age,desc")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk())
.andExpect(jsonPath("$.length()").value(3))
.andReturn().getResponse().getContentAsString();//將服務(wù)器返回的json字符串當(dāng)成變量返回
System.out.println(result);//[{"username":null},{"username":null},{"username":null}]
}
}
2.使用注解聲明RestfulAPI
常用注解
@RestController 標(biāo)明此Controller提供RestAPI
@RequestMapping及其變體。映射http請(qǐng)求url到j(luò)ava方法
@RequestParam 映射請(qǐng)求參數(shù)到j(luò)ava方法的參數(shù)
@PageableDefault 指定分頁參數(shù)默認(rèn)值
@PathVariable 映射url片段到j(luò)ava方法的參數(shù)
在url聲明中使用正則表達(dá)式
@JsonView控制json輸出內(nèi)容
查詢請(qǐng)求:
@RestController
public class UserController {
@RequestMapping(value="/user",method=RequestMethod.GET)
public List<User> query(@RequestParam(name="username",required=false,defaultValue="tom") String username){
System.out.println(username);
List<User> users = new ArrayList<>();
users.add(new User());
users.add(new User());
users.add(new User());
return users;
}
}
①當(dāng)前端傳遞的參數(shù)和后臺(tái)自己定義的參數(shù)不一致時(shí)牵舵,可以使用name屬性來標(biāo)記:
(@RequestParam(name="username",required=false,defaultValue="hcx") String nickname
②前端不傳參數(shù)時(shí),使用默認(rèn)值 defaultValue="hcx"
③當(dāng)查詢參數(shù)很多時(shí),可以使用對(duì)象接收
④使用Pageable作為參數(shù)接收菱属,前臺(tái)可以傳遞分頁相關(guān)參數(shù)
pageSize,pageNumber舰罚,sort纽门;
也可以使用@PageableDefault指定默認(rèn)的參數(shù)值。
@PageableDefault(page=2,size=17,sort="username,asc")
//查詢第二頁营罢,查詢17條赏陵,按照用戶名升序排列
3.jsonPath表達(dá)式書寫
github鏈接:https://github.com/json-path/JsonPath
二、編寫用戶詳情服務(wù)
@PathVariable 映射url片段到j(luò)ava方法的參數(shù)
在url聲明中使用正則表達(dá)式
@JsonView控制json輸出內(nèi)容
單元測(cè)試:
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
//獲取用戶詳情
@Test
public void whenGetInfoSuccess() throws Exception {
String result = mockMvc.perform(get("/user/1")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk())
.andExpect(jsonPath("$.username").value("tom"))
.andReturn().getResponse().getContentAsString();
System.out.println(result); //{"username":"tom","password":null}
}
后臺(tái)代碼:
@RestController
@RequestMapping("/user")//在類上聲明了/user饲漾,在方法中就可以省略了
public class UserController {
@RequestMapping(value="/user/{id}",method=RequestMethod.GET)
public User getInfo(@PathVariable String id) {
User user = new User();
user.setUsername("tom");
return user;
}
當(dāng)希望對(duì)傳遞進(jìn)來的參數(shù)作一些限制時(shí)蝙搔,可以使用正則表達(dá)式:
//測(cè)試提交錯(cuò)誤信息
@Test
public void whenGetInfoFail() throws Exception {
mockMvc.perform(get("/user/a")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().is4xxClientError());
}
后臺(tái)代碼:
@RequestMapping(value="/user/{id:\\d+}",method=RequestMethod.GET)//如果希望對(duì)傳遞進(jìn)來的參數(shù)作一些限制,使用正則表達(dá)式
@JsonView(User.UserDetailView.class)
public User getInfo(@PathVariable String id) {
User user = new User();
user.setUsername("tom");
return user;
}
使用@JsonView控制json輸出內(nèi)容
1.場(chǎng)景:在以上兩個(gè)方法中考传,查詢集合和查詢用戶詳細(xì)信息時(shí)吃型,期望查詢用戶集合時(shí)不返回密碼給前端,而在查詢單個(gè)用戶信息時(shí)才返回伙菊。
2.使用步驟:
①使用接口來聲明多個(gè)視圖
②在值對(duì)象的get方法上指定視圖
③在Controller方法上指定視圖
在user實(shí)體中操作:
package com.hcx.web.dto;
import java.util.Date;
import javax.validation.constraints.Past;
import org.hibernate.validator.constraints.NotBlank;
import com.fasterxml.jackson.annotation.JsonView;
import com.hcx.validator.MyConstraint;
public class User {
public interface UserSimpleView{};
//有了該繼承關(guān)系败玉,在顯示detail視圖的時(shí)候同時(shí)會(huì)把simple視圖的所有字段也顯示出來
public interface UserDetailView extends UserSimpleView{};
@MyConstraint(message="這是一個(gè)測(cè)試")
private String username;
@NotBlank(message = "密碼不能為空")
private String password;
private String id;
@Past(message="生日必須是過去的時(shí)間")
private Date birthday;
@JsonView(UserSimpleView.class)
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@JsonView(UserSimpleView.class)
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@JsonView(UserSimpleView.class) //在簡(jiǎn)單視圖上展示該字段
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@JsonView(UserDetailView.class)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
在具體的方法中操作Controller:
@GetMapping
@JsonView(User.UserSimpleView.class)
public List<User> query(@RequestParam(name="username",required=false,defaultValue="tom") String username){
System.out.println(username);
List<User> users = new ArrayList<>();
users.add(new User());
users.add(new User());
users.add(new User());
return users;
}
@RequestMapping(value="/user/{id:\\d+}",method=RequestMethod.GET)//如果希望對(duì)傳遞進(jìn)來的參數(shù)作一些限制,就需要使用正則表達(dá)式
@JsonView(User.UserDetailView.class)
public User getInfo(@PathVariable String id) {
User user = new User();
user.setUsername("tom");
return user;
}
單元測(cè)試:
//查詢
@Test
public void whenQuerySuccess() throws Exception {
String result = mockMvc.perform(get("/user")
.param("username", "jojo")
.param("age", "18")
.param("ageTo", "60")
.param("xxx", "yyy")
//.param("size", "15")
//.param("sort", "age,desc")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk())
.andExpect(jsonPath("$.length()").value(3))
.andReturn().getResponse().getContentAsString();//將服務(wù)器返回的json字符串當(dāng)成變量返回
System.out.println(result);//[{"username":null},{"username":null},{"username":null}]
}
//獲取用戶詳情
@Test
public void whenGetInfoSuccess() throws Exception {
String result = mockMvc.perform(get("/user/1")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk())
.andExpect(jsonPath("$.username").value("tom"))
.andReturn().getResponse().getContentAsString();
System.out.println(result); //{"username":"tom","password":null}
}
代碼重構(gòu):
1.@RequestMapping(value="/user",method=RequestMethod.GET)
替換成:
@GetMapping("/user")
2.在每個(gè)url中都重復(fù)聲明了/user镜硕,此時(shí)就可以提到類中聲明
@RestController
@RequestMapping("/user")//在類上聲明了/user运翼,在方法中就可以省略了
public class UserController {
@GetMapping
@JsonView(User.UserSimpleView.class)
public List<User> query(@RequestParam(name="username",required=false,defaultValue="tom") String username){
System.out.println(username);
List<User> users = new ArrayList<>();
users.add(new User());
users.add(new User());
users.add(new User());
return users;
}
@GetMapping("/{id:\\d+}")
@JsonView(User.UserDetailView.class)
public User getInfo(@PathVariable String id) {
User user = new User();
user.setUsername("tom");
return user;
}
}
三、處理創(chuàng)建請(qǐng)求
1.@RequestBody 映射請(qǐng)求體到j(luò)ava方法的參數(shù)
單元測(cè)試:
@Test
public void whenCreateSuccess() throws Exception {
Date date = new Date();
System.out.println(date.getTime());//1524741370816
String content = "{\"username\":\"tom\",\"password\":null,\"birthday\":"+date.getTime()+"}";
String result = mockMvc.perform(post("/user").contentType(MediaType.APPLICATION_JSON_UTF8)
.content(content))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value("1"))
.andReturn().getResponse().getContentAsString();
System.out.println(result);//{"username":"tom","password":null,"id":"1","birthday":1524741229875}
}
Controller:要使用@RequestBody才可以接收前端傳遞過來的參數(shù)
@PostMapping
public User create(@RequestBody User user) {
System.out.println(user.getId()); //null
System.out.println(user.getUsername()); //tom
System.out.println(user.getPassword());//null
user.setId("1");
return user;
}
2.日期類型參數(shù)的處理
對(duì)于日期的處理應(yīng)該交給前端或app端兴枯,所以統(tǒng)一使用時(shí)間戳
前端或app端拿到時(shí)間戳血淌,由他們自己決定轉(zhuǎn)換成什么格式,而不是由后端轉(zhuǎn)好直接給前端。
前端傳遞給后臺(tái)直接傳時(shí)間戳:
@Test
public void whenCreateSuccess() throws Exception {
Date date = new Date();
System.out.println(date.getTime());//1524741370816
String content = "{\"username\":\"tom\",\"password\":null,\"birthday\":"+date.getTime()+"}";
String result = mockMvc.perform(post("/user").contentType(MediaType.APPLICATION_JSON_UTF8)
.content(content))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value("1"))
.andReturn().getResponse().getContentAsString();
System.out.println(result);//{"username":"tom","password":null,"id":"1","birthday":1524741229875}(后臺(tái)返回的時(shí)間戳)
}
Controller:
@PostMapping
public User create(@RequestBody User user) {
System.out.println(user.getId()); //null
System.out.println(user.getUsername()); //tom
System.out.println(user.getPassword());//null
System.out.println(user.getBirthday());//Thu Apr 26 19:13:49 CST 2018(Date類型)
user.setId("1");
return user;
}
3.@Valid注解和BindingResult驗(yàn)證請(qǐng)求參數(shù)的合法性并處理校驗(yàn)結(jié)果
1.hibernate.validator中的常用驗(yàn)證注解:
①在實(shí)體中添加相應(yīng)驗(yàn)證注解:
@NotBlank
private String password;
②后臺(tái)接收參數(shù)時(shí)加@Valid注解
@PostMapping
public User create(@Valid @RequestBody User user) {
System.out.println(user.getId()); //null
System.out.println(user.getUsername()); //tom
System.out.println(user.getPassword());//null
System.out.println(user.getBirthday());//Thu Apr 26 19:13:49 CST 2018
user.setId("1");
return user;
}
2.BindingResult:帶著錯(cuò)誤信息進(jìn)入方法體
@PostMapping
public User create(@Valid @RequestBody User user,BindingResult errors) {
if(errors.hasErrors()) {
//有錯(cuò)誤返回true
errors.getAllErrors().stream().forEach(error -> System.out.println(error.getDefaultMessage()));
//may not be empty
}
System.out.println(user.getId()); //null
System.out.println(user.getUsername()); //tom
System.out.println(user.getPassword());//null
System.out.println(user.getBirthday());//Thu Apr 26 19:13:49 CST 2018
user.setId("1");
return user;
}
四悠夯、處理用戶信息修改
1.自定義消息
@Test
public void whenUpdateSuccess() throws Exception {
//一年之后的時(shí)間
Date date = new Date(LocalDateTime.now().plusYears(1).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
System.out.println(date.getTime());//1524741370816
String content = "{\"id\":\"1\",\"username\":\"tom\",\"password\":null,\"birthday\":"+date.getTime()+"}";
String result = mockMvc.perform(put("/user/1").contentType(MediaType.APPLICATION_JSON_UTF8)
.content(content))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value("1"))
.andReturn().getResponse().getContentAsString();
System.out.println(result);//{"username":"tom","password":null,"id":"1","birthday":1524741229875}
}
Controller:
@PutMapping("/{id:\\d+}")
public User update(@Valid @RequestBody User user,BindingResult errors) {
/*if(errors.hasErrors()) {
//有錯(cuò)誤返回true
errors.getAllErrors().stream().forEach(error -> System.out.println(error.getDefaultMessage()));
//may not be empty
}*/
if(errors.hasErrors()) {
errors.getAllErrors().stream().forEach(error -> {
//FieldError fieldError = (FieldError)error;
//String message = fieldError.getField()+" "+error.getDefaultMessage();
System.out.println(error.getDefaultMessage());
//密碼不能為空
//生日必須是過去的時(shí)間
//birthday must be in the past
//password may not be empty
}
);
}
System.out.println(user.getId()); //null
System.out.println(user.getUsername()); //tom
System.out.println(user.getPassword());//null
System.out.println(user.getBirthday());//Thu Apr 26 19:13:49 CST 2018
user.setId("1");
return user;
}
實(shí)體:
public class User {
public interface UserSimpleView{};
//有了該繼承關(guān)系癌淮,在顯示detail視圖的時(shí)候同時(shí)會(huì)把simple視圖的所有字段也顯示出來
public interface UserDetailView extends UserSimpleView{};
@MyConstraint(message="這是一個(gè)測(cè)試")
private String username;
@NotBlank(message = "密碼不能為空")
private String password;
private String id;
@Past(message="生日必須是過去的時(shí)間")
private Date birthday;
@JsonView(UserSimpleView.class)
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@JsonView(UserSimpleView.class)
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@JsonView(UserSimpleView.class) //在簡(jiǎn)單視圖上展示該字段
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@JsonView(UserDetailView.class)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
2.自定義校驗(yàn)注解
創(chuàng)建一個(gè)注解MyConstraint:
@Target({ElementType.METHOD,ElementType.FIELD})//可以標(biāo)注在方法和字段上
@Retention(RetentionPolicy.RUNTIME)//運(yùn)行時(shí)注解
@Constraint(validatedBy = MyConstraintValidator.class)//validatedBy :當(dāng)前的注解需要使用什么類去校驗(yàn),即校驗(yàn)邏輯
public @interface MyConstraint {
String message();//校驗(yàn)不通過要發(fā)送的信息
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
校驗(yàn)類:MyConstraintValidator:
public class MyConstraintValidator implements ConstraintValidator<MyConstraint, Object> {
/*ConstraintValidator<A, T>
參數(shù)一:驗(yàn)證的注解
參數(shù)二:驗(yàn)證的類型
ConstraintValidator<MyConstraint, String> 當(dāng)前注解只能放在String類型字段上才會(huì)起作用
*/
@Autowired
private HelloService helloService;
@Override
public void initialize(MyConstraint constraintAnnotation) {
System.out.println("my validator init");
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
helloService.greeting("tom");
System.out.println(value);
return false;//false:校驗(yàn)失斅俨埂乳蓄;true:校驗(yàn)成功
}
}
五、處理刪除
單元測(cè)試:
@Test
public void whenDeleteSuccess() throws Exception {
mockMvc.perform(delete("/user/1")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
}
Controller:
@DeleteMapping("/{id:\\d+}")
public void delete(@PathVariable String id) {
System.out.println(id);
}
六夕膀、RESTful API錯(cuò)誤處理
1.Spring Boot中默認(rèn)的錯(cuò)誤處理機(jī)制
Spring Boot中默認(rèn)的錯(cuò)誤處理機(jī)制虚倒,
對(duì)于瀏覽器是響應(yīng)一個(gè)html錯(cuò)誤頁面,
對(duì)于app是返回錯(cuò)誤狀態(tài)碼和一段json字符串
2.自定義異常處理
①針對(duì)瀏覽器發(fā)出的請(qǐng)求
在src/mian/resources文件夾下創(chuàng)建文件夾error編寫錯(cuò)誤頁面
對(duì)應(yīng)的錯(cuò)誤狀態(tài)碼就會(huì)去到對(duì)應(yīng)的頁面
只會(huì)對(duì)瀏覽器發(fā)出的請(qǐng)求有作用产舞,對(duì)app發(fā)出的請(qǐng)求魂奥,錯(cuò)誤返回仍然是錯(cuò)誤碼和json字符串
②針對(duì)客戶端app發(fā)出的請(qǐng)求
自定義異常:
package com.hcx.exception;
public class UserNotExistException extends RuntimeException{
private static final long serialVersionUID = -6112780192479692859L;
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public UserNotExistException(String id) {
super("user not exist");
this.id = id;
}
}
在Controller中拋?zhàn)约憾x的異常
//發(fā)生異常時(shí),拋?zhàn)约鹤远x的異常
@GetMapping("/{id:\\d+}")
@JsonView(User.UserDetailView.class)
public User getInfo1(@PathVariable String id) {
throw new UserNotExistException(id);
}
默認(rèn)情況下易猫,springboot不讀取id的信息
拋出異常時(shí)耻煤,進(jìn)入該方法進(jìn)行處理:
ControllerExceptionHandler:
@ControllerAdvice //只負(fù)責(zé)處理異常
public class ControllerExceptionHandler {
@ExceptionHandler(UserNotExistException.class)
@ResponseBody
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Map<String, Object> handleUserNotExistException(UserNotExistException ex){
Map<String, Object> result = new HashMap<>();
//把需要的信息放到異常中
result.put("id", ex.getId());
result.put("message", ex.getMessage());
return result;
}
}