Springboot 通過自定義 DTO 實現 介面響應資料隱藏
阿新 • • 發佈:2021-08-05
參考
步驟
- pom.xml dependencies 中新增
<dependency> <groupId>org.modelmapper</groupId> <artifactId>modelmapper</artifactId> <version>2.4.2</version> </dependency>
- 入口檔案註冊 @Bean
public class SuddenlyNlineLearningPlatformApplication { // 裝配bean 實現dto轉換類自動注入 @Bean public ModelMapper modelMapper() { return new ModelMapper(); } public static void main(String[] args) { SpringApplication.run(SuddenlyNlineLearningPlatformApplication.class, args); } }
- 根據實體建立對應介面相應的 DTO 類
學生實體參考:
public class Student implements Serializable { /** * 序列化安全 */ private static final long serialVersionUID = 1L; private Integer id; /** * 賬號 */ private String account; /** * 密碼 */ private String password; /** * 使用者名稱 */ private String name; /** * 頭像 */ private String avatarUrl; /** * 性別 */ private Byte gender; /** * 手機號 */ private String phoneNumber; /** * 手機號驗證狀態 */ private byte phoneVerificationStatus; /** * 賬號 */ private String bewrite; /** * 建立時間 */ private Date createdAt; /** * 更新時間 */ private Date updatedAt; }
介面不想顯示密碼與實踐欄位,建立對應的DAO,DAO參考
public class InfoStudentDto implements Serializable {
/**
* 序列化安全
*/
private static final long serialVersionUID = 1L;
private Integer id;
/**
* 使用者名稱
*/
private String name;
/**
* 頭像
*/
private String avatarUrl;
/**
* 性別
*/
private Byte gender;
/**
* 手機號
*/
private String phoneNumber;
}
- 在控制器內使用
public class Info {
@Autowired
StudentService studentService;
// 自動注入
@Autowired
ModelMapper modelMapper;
/**
* 根據id獲取學生資訊
*/
@ApiOperation(value = "顯示學生資訊", notes = "檢視別人的(隱藏部分欄位)")
@ApiImplicitParam(name = "id", value = "學生id", required = true,
dataType = "int", paramType = "query")
@RequestMapping(value = "show", method = RequestMethod.GET)
public ResponseEntity<ResponseBody<InfoStudentDto>> show(@RequestParam("id") Integer id){
// 轉換
InfoStudentDto infoStudentDto = modelMapper.map(studentService.findById(id), InfoStudentDto.class);
return ResponseEntity.ok( new ResponseBody(infoStudentDto));
}
}
- 執行測試
總結
- 沒有演示如何轉換list
- 沒有測試DTO轉實體