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. 運行測試

image

總結

  1. 沒有演示如何轉換list
  2. 沒有測試DTO轉實體


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM