import com.hsq.common.utils.StringUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
@Component
@Aspect
public class FuzzyQueryAspect {
@Around("@annotation(com.hsq.common.aop.FuzzyQuery)")
public Object proceed(ProceedingJoinPoint joinPoint)
throws Throwable {
Object[] args = joinPoint.getArgs();
for (Object arg : args) {
Field[] fields = arg.getClass().getDeclaredFields();
for (Field field : fields) {
FuzzyQuery fuzzyQuery = field.getAnnotation(FuzzyQuery.class);
if (fuzzyQuery != null) {
field.setAccessible(true);
String value = field.get(arg) == null ? null : String.valueOf(field.get(arg));
value = StringUtil.escapeSpecialChar(value);
field.set(arg, value);
}
}
}
return joinPoint.proceed();
}
}
StringUtil
public static String escapeSpecialChar(String keyword){
log.info("input:"+keyword);
if (StringUtils.isNotBlank(keyword)) {
String[] fbsArr = { "\\", "$", "|","%","_" , "(", ")", "*", "+", ".", "[", "]", "?", "^", "{", "}"};
for (String key : fbsArr) {
if (keyword.contains(key)) {
log.info("escapeSpecialChar:"+key);
keyword = keyword.replace(key, "\\" + key);
}
}
}
log.info("output:"+keyword);
return keyword;
}
@Target({ElementType.FIELD,ElementType.PARAMETER,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface FuzzyQuery {
}
使用
@FuzzyQuery
private String keyWord;//关键字查询
controller也加上@FuzzyQuery