سؤال

I am using Struts 1.2 for my application. I have a validate method for my form where I am doing some validation for the inputs provided by the user. Below is the code for the userName provided by the user:

@Override
public ActionErrors validate(ActionMapping mapping,
        HttpServletRequest request) {

    System.out.println("Validating the Form...");
    ActionErrors errors = new ActionErrors();

    if(userName != null && userName.length() <= 0)
        errors.add("userName",new ActionError("Invalid UserName"));

    return errors;
}

If the userName is not wntered by the user, then the above error message should be displayed in the UI. Below is the code I used in the jsp file for displaying the above error message:

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

But it did not displayed any error message.

I also tried this alternative but this also did not worked.:

<logic:messagesPresent property="userName">                             
        <html:errors property="userName" /><html:errors/>       
</logic:messagesPresent>

When I try debugging the code, the validate method is getting executed in the form and the execute method is not triggered since there are validation errors. In the UI, no error message is getting displayed. Kindly let me know how to fix this.

هل كانت مفيدة؟

المحلول

ActionError does not take the error message itself. Instead, it takes a key to the error message in the application's MessageResources bundle.

From the Struts documentation on Automatic Form Validation:

Return an ActionErrors instance containing ActionMessage's, which are classes that contain the error message keys (into the application's MessageResources bundle) that should be displayed.

So, you should do something like this:

errors.add("userName",new ActionError("userName.invalid"));

Then, in your resource bundle, you should have something like this:

userName.invalid=Invalid UserName

Also, Struts 1.x is quite old and has reached End-Of-Life. If this is a new application, I would recommend looking at something newer.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top