JFast应用系列之(7) -- 参数验证器概述

    对请求参数进行后端验证:

 

    创建参数验证类:

    

    1.必填验证:

     

    

@Validate(name = "require", description = "验证请求参数不可为null")
public class RequireValidate implements ValidateHandler{
	
	/**
	 * 必填验证
	 */
	@Override
	public void handleValidate(ApiInvocation invoke, String paramName, Object value) throws Exception {
		Assert.notNull(value);
	}
	
	/**
	 * 渲染验证失败的返回视图
	 */
	@Override
	public void handleError(ApiInvocation invoke, Exception validateError) {
		invoke.renderException(new Json("{error:'"+validateError.getMessage()+"'}"));             
        }

}

   

    2.邮箱验证:

    

     

@Validate(name = "email", description = "邮箱格式验证")
public class EmailValidate implements ValidateHandler {

	/**
	 * 邮箱格式验证
	 */
	@Override
	public void handleValidate(ApiInvocation invoke, String paramName, Object value) throws Exception {
		  String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
		  Pattern regex = Pattern.compile(check);
		  Matcher matcher = regex.matcher((String)value);
		  Assert.isTrue(matcher.matches(),"请填写正确邮箱");
	}
	
	/**
	 * 渲染验证失败的返回视图
	 */
	@Override
	public void handleError(ApiInvocation invoke, Exception validateError) {
		invoke.renderException(new Json("{error:'"+validateError.getMessage()+"'}"));        
	}

}

    

    控制器中调用参数验证:

 

    

@Get(path = "email")
public void validate(@HttpParam(validate={"require","email"}) String email){
		
}

 

你可能感兴趣的:(java,Restful,参数验证,jfast)