1. 程式人生 > 其它 >Springboot 通過自定義 DTO 實現 介面響應資料隱藏

Springboot 通過自定義 DTO 實現 介面響應資料隱藏

參考

  1. 【SpringREST實體(entity)與資料傳輸物件(DTO)間的轉換-嗶哩嗶哩
  2. Spring Boot DTO示例:實體到DTO的轉換

步驟

  1. pom.xml dependencies 中新增
        <dependency>
            <groupId>org.modelmapper</groupId>
            <artifactId>modelmapper</artifactId>
            <version>2.4.2</version>
        </dependency>
  1. 入口檔案註冊 @Bean
public class SuddenlyNlineLearningPlatformApplication {

//    裝配bean 實現dto轉換類自動注入
    @Bean
    public ModelMapper modelMapper() {
        return new ModelMapper();
    }

    public static void main(String[] args) {
        SpringApplication.run(SuddenlyNlineLearningPlatformApplication.class, args);
    }

}

  1. 根據實體建立對應介面相應的 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;
}

  1. 在控制器內使用
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));
    }
}
  1. 執行測試

總結

  1. 沒有演示如何轉換list
  2. 沒有測試DTO轉實體
如果覺得文章對您有幫助,希望您能 關注+推薦 哦