All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.nxyfan.framework.common.safe.EncryptResponseBodyAdvice Maven / Gradle / Ivy

package com.nxyfan.framework.common.safe;

import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import com.alibaba.fastjson.JSON;
import com.nxyfan.framework.common.annotation.CommonApiSafe;
import com.nxyfan.framework.common.util.CommonCryptogramUtil;

/** 
 *
 * Describe: 对响应的数据进行加密
 * Author: Administrator  
 * Create Time: 2024年4月25日 下午2:25:23 
 * Copyright @ 2024 51LIFE  
 */
@Aspect
@Component
@ControllerAdvice
public class EncryptResponseBodyAdvice implements ResponseBodyAdvice {

	@Override
    public boolean supports(MethodParameter methodParameter, Class> aClass) {
    	// 这里特意加上了CommonApiSafe,意味着只有加了该注解的方法才会走beforeBodyWrite方法
    	return methodParameter.hasMethodAnnotation(CommonApiSafe.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class> aClass, ServerHttpRequest request, ServerHttpResponse serverHttpResponse) {
        // 拿到响应的数据
        String json = JSON.toJSONString(body);
        // 进行加密返回
        return CommonCryptogramUtil.doSm2Encrypt(json);
    }
    
}