在我的 Controller 中,我有一个如下所示的方法:
public QueryResult<TrsAccount> listExclude(String codeAccount, String searchFilter, String order, int pageNumber,
int pageSize){}
但是在执行这个方法之前我必须检查如果:
Assert.TRUE(codeAccount.matches("^[0-9]{1,20}$"));
因为这在我的应用程序中很常见而且不仅是这种情况,所以我想要一种检查参数格式的通用方法。我现在使用的方式是使用AOP,其中:
@Aspect
public class HijackBeforeMethod {
@Pointcut("within(@org.springframework.stereotype.Controller *)")
public void controllerBean() {
}
@Pointcut("execution(* *(..))")
public void methodPointcut() {
}
@Before(value = "controllerBean() && methodPointcut()", argNames = "joinPoint")
public void before(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Object[] args = joinPoint.getArgs();
String[] paramNames = signature.getParameterNames();
for (int count = 0; count < paramNames.length; count++) {
String tempParam = paramNames[count];
Object tempValue = args[count];
if (tempParam.toLowerCase().equalsIgnoreCase("codeAccount") && Assert.isNotNull(tempValue)
&& Assert.isNotEmpty((String) tempValue)) {
Assert.TRUE(((String) tempValue).matches("^[0-9]{1,20}$"));
}
}
}
}
如您所见,这是非常基本且容易出错的代码片段。有没有更好的解决方案??
最佳答案
不推荐在 Controller 中使用 AOP。更好的方法是 to use JSR 303 / JSR 349 Bean Validation ,但这可能需要将字符串包装在一个值对象中,然后对其进行相应的注释。
如果你坚持用AOP解决这个问题,you'll probably need a ControllerAdvice
关于java - 如何在 Controller 方法之前检查参数值格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37559997/