使用SpringMvc 開發 RESTful API 用戶詳情請求、JsonView註解使用(二)

@PathVariable 映射url片段到java方法的參數
在url聲明中使用正則表達式
@JsonView控制json輸出內容

1.獲取用戶詳情

測試用例

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;


@Test
public void whenGetInfoSuccess(){
// url代表資源,方法代表查詢做出的操作 狀態碼獲取狀態
mockMvc.perform(get("/user/1")
                .contentType(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(status().isOk)
                .andExcept(jsonPath($.username).value("tom"));
}

@Test
public whenGetInfoFalil(){
 mockMvc.perform(get("/user/a"))
             .contentType(MediaType.APPLICATION_JSON_UTF8)
             .andExcept(status().is4xxClientError()); 
}

Controller

    @GetMapping("/{id:\\d+}")
    public User getInfo(@PathVariable(value = "id") String id) {
        User user = new User();
        user.setUsername("tom");
        user.setPassword("123456");
        return user;
    }

2.@JsonView 註解的使用

什麼樣的場景下適用於JonView註解?
比如下面這兩個方法

// 返回一組信息
public List<User> query(){}   
// 返回單個用戶的信息
public User getInfo(){}   

在這個用戶的對對象裏面包含 兩個字段 一個是username 一個是password
假設在查詢的時候不把用戶的密碼返回過去,而在返回單個用戶信息的時候把密碼這個字段返回

JsonView使用步驟
使用接口來聲明多個視圖
在值對象的get方法上指定視圖
在Controller方法上指定視圖

/**
 * 用戶實體類
 * @author ZhuPengWei
 */
public class User {
   // 用戶的簡單視圖
   public interface UserSimpleView {};
   // 用戶的複雜視圖
   public interface UserDetailView extends UserSimpleView {};

   private String username;
   private String password;


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

}
// 返回一組用戶信息
@RequestMapping(value= "/user",method= RequestMethod.GET)
@JsonView(User.UserSimpleView.class )
public List<User> query(){}   
// 返回單個用戶的信息
@RequestMapping(value= "/user/{id : \\d+}",method= RequestMethod.GET)
@JsonView(User.UserDetailView.class )
public User getInfo(){}  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章