Reputation: 8067
I am new to Struts 2, have worked in Struts 1 earlier.
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.
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.
Upvotes: 2
Views: 14041
Reputation: 160181
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.
Upvotes: 5