Jfinal实战:自定义方法级别的Validator

    Jfinal官方提供的validator一般用来对controller中某一方法进行条件验证,如果需要对controller
中多个方法进行不同条件的验证,则需要些多个validator文件,那么有没有办法将同一个contrler中方法的
validate方法写到同一个validator文件中呢,答案当然是yes,我们可以通过自定义注解来解决这个问题。
  • 1、自定义方法级别的注解

    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface MethodValidator {

    
     /**
     * 验证器方法
     * @return
     */
    String name();
    

    }

  • 2、自定义BaseValidator

    public abstract class BaseValidator extends Validator {

    protected void validate(Controller controller) {
        Method method=getActionMethod();
        if (method.isAnnotationPresent(MethodValidator.class)) {
            String name = method.getAnnotation(MethodValidator.class).name();
            for(Method me:this.getClass().getMethods())
            {
                if (me.getName().equals(name)) {
                    try {
                        me.invoke(this,controller);
                    } catch (IllegalAccessException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IllegalArgumentException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    break;
                }
            }
        }
    }

    }

3、例子validator

public class Area2Validator  extends BaseValidator {

    public void validate2(Controller controller)
    {
        validateRequiredString("bArea.id", "parendIdMsg", "父级不可为空!validate2");
    }

    public void validate3(Controller controller)
    {
        validateRequiredString("bArea.id", "parendIdMsg", "父级不可为空!validate3");
    }

    protected void handleError(Controller controller) {
        controller.keepModel(Area2.class);
        RespBody respBody= new RespBody();
        respBody.setSuccess(false);
        controller.setAttr("json", respBody);
        controller.renderJson();
    }
}

4、例子controller

@Before(Area2Validator.class)
public class Area2Controller extends BaseController{
    protected static final Logger log = LoggerFactory.getLogger(Area2Controller.class);
    
    @MethodValidator(name="validate2")
    public void test2() {
        log.debug("modify"+new Random().nextDouble());
    }
    
    @MethodValidator(name="validate3")
    public void test3() {
        log.debug("delete"+new Random().nextDouble());
    }
}

你可能感兴趣的:(validator,jfinal)