在web开发中,通常会对一些属性进行模糊查询或者精确查询,但是用户在输入之前或之后可能会输入空格。这些空格通常是不需要进行匹配的,所以需要后台自动去掉空格。这样的接口通常在一个系统中会有多个,为了对每个接口的每个字符串做同样的处理,通常我们会写一个前置通知,具体代码如下:
1.aspect
package com.mayi1203.myproject.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import com.mayi1203.myproject.util.TrimUtils;
/**
* 修剪通知,去掉字符串前后端的空格
* @author 码蚁1203
* @date 2020年4月30日
*/
@Component
@Aspect
public class TrimAspect {
@Before("execution(* com.mayi1203.myproject.*.*Controller.*(..))")
public void before(JoinPoint joinPoint) {
Object[] args = joinPoint.getArgs();
for(Object arg : args) {
TrimUtils.trim(arg);
}
}
}
2.util
package com.mayi1203.myproject.util;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Objects;
import org.springframework.beans.BeanUtils;
import org.springframework.util.Assert;
/**
* 修剪工具类
* @author 码蚁1203
* @date 2020年4月30日
*/
public final class TrimUtils {
public final static void trim(Object source) {
Assert.notNull(source, "Source must not be null");
Class<?> editable = source.getClass();
PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(editable);
for(PropertyDescriptor pd : pds) {
Method readMethod = pd.getReadMethod();
Method writeMethod = pd.getWriteMethod();
if(Objects.nonNull(readMethod) && Objects.nonNull(writeMethod)) {
try {
if(!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
readMethod.setAccessible(true);
}
Object value = readMethod.invoke(source);
if(value instanceof String) {
String str = (String)value;
str = null == str ? null : str.trim();
writeMethod.invoke(source, str);
}
} catch (Throwable ex){
ex.printStackTrace();
}
}
}
}
}
3.controller
package com.mayi1203.myproject.controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.mayi1203.myproject.dto.FriendDTO;
@RestController
@RequestMapping("v1/test")
public class TestController {
@PostMapping("test")
public FriendDTO test(@RequestBody FriendDTO dto) {
return dto;
}
}
4.dto
package com.mayi1203.myproject.dto;
import lombok.Data;
/**
* 朋友类
* @author 码蚁1203
* @date 2020年4月30日
*/
@Data
public class FriendDTO {
private String name;
private String nation;
}
5.request
6.response