Created
March 6, 2014 02:02
-
-
Save wendal/9380748 to your computer and use it in GitHub Desktop.
nutz与Validation, 基于jsr303
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.nutz.integration.jsr303; | |
import java.util.Set; | |
import javax.validation.ConstraintViolation; | |
import javax.validation.Valid; | |
import javax.validation.Validation; | |
import javax.validation.Validator; | |
import javax.validation.ValidatorFactory; | |
import org.nutz.mvc.ActionContext; | |
import org.nutz.mvc.impl.processor.AbstractProcessor; | |
public class ValidationProcessor extends AbstractProcessor { | |
protected ValidatorFactory factory; | |
protected Validator validator; | |
public ValidationProcessor() { | |
init(); | |
} | |
public void init() { | |
factory = Validation.buildDefaultValidatorFactory(); | |
validator = factory.getValidator(); | |
} | |
public void process(ActionContext ac) throws Throwable { | |
Object[] args = ac.getMethodArgs(); | |
if (args == null || args.length == 0) { | |
doNext(ac); | |
return; | |
} | |
for (Object obj : args) { | |
if (obj == null) | |
continue; | |
if (obj.getClass().getAnnotation(Valid.class) == null) | |
continue; | |
Set<ConstraintViolation<Object>> rest = validator.validate(obj); | |
ac.getRequest().setAttribute("violations", rest); | |
break; | |
} | |
doNext(ac); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment