Struts2验证中的短路

时间:2014-01-10 17:21:27

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

假设动作类中有BigDecimal类型的字段如下。

@Namespace("/admin_side")
@ResultPath("/WEB-INF/content")
@ParentPackage(value = "struts-default")
public final class TestAction extends ActionSupport
{
    private BigDecimal price;

    //Setter and getter.        

    @Validations(
    requiredFields = {
        @RequiredFieldValidator(fieldName = "price", type = ValidatorType.FIELD, message = "Price is mandatory.")},
    fieldExpressions = {
        @FieldExpressionValidator(fieldName = "price", expression = "price>0", shortCircuit = true, message = "Price cannot be less than or equal to zero.")})
    @Action(value = "Add",
    results = {
        @Result(name = ActionSupport.SUCCESS, type = "redirectAction", params = {"namespace", "/admin_side", "actionName", "Test"}),
        @Result(name = ActionSupport.INPUT, location = "Test.jsp")},
    interceptorRefs = {
        @InterceptorRef(value = "defaultStack", params = {"params.acceptParamNames", "price", "validation.validateAnnotatedMethodOnly", "true"})
    })
    public String insert() {
        return ActionSupport.SUCCESS;
    }

    //This method is worth nothing. It is used just to return an initial view on page load.
    @Action(value = "Test",
    results = {
        @Result(name = ActionSupport.SUCCESS, location = "Test.jsp"),
        @Result(name = ActionSupport.INPUT, location = "Test.jsp")},
    interceptorRefs = {
        @InterceptorRef(value = "defaultStack", params = {"params.acceptParamNames", "", "params.excludeMethods", "load", "validation.validateAnnotatedMethodOnly", "true"})})
    public String load() throws Exception {
        return ActionSupport.SUCCESS;
    }
}

以下是表格。

<s:form namespace="/admin_side" action="Test" id="dataForm" name="dataForm">
    <s:fielderror fieldName="price"/>
    <s:textfield id="price" name="price"/>

    <s:submit value="Submit" action="Add"/>
</s:form>

我想实现,

  1. 如果该字段留空,那么唯一的消息价格是强制性的。应该通过@RequiredFieldValidator
  2. 显示
  3. 如果输入了非数字值,例如“abc”,那么它应该只显示属性文件中的转换错误消息。
  4. 如果尝试使用负值,则唯一的消息 Price不能小于或等于零。应该通过@FieldExpressionValidator显示。
  5. 一次只能出现一个转换错误或一个验证错误。

    这可能吗?到目前为止,我还没有正确理解shourtCircuit属性的功能。

1 个答案:

答案 0 :(得分:2)

乍一看,我们看不到这么多。但是看看docs我说有一种处理转换错误的方法。通过在配置中添加转换验证器,这是一个短路验证器。 Short-circuit表示如果此类验证程序出现错误,则会跳过其他验证程序。

 conversionErrorFields = @ConversionErrorFieldValidator(fieldName = "price", message = "Price has invalid value", shortCircuit = true) 

将此代码放在@Validations注释下。