Springboot2.x 通过自定义 DTO 实现 接口响应数据隐藏
参考
步骤
- 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转实体
博 主 :夏秋初
地 址 :https://www.cnblogs.com/xiaqiuchu/p/15102283.html
如果对你有帮助,可以点一下 推荐 或者 关注 吗?会让我的分享变得更有动力~
转载时请带上原文链接,谢谢。
地 址 :https://www.cnblogs.com/xiaqiuchu/p/15102283.html
如果对你有帮助,可以点一下 推荐 或者 关注 吗?会让我的分享变得更有动力~
转载时请带上原文链接,谢谢。
标签:
dto
, springboot
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义