假设操作类中有一个 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>
我想要实现,
- 如果该字段留空,则唯一的消息,价格是强制性的。应该通过
@RequiredFieldValidator
显示 - 如果输入“abc”等非数字值,则它应该仅显示属性文件中的转换错误消息。
- 如果尝试使用负值,则唯一的消息“价格不能小于或等于零”。 应通过
@FieldExpressionValidator
显示。
一次应该出现一个转换错误或一个验证错误。
这可能吗?到目前为止,我还没有正确理解 shourtCircuit
属性的功能。
最佳答案
乍一看还没有看到那么多。但看看Type Conversion Error Handling我想说有一种方法可以处理转换错误。通过在短路 validator 的配置中添加转换 validator 。 Short-circuit意味着如果这样的 validator 有错误,其他 validator 将被跳过。
conversionErrorFields = @ConversionErrorFieldValidator(fieldName = "price", message = "Price has invalid value", shortCircuit = true)
将此代码放在@Validations
注释下。
关于java - Struts2 验证中的短路,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21050502/