【发布时间】:2016-06-01 05:18:45
【问题描述】:
在我的控制器中,我有如下方法:
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}$"));
}
}
}
}
如您所见,这是非常基本且容易出错的代码 sn-p。有没有更好的解决办法??
【问题讨论】:
-
只是不要...使用对象并通过 JSR303 验证或自定义验证器对其进行验证。
标签: java spring spring-mvc spring-aop