Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check argument value formatting before controller method?

In my controller I have a method such as bellow:

public QueryResult<TrsAccount> listExclude(String codeAccount, String searchFilter, String order, int pageNumber,
     int pageSize){}

But before executing this method I have to chech if:

Assert.TRUE(codeAccount.matches("^[0-9]{1,20}$"));

Because this is very frequent in my application and it is not only this case, I want a general approach to check the argument format. The way I'm using now is the use of AOP, in which:

@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}$"));
     }
  }
}
}

As you can see, this is very rudimentary and error prone code snippet. Is there any better solutions??

like image 225
Khoda Avatar asked Aug 21 '26 22:08

Khoda


1 Answers

Using AOP in Controllers is not really recommended. A better approach would be to use JSR 303 / JSR 349 Bean Validation, but that would probably require wrapping the string in a value object, which is then annotated accordingly.

If you insist on solving this with AOP, you'll probably need a ControllerAdvice

like image 197
Sean Patrick Floyd Avatar answered Aug 24 '26 12:08

Sean Patrick Floyd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!