Search code examples
javastruts2struts

Create multiple methods in one action class itself in Struts2?


Can I create two methods in the same Action Class? If so how can we specify it in the struts.xml file ?

For example : I created a simple validation action class to validate the email address as well as password using two separate regular expression. I created two Methods in the Action class say: emailVerification() and passVerification(). I wrote all the necessary validation code inside, but now when they return SUCCESS they should result into the same success page result and for ERROR likewise..


Solution

  • Yes you can create any number of methods in an Action Class. You can do something like this

    package com.myvalidation;
    
    public class MyValidationClass extends ActionSupport
    {
         public String emailVerification() throws Exception
         {
             //Your validation logic for email validation
             return SUCCESS;
         }
    
         public String passVerification() throws Exception
         {
             //Your validation logic for password validation
             return SUCCESS;
         }
    }
    

    struts.xml

    <action name="emailVerification" method="emailVerification" class="com.myvalidation.MyValidationClass">
            <result name="success">/your_success_jsp.jsp</result>
            <result name="input">/your_error_jsp.jsp</result>
    </action> 
    
    <action name="passVerification" method="passVerification" class="com.myvalidation.MyValidationClass">
        <result name="success">/your_success_jsp.jsp</result>
        <result name="input">/your_error_jsp.jsp</result>
    </action>