Tapan Mohakul
Tapan Mohakul

Reputation: 85

The validation and theme in Struts 2

I am working on a Struts 2 project ,the problem is that I am using <constant name="struts.ui.theme" value="simple"/> in my struts.xml for the layout of my JSP page(e.g arranging 2-3 textfiled in one line using tablecode ) as per the CSS applied, but I am not able show the validation error on the same jsp page due to theme="simple".

Configuration:

<struts>
    <!-- Configuration for the default package. -->
    <constant name="struts.ui.theme" value="simple"/>
    <package name="default"   extends="struts-default">
        <action name="validateUser" class="login.LoginAction">
            <result name="SUCCESS">/welcome.jsp</result>
            <result name="input">/login.jsp</result>
        </action>
    </package>
</struts>

Action:

public class LoginAction extends ActionSupport{

    private String username; // getter and setter
    private String password; // getter and setter


    @Override
    public String execute() {
        // some business logic here....
        return "SUCCESS";    
    }
    //simple validation
    @Override 
    public void validate(){             
        if("".equals(getUsername())){
            addFieldError("username", getText("username.required"));
        }
        if("".equals(getPassword())){
            addFieldError("password", getText("password.required"));
        }
    }       
}

View:

<s:form action="validateUser" validate="true" >
    <table>
        <tr>
            <td>username</td>
            <td><s:textfield  label="username" name="username" /><td/>
        </tr>
        <tr>
            <td>password</td>
            <td><s:password  label="password" name="password" /><td/>
        <tr> 
            <td> <s:submit  label="submit" name="submit"/></td>
        </tr>
     </table>
</s:form>

Is there a way to maintain the layout with my CSS and also use Struts 2 validation ?

Upvotes: 6

Views: 1058

Answers (1)

Andrea Ligios
Andrea Ligios

Reputation: 50203

Sure! The XHTML theme will automatically add a fieldError tag to your input tags;

when using the Simple theme, instead, you need to add them manually, and give an id to your tags to match them (unless it would be autogenerated, and more difficult to spot):

<td>
    <s:textfield id="username" label="username" name="username" />
    <s:fielderror fieldName="username" />
</td>

<td>
    <s:password id="password" label="password" name="password" />
    <s:fielderror fieldName="password" />
</td>

P.S: I guess these are in the typos and errors are in the question only, and not in the real code, but you have:

  • self closing <td/>,
  • an unclosed <tr>, and
  • a <tr> with a single <td> without a colspan="2" specified.

Upvotes: 4

Related Questions