Spring使用注解Aop处理前端Html转义字符

注解类

import java.lang.annotation.*;

/**
 * @author CJJ
 * @version 1.0
 * @createDate 2021/08/24 18:44
 * @see com.suncnpap.framework.web.annotation
 */
@Documented
@Inherited
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Unescape {
    boolean enable() default true;
}

aspect类环绕通知

import cn.hutool.http.HtmlUtil;
import com.suncnpap.framework.web.annotation.Unescape;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

/**
 * Unescape Annotation 处理
 * @author CJJ
 * @version 1.0
 * @createDate 2021/08/25 10:07
 * @see com.suncnpap.framework.web.aspect
 */

@Aspect
@Component
@Slf4j
@Order(-99)
public class UnescapeAspect {
//com.suncnpap.datacenter.datamart.pojo.vo.EscapeVo.getRawContent

    @Pointcut("execution(* com.suncnpap.datacenter.*.controller.*.*(..))")
    public void pointcutGet() {
    }

    @SneakyThrows
    @Around("pointcutGet()")
    public Object unescape(ProceedingJoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            Class<?> aClass = arg.getClass();
            String name = aClass.getName();
            if (name.contains(".pojo.")) {
                Field[] declaredFields = aClass.getDeclaredFields();
                for (Field declaredField : declaredFields) {
                    Unescape unescape = declaredField.getDeclaredAnnotation(Unescape.class);
                    if (null != unescape && unescape.enable()) {
                        log.info("field:{} with Unescape annotation!", declaredField.getName());
                        declaredField.setAccessible(true);
                        Object rawValue = declaredField.get(arg);
                        declaredField.set(arg, null == rawValue ? null : HtmlUtil.unescape(rawValue.toString()));
                    }
                }
            }
        }
        Object proceed = joinPoint.proceed(args);
        return proceed;
    }
}

切点表达式拦截方法

 在接收参数前,将有注解@Unescape的字段内容进行html解码

如果切点表达式拦截不到,检查是否扫描到,是否在spring容器中,切点表达式是否正确,idea是可以跳转到方法的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值