简体   繁体   中英

Displaying Validation Error Messages in Struts2

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

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

For achieving the same in 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:

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

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

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

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

<s:actionerror />

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

The <s:fieldError> tag would be the closest equivalent:

<s:fielderror fieldName="userName" />

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM