利用SpringAOP的返回通知处理数据加密返回

项目安全要求把所有返回值做加密处理,利用SpringAOP的返回切面可以简单方便的做到该需求。

java 复制代码
@Aspect
public class ResponseDataEncryptAspect {

    private ObjectMapper objectMapper;

    public ResponseDataEncryptAspect () {
        this.objectMapper = new ObjectMapper();
        // 保持空值也被序列化
        objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
    }
	
	// 拦截Controller内带@RequestMapper的方法及衍生注解即可
    @AfterReturning(value = PointCut.CONTROLLER_POINT_CUT, returning = "res")
    public void jsonDateEncrypt(JoinPoint joinPoint, Object res){
        // 只处理JsonResult返回值
        if (res instanceof JsonResult) {
            JsonResult jsonResult = (JsonResult) res;
            Object data = jsonResult.getData();
            if (null != data) {
                // 把data转成json串,再把json串加密,再替换原来的data,vue拦截到data作全局解密,不影响已绑定的功能。
                String json = objectMapper.writeValueAsString(data);
                String cryptResult = ZYCryptUtils.encryptAES(json);
                // 在全局响应结果里添加一个布尔值,方便前端判断到底是密文还是明文
                jsonResult.setEncrypt(true);
                jsonResult.setData(cryptResult);
            }
        }
    }
}

实际效果:

相关推荐
超级种码几秒前
Java:JavaAgent技术(java.instrument和java.attach)
java·开发语言·python
甜鲸鱼9 分钟前
【Spring AOP】操作日志的完整实现与原理剖析
java·spring boot·spring
狗头大军之江苏分军13 分钟前
年底科技大考:2025 中国前端工程师的 AI 辅助工具实战盘点
java·前端·后端
一 乐41 分钟前
酒店客房预订|基于springboot + vue酒店客房预订系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端
计算机毕设指导642 分钟前
基于Spring Boot的防诈骗管理系统【源码文末联系】
java·spring boot·后端·spring·tomcat·maven·intellij-idea
a程序小傲1 小时前
饿了吗Java面试被问:Redis的持久化策略对比(RDBVS AOF)
java·redis·面试
我家领养了个白胖胖1 小时前
MCP模型上下文协议 Model Context Protocol & 百度地图MCP开发
java·后端·ai编程
Coder_Boy_1 小时前
基于DDD+Spring Boot 3.2+LangChain4j构建企业级智能客服系统
java·人工智能·spring boot·后端
黄俊懿1 小时前
【深入理解SpringCloud微服务】Spring-Security作用与原理解析
java·后端·安全·spring·spring cloud·微服务·架构师
塔能物联运维1 小时前
设备自适应采样率忽视能耗致续航降 后来结合功耗模型动态调优
java·后端·struts