use*_*812 1 validation ejb bean-validation jsf-2
我想使用select来验证我的用户名.如果用户名已存在于数据库中,则验证失败.
我找到了像这样的primefaces的一些注释,例如:
@Size(min=2,max=5)
private String name;
Run Code Online (Sandbox Code Playgroud)
我没有找到这样的注释解决方案:
try {
dao.findUserByUserName(userName);
message = new FacesMessage ("Invalid username!", "Username Validation Error");
message.setDetail("Username already exists!");
message.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(message);
} catch (NoSuchUserException e) {}
Run Code Online (Sandbox Code Playgroud)
我是否必须使用自定义验证器或是否有注释?
我是否必须使用自定义验证器或是否有注释?
它可以通过两种方式完成.
在自定义JSF验证器的情况下,您只需要了解EJB不能注入@FacesValidator.你基本上有3种选择:
最终,你可以这样结束,假设你采用了这种@ManagedBean方法:
@ManagedBean
@RequestScoped
public class UsernameValidator implements Validator {
@EJB
private UserService service;
public void validate(FacesContext context, UIComponent component, Object submittedValue) throws ValidatorException {
if (submittedValue == null) {
return; // Let required="true" handle.
}
String username = (String) submittedValue;
if (service.exist(username) {
throw new ValidatorException(new FacesMessage("Username already in use, choose another"));
}
}
}
Run Code Online (Sandbox Code Playgroud)
使用如下:
<h:inputText ... validator="#{usernameValidator}" />
Run Code Online (Sandbox Code Playgroud)
在JSR303 bean验证的情况下,您需要创建自定义@Constraint注释以及自定义ConstraintValidator.你需要确保你至少使用CDI 1.1,否则你不能在一个EJB中注入一个EJB ConstraintValidator,你需要在initialize()方法中手动从JNDI中获取它.你无法通过使它成为托管bean来解决它,甚至OmniFaces也没有任何魔力.
例如
@Constraint(validatedBy = UsernameValidator.class)
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
public @interface Username {
String message() default "Username already in use, choose another";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Run Code Online (Sandbox Code Playgroud)
同
public class UsernameValidator implements ConstraintValidator<Username, String> {
@EJB
private UserService service;
@Override
public void initialize(Username constraintAnnotation) {
// If not on CDI 1.1 yet, then you need to manually grab EJB from JNDI here.
}
Override
public boolean isValid(String username, ConstraintValidatorContext context) {
return !service.exist(username);
}
}
Run Code Online (Sandbox Code Playgroud)
在模型中
@Username
private String username;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1918 次 |
| 最近记录: |