2

让我们假设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. 如果输入了像“abc”这样的非数字值,它应该只显示来自属性文件的转换错误消息。
  3. 如果尝试负值,则唯一的消息Price 不能小于或等于零。应该通过@FieldExpressionValidator.

一次应该出现一个转换错误或一个验证错误。

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

4

1 回答 1

2

乍一看没见过这么多。但是看看类型转换错误处理我会说有一种方法可以处理转换错误。通过将转换验证器添加到短路验证器的配置中。短路意味着如果此类验证器有错误,则跳过其他验证器。

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

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

于 2014-01-10T19:33:06.880 回答