java 在 Struts2 中显示验证错误消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16672435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 23:37:30  来源:igfitidea点击:

Displaying Validation Error Messages in Struts2

javawebstruts2struts

提问by user182944

I am new to Struts 2, have worked in Struts 1 earlier.

我是 Struts 2 的新手,之前曾在 Struts 1 中工作过。

How can we bind a error message with a UI component (e.g. a Text box) ? I don't want the error message to be a global one.

我们如何将错误消息与 UI 组件(例如文本框)绑定?我不希望错误消息是全局的。

For achieving the same in Struts 1:

为了在 Struts 1 中实现相同的目标:

In the form validate method, I used this:

在表单验证方法中,我使用了这个:

ActionErrors errors = new ActionErrors();       
if(userName != null && userName.length() <= 0)
    errors.add("userName",new ActionError("error.userName.required"));

and in the UI, for displaying the message:

在 UI 中,用于显示消息:

<html:messages id="userName" property="userName">
    <bean:write name="userName"/>
</html:messages>

In Struts 2, If I extend the Action class with ActionSupportand use this:

在 Struts 2 中,如果我扩展 Action 类ActionSupport并使用它:

addActionError(getText("Please enter UserId"));

Then it seems to be a global message which can be displayed in the UI using:

然后它似乎是一个全局消息,可以使用以下方法在 UI 中显示:

<s:actionerror />

Hence not sure how to achieve the same functionality in Struts 2. Kindly let me know on this.

因此不确定如何在 Struts 2 中实现相同的功能。请让我知道这一点。

回答by Dave Newton

The <s:fieldError>tagwould be the closest equivalent:

<s:fieldError>标签将是最接近的等效:

<s:fielderror fieldName="userName" />

On the Java side you'd use ValidationAware.addFieldErrorto add field-specific messages:

在 Java 端,您将用于ValidationAware.addFieldError添加特定于字段的消息:

public class AnyAction extends ActionSupport {
    public void validate() {
        addFieldError("userName", "User ID is required");
    }
}

That said, for the low-level validations, I'd stick to the default XML-based mechanism when possible, since it does a lot of this work for you, and makes working with I18N/properties a little easier.

也就是说,对于低级验证,我会尽可能坚持使用默认的基于 XML 的机制,因为它为您完成了很多此类工作,并使使用 I18N/属性更容易一些。