Using Spring AOP to modify request and return parameters

AOP: a technology for aspect oriented programming to achieve unified maintenance of program functions through precompiling and runtime dynamic agents.

By using AOP technology, we can expand the corresponding operations on the tangent point in the customized tangent plane, such as printing logs, converting parameters, etc.

In production, in order to ensure the data security or reduce the data transmission volume, the parameters are often processed with BASE64 encoding, asymmetric encryption and other operations when they are transferred. Generally, we will encapsulate a public class and call it when the parameters need to be encoded, decoded or encrypted, which will cause certain code redundancy. Above all, we can use AOP technology to liberate the operation.

Taking BASE64 encoding and decoding of parameters as an example, we first define cut plane and cut point:

 * @author : niithub
 * @description : Facet - verify request parameters
 * @date : 2018/7/20
public class ParamAspect {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Pointcut("execution(public * com..*.*Controller.*(..))")
    public void doOperation() {"Parameter test AOP");

    public Object doBefore(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] obj = joinPoint.getArgs();
        byte[] param = null;
        for (Object argItem : obj) {
            String convertData;
            if (argItem instanceof String) {
                param = Base64Utils.decode(String.valueOf(argItem).getBytes());
            convertData = new String(param);
            Map map = MAPPER.readValue(convertData, Map.class);
            if(map.get("body") == null) {
                throw new ApiRuntimeException(-1, "Parameter error");
            obj[0] = MAPPER.writeValueAsString(map.get("body"));
        return joinPoint.proceed(obj);

    @AfterReturning(returning = "object", pointcut = "doOperation()")
    public void doAfterReturning(Object object) {
        ResponseMessage responseMessage = (ResponseMessage) object;
        byte[] a = Base64Utils.encode(String.valueOf(responseMessage.getData()).getBytes());
        responseMessage.setMsg(new String(a ));"Request return value[{}]", object.toString());


The doBefore method decodes the request parameters, and the doAfterReturning method encodes the return parameters.

1. Modify request parameters

Request parameters:

Printed request parameters:

2. Modify return parameters

As shown in the figure above, the return parameter should be {"code":0,"msg":"1","data":"2"}, and the actual return result is:

Let's take a look at the debug process:

Tags: encoding Programming

Posted on Tue, 07 Jan 2020 01:02:10 -0800 by amal.barman