基于springboot創(chuàng)建RESTful風(fēng)格接口

基于springboot創(chuàng)建RESTful風(fēng)格接口

RESTful API風(fēng)格

restfulAPI.png

特點:

  1. URL描述資源
  2. 使用HTTP方法描述行為。使用HTTP狀態(tài)碼來表示不同的結(jié)果
  3. 使用json交互數(shù)據(jù)
  4. RESTful只是一種風(fēng)格,并不是強制的標準
REST成熟度模型.png

一、查詢請求

1.編寫單元測試

@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字符串當成變量返回
        
        System.out.println(result);//[{"username":null},{"username":null},{"username":null}]
    }
}

2.使用注解聲明RestfulAPI

常用注解

@RestController 標明此Controller提供RestAPI
@RequestMapping及其變體。映射http請求url到j(luò)ava方法
@RequestParam 映射請求參數(shù)到j(luò)ava方法的參數(shù)
@PageableDefault 指定分頁參數(shù)默認值
@PathVariable 映射url片段到j(luò)ava方法的參數(shù)
在url聲明中使用正則表達式
@JsonView控制json輸出內(nèi)容

查詢請求:

@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;
    }
}

①當前端傳遞的參數(shù)和后臺自己定義的參數(shù)不一致時,可以使用name屬性來標記:

(@RequestParam(name="username",required=false,defaultValue="hcx") String nickname

②前端不傳參數(shù)時,使用默認值 defaultValue="hcx"

③當查詢參數(shù)很多時,可以使用對象接收

④使用Pageable作為參數(shù)接收,前臺可以傳遞分頁相關(guān)參數(shù)
pageSize,pageNumber,sort;
也可以使用@PageableDefault指定默認的參數(shù)值。

@PageableDefault(page=2,size=17,sort="username,asc")
//查詢第二頁,查詢17條,按照用戶名升序排列

3.jsonPath表達式書寫

github鏈接:https://github.com/json-path/JsonPath

jsonpath表達式.png
打包發(fā)布maven項目.png

二、編寫用戶詳情服務(wù)

@PathVariable 映射url片段到j(luò)ava方法的參數(shù)
在url聲明中使用正則表達式
@JsonView控制json輸出內(nèi)容

單元測試:

@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}
        
    }

后臺代碼:

@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;
        }

當希望對傳遞進來的參數(shù)作一些限制時,可以使用正則表達式:

//測試提交錯誤信息
@Test
public void whenGetInfoFail() throws Exception {
    mockMvc.perform(get("/user/a")
            .contentType(MediaType.APPLICATION_JSON_UTF8))
            .andExpect(status().is4xxClientError());
}

后臺代碼:

@RequestMapping(value="/user/{id:\\d+}",method=RequestMethod.GET)//如果希望對傳遞進來的參數(shù)作一些限制,使用正則表達式
@JsonView(User.UserDetailView.class)
public User getInfo(@PathVariable String id) {
    User user = new User();
    user.setUsername("tom");
    return user;
}

使用@JsonView控制json輸出內(nèi)容

1.場景:在以上兩個方法中,查詢集合和查詢用戶詳細信息時,期望查詢用戶集合時不返回密碼給前端,而在查詢單個用戶信息時才返回。

2.使用步驟:
①使用接口來聲明多個視圖
②在值對象的get方法上指定視圖
③在Controller方法上指定視圖

在user實體中操作:

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視圖的時候同時會把simple視圖的所有字段也顯示出來
    public interface UserDetailView extends UserSimpleView{};
    
    @MyConstraint(message="這是一個測試")
    private String username;
    
    @NotBlank(message = "密碼不能為空")
    private String password;
    
    private String id;
    
    @Past(message="生日必須是過去的時間")
    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) //在簡單視圖上展示該字段
    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)//如果希望對傳遞進來的參數(shù)作一些限制,就需要使用正則表達式
@JsonView(User.UserDetailView.class)
public User getInfo(@PathVariable String id) {
    User user = new User();
    user.setUsername("tom");
    return user;
}

單元測試:

//查詢
@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字符串當成變量返回
    
    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.在每個url中都重復(fù)聲明了/user,此時就可以提到類中聲明

@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)建請求

1.@RequestBody 映射請求體到j(luò)ava方法的參數(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}
}

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ù)的處理

對于日期的處理應(yīng)該交給前端或app端,所以統(tǒng)一使用時間戳

