如何在bean验证中注入httpSession属性?

时间:2019-06-26 21:38:17

标签: eclipselink cdi bean-validation

我正在使用自定义Bean验证,但是当我尝试通过CDI在 validator类中通过传递 JPA bean 来注入http会话属性时,会出现异常。 (EclipseLink 2.1)作为参数之一;但是当我将其注入 JSF bean (Mojarra 2.2)时,它可以正常工作。

JPA bean (代码摘录):

@Entity
@Table(name = "TaxiTrips", catalog = "DIAGE", schema = "gdt")
@XmlRootElement
@JustificativaFunciConstraint
@NamedQueries({...})
public class TaxiTrips implements Serializable {
[...]
}

(CDI)托管bean (代码摘录):

@Named(value = "taxiTripsController")
@ApplicationScoped
public class TaxiTripsController extends AbstractController<TaxiTrips> {

@Inject
@SessionChave
private String httpSessionChave;

private String sessionChave;

public String getSessionChave() {
    return sessionChave;
}

@PostConstruct
public void init() {
    sessionChave = httpSessionChave;
 }
}

约束类

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = JustificativaFunciValidator.class)
public @interface JustificativaFunciConstraint {

String message() default "Not allowed, sorry.";

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};
}

验证器类

public class JustificativaFunciValidator implements ConstraintValidator<JustificativaFunciConstraint, TaxiTrips> {

@Inject
@SessionChave
private String httpSessionChave;

private String sessionChave;

@Override
public void initialize(JustificativaFunciConstraint constraintAnnotation) {
}

@Override
public boolean isValid(TaxiTrips taxiTrips, ConstraintValidatorContext context) {

    if (httpSessionChave == null) {
        sessionChave = "F0000000";
    } else {
        sessionChave = httpSessionChave;
}
    return taxiTrips.getMatricula().getMatricula().equals(sessionChave);
}

@PostConstruct
public void init() {
    sessionChave = httpSessionChave; //it is not injecting, the value is null here
 }
}

执行edit方法时,将启动以下异常:

javax.validation.ConstraintViolationException: Bean Validation constraint(s) violated while executing Automatic Bean Validation on callback event:'preUpdate'. Please refer to embedded ConstraintViolations for details.

我研究并找到了这两个问题(question 1question 2),但是我不知道该怎么做才能解决我的问题。

有人可以帮助我吗?

0 个答案:

没有答案