Search code examples
jspvalidationstruts2jsp-tags

Need help in displaying error message in a jsp page


I am new to struts 2. I just tried to validate a form using validation.xml file and it works fine.

But Error messages are displayed on the top of the text field . Need to display those error messages to the right side of the test field with red font.

My jsp code(index.jsp)

<s:form action="addEmp" method="post">
      <s:textfield name="name" label="Name" size="20" />
      <s:textfield name="age" label="Age" size="20" />
      <s:select name="gender" headerKey="0" headerValue="Select Gender"
     label="gender" list="#{'1':'Male','2':'Female'}" />

      <s:textfield name="email" label="Email" size="20" />
      <s:textfield name="phone" label="Phone_Number" size="20" />
      <s:textfield name="address" label="Address" size="20" />
      <s:submit name="submit" label="Login" align="center" />  
   </s:form>

My Action class(Employee.java):

package com.tutorialspoint.struts2;
import com.opensymphony.xwork2.ActionSupport;

public class Employee extends ActionSupport{

   public String addEmployee()
   {
       return SUCCESS;
   }

}

struts.xml file:

<action name="addEmp" 
   class="com.tutorialspoint.struts2.Employee"
  method="addEmployee"  >
   <result name="input">/index.jsp</result>
  <result name="success">/success.jsp</result>
</action>

and Employee-validation.xml file:

 <validators>
       <field name="name">
          <field-validator type="requiredstring">
             <message>
                The name is required.
             </message>
          </field-validator>
       </field>

       <field name="gender">
         <field-validator type="int">
         <param name="min">1</param>
             <message>
                Please select a value
             </message>
          </field-validator>
       </field>

       <field name="email">
          <field-validator type="requiredstring">
             <message>
                The email is required.
             </message>
          </field-validator>
         <field-validator type="email">
             <message>
                Please enter a valid email ID
             </message>
          </field-validator>
       </field>

Please help me doing this.. Thanks in advance.


Solution

  • This is due to default theme being used by Struts2.Please remember that struts2 uses theme layout to generate HTML based on the tags being used by you and will create default layout for you.

    By default Struts2 use xhtml theme which means that it will create some sort of table, tr and td. just have a look in the generated source code and you will able to see what is happing.

    I suggest to switch simple theme and it will let you control layout with your custom CSS.

    Have a look at themes and how they work, i believe it will help you to get an idea