验证另一个控制器的一个bean(Spring MVC portlet)

时间:2013-02-04 09:02:39

标签: validation spring-mvc portlet

我试图做一些奇怪的事情,但我需要这样做......

我在两个控制器和两个验证器中有两个bean:让我们说......

BeanA {
    private String propertyA;
}

BeanB {
    private String propertyB;
}

为了保存bean A,我还需要验证bean B,所以我尝试做类似的事情:

@RequestMapping(params = ACTION_SAVE_BEAN_A)
public final void doActionSave (@ModelAttribute(value = ServletContextKeys.BEAN_A) BeanA beanA,
        Errors errors, ActionRequest actionrequest, ActionResponse actionResponse, PortletSession portletSession) {

    BeanB beanB = getBeanB();
    validatorBeanB.validate(beanB, errors);
    if (!errors.hasErrors()) {
        //Save beanA
        beanA.save();
    }

}

我的验证码:

validatorBeanB{

private void validatePropertyB(Errors errors) {
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, PROPERTY_B, BEANB_ERRORS + PROPERTY_B);
      }

   }

但执行此代码时,收到错误:

Caused by: org.springframework.beans.NotReadablePropertyException: Invalid property 'propertyB' of bean class [BeanA]: Bean property 'propertyB' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?

我理解错误,但我需要找到一个解决方法来修复它,我不能只将propertyB放在beanA中(实际上,它不仅仅是一个属性,bean中还有更多。 ..)

有什么想法吗?提前谢谢。

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。我没有在方法中声明错误(它与目标字段所关联的Bean A一起),而是在验证调用之前创建一个新错误。类似的东西:

BindingResult errors = new BeanPropertyBindingResult(beanB,"BeanB");

BeanBValidator.validate(beanB, errors);