前端或app端拿到時間戳,由他們自己決定轉(zhuǎn)換成什么格式,而不是由后端轉(zhuǎn)好直接給前端。

前端傳遞給后臺直接傳時間戳:

@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:

@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驗證請求參數(shù)的合法性并處理校驗結(jié)果

1.hibernate.validator中的常用驗證注解:

注解及其含義.png

①在實體中添加相應(yīng)驗證注解:

@NotBlank
private String password;

②后臺接收參數(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:帶著錯誤信息進入方法體

@PostMapping
public User create(@Valid @RequestBody User user,BindingResult errors) {
    
    if(errors.hasErrors()) {
        //有錯誤返回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 {
    //一年之后的時間
    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()) {
        //有錯誤返回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()); 
            //密碼不能為空
            //生日必須是過去的時間
            //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;
}

實體:

public class User {
    
    public interface UserSimpleView{};
    //有了該繼承關(guān)系,在顯示detail視圖的時候同時會把simple視圖的所有字段也顯示出來
    public interface UserDetailView extends UserSimpleView{};
    
    @MyConstraint(message="這是一個測試")
    private String username;
    
    @NotBlank(message = "密碼不能為空")
    private String password;
    
    private String id;
    
    @Past(message="生日必須是過去的時間")
    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) //在簡單視圖上展示該字段
    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.自定義校驗注解

創(chuàng)建一個注解MyConstraint:

@Target({ElementType.METHOD,ElementType.FIELD})//可以標注在方法和字段上
@Retention(RetentionPolicy.RUNTIME)//運行時注解
@Constraint(validatedBy = MyConstraintValidator.class)//validatedBy :當前的注解需要使用什么類去校驗,即校驗邏輯
public @interface MyConstraint {
    
    String message();//校驗不通過要發(fā)送的信息

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };
    
}

校驗類:MyConstraintValidator:

public class MyConstraintValidator implements ConstraintValidator<MyConstraint, Object> {

    /*ConstraintValidator<A, T>
    參數(shù)一:驗證的注解
    參數(shù)二:驗證的類型
    ConstraintValidator<MyConstraint, String> 當前注解只能放在String類型字段上才會起作用
    */
    @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:校驗失?。籺rue:校驗成功
    }
    
}

五、處理刪除

單元測試:

@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錯誤處理

1.Spring Boot中默認的錯誤處理機制

Spring Boot中默認的錯誤處理機制,
對于瀏覽器是響應(yīng)一個html錯誤頁面,
對于app是返回錯誤狀態(tài)碼和一段json字符串

2.自定義異常處理

①針對瀏覽器發(fā)出的請求

在src/mian/resources文件夾下創(chuàng)建文件夾error編寫錯誤頁面

錯誤頁面.png

對應(yīng)的錯誤狀態(tài)碼就會去到對應(yīng)的頁面

只會對瀏覽器發(fā)出的請求有作用,對app發(fā)出的請求,錯誤返回仍然是錯誤碼和json字符串

②針對客戶端app發(fā)出的請求

自定義異常:

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中拋自己定義的異常

//發(fā)生異常時,拋自己自定義的異常
@GetMapping("/{id:\\d+}")
@JsonView(User.UserDetailView.class)
public User getInfo1(@PathVariable String id) {
    throw new UserNotExistException(id);
}

默認情況下,springboot不讀取id的信息

拋出異常時,進入該方法進行處理:
ControllerExceptionHandler:

@ControllerAdvice //只負責(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;
    }

}

完整Demo鏈接:https://github.com/GitHongcx/RESTfulAPIDemo

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,554評論 19 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,273評論 6 342
  • 這是我在高中就很喜歡一則故事。 有一個男孩有著很壞的脾氣,一天他的父親給了他一袋釘子,告訴他,每當他發(fā)脾氣的時候就...
    Louise718閱讀 287評論 0 2
  • 就想說出來。跟她說,能不能別一整天的都跟我講你男朋友,什么都分享,任何細節(jié)都不放過。甚至你們的吻也可以細節(jié)化出來,...
    張小橘閱讀 276評論 0 2
  • 文/左岸江南 20歲到30歲,是女人一生中最美的時候,也是職場發(fā)展的黃金期。這個時候,好看是一種天賦資源,是資本,...
    左岸江南閱讀 584評論 0 1

友情鏈接更多精彩內(nèi)容