【问题标题】:How to validate Boolean fields in Struts2 using annotations?如何使用注释验证 Struts2 中的布尔字段?
【发布时间】:2014-01-03 11:52:16
【问题描述】:

在这样的操作类中给定一个Boolean 字段。

@Namespace("/admin_side")
@ResultPath("/WEB-INF/content")
@ParentPackage(value="struts-default")
public final class TestAction extends ActionSupport implements Serializable, ValidationAware, ModelDriven<Entity>
{
    private Boolean boolField;

    public Boolean getBoolField()
    {
        return boolField;
    }

    public Boolean setBoolField(Boolean boolField)
    {
        this.boolField=boolField;
    }

    @Validations(requiredFields={@RequiredFieldValidator(fieldName="boolField", type= ValidatorType.FIELD, key="delete.row.confirm")})
    @Action(value = "testAction",
            results = {
                @Result(name=ActionSupport.SUCCESS, type="redirectAction", location="Test.action"),
                @Result(name = ActionSupport.INPUT, location = "Test.jsp")},
    public String testAction()
    {            
        return ActionSupport.SUCCESS;
    }

    // The rest of the action class.
}

动作类boolField 中的字段只有在设置为true 时才应该被验证。它可能是隐藏字段&lt;s:hidden&gt;,也可以通过查询字符串参数设置。

Thisthis 问题使用 XML 配置进行布尔字段验证,但不涉及注释。

如何使用注释验证此类布尔字段?

我已经避免使用拦截器和其他东西来缩短代码。

【问题讨论】:

    标签: java validation struts2 ognl struts2-convention-plugin


    【解决方案1】:

    您可以使用@FieldExpressionValidator 执行此操作。例如

    @Validations(fieldExpressions = @FieldExpressionValidator(fieldName="boolField", expression="boolField == true", message="boolField should be set"))
    

    【讨论】:

    • 它验证一个Boolean类型的字段,当它的值设置为true时。但是当动作类中的Boolean 类型字段设置为false 时,它会导致java.lang.NullPointerException 被抛出事件,尽管该字段还有一个@RequiredFieldValidator
    • 这是因为值不是null。查看更新。
    • 哦,是的!确实,我没有注意到。傻我:)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-25
    • 2019-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-19
    • 1970-01-01
    相关资源
    最近更新 更多