gpt4 book ai didi

java - Struts2验证短路

转载 作者:行者123 更新时间:2023-11-30 09:13:21 24 4
gpt4 key购买 nike

假设在操作类中有一个 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. 如果尝试使用负值,那么唯一的消息价格不能小于或等于零。 应该通过 @FieldExpressionValidator 出现。

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

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

最佳答案

乍一看没见过这么多。但是看着 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com