Struts 2 assertion not working as expected as the application grows

Is there any alternative validation scheme when building a complex web application? Or any manual to check. Example links are not required when working with a simple form, but not in a complex form with multiple links.

This is my action class

package com.tpc.action;

 import java.util.ArrayList;
 import java.util.List;

 import com.opensymphony.xwork2.ActionSupport;
 import com.tpc.domain.LeadFacultyModel;
 import com.tpc.service.LeadFacultyServiceInterface;

  public class LeadFacultyAction extends ActionSupport {


private static final long serialVersionUID = 1L;


private LeadFacultyModel leadFacultyModel;

private String lead_faculty_formAction;

// Injecting leadFacultyServiceImpl bean 
LeadFacultyServiceInterface leadFacultyServiceImpl;


//variable to store the action message to pass to other pages through get request
private String action_msg = null;

private List<LeadFacultyModel> leadFacultyModelList = new ArrayList<LeadFacultyModel>();


public String execute() throws Exception {
    return SUCCESS;
}


public String formAction() throws Exception
{
    if(lead_faculty_formAction.equals("Save"))
    {
        System.out.println("Inside Update");
        return this.updateLeadFaculty();
    }
    else if(lead_faculty_formAction.equals("Submit"))
    {
        System.out.println("Inside Save");
        return this.saveLeadFaculty();      
    }
    else if(lead_faculty_formAction.equals("Delete"))
    {
        System.out.println("Inside Delete");
        return this.deleteLeadFaculty();
    }
    else
    {
        return SUCCESS;
    }           

}

public String saveLeadFaculty() throws Exception {

    boolean result =leadFacultyServiceImpl.createLeadFaculty(leadFacultyModel);
    if(result == true)
    {
        addActionMessage(getText("message.save_success"));
        return "SAVE_SUCCESS";
    }
    else {
        addActionError(getText("message.save_error"));
        return  "SAVE_ERROR";
    }

}

public String viewAllLeadFaculty(){
    // TODO Auto-generated method stub
    System.out.println("view all method is called");
    try{
        leadFacultyModelList = leadFacultyServiceImpl.getAllLeadFaculty();
        System.out.println("Action page "+leadFacultyModelList.size());
        return SUCCESS;
    }catch(Exception ex){
        ex.printStackTrace();
        return ERROR;
    }


}



//Section of getter/setter methods in this class

public void setLeadFacultyModel(LeadFacultyModel leadFacultyModel) {
    this.leadFacultyModel = leadFacultyModel;
}

public LeadFacultyModel getLeadFacultyModel() {
    return leadFacultyModel;
}

public String getLead_faculty_formAction() {
    return lead_faculty_formAction;
}
public void setLead_faculty_formAction(String lead_faculty_formAction) {
    this.lead_faculty_formAction = lead_faculty_formAction;
}

public void setLeadFacultyServiceImpl(
        LeadFacultyServiceInterface leadFacultyServiceImpl) {
    this.leadFacultyServiceImpl = leadFacultyServiceImpl;
}

public void setAction_msg(String action_msg) {
    this.action_msg = action_msg;
}

public List<LeadFacultyModel> getLeadFacultyModelList() {
    return leadFacultyModelList;
}

public void setLeadFacultyModelList(List<LeadFacultyModel> leadFacultyModelList) {
    this.leadFacultyModelList = leadFacultyModelList;
}

public String getAction_msg() {
    return action_msg;
}   
}

      

This is LeadFacultyAction-validation.xml:

<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN"
    "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">



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

      

this is the struts.xml file:

<?xml version="1.0" encoding="UTF-8"?>

      

  

<package name="default" extends="struts-default">

<!-- /** defining result types for implementing tiles **/ -->
    <result-types>
        <result-type name="tiles"
            class="org.apache.struts2.views.tiles.TilesResult" />
    </result-types>
    <global-results>
        <result name="error">/404_error.jsp</result>
    </global-results>
    <action name="">
        <result></result>
    </action>
    <action name="baseTemplate" >
        <result type="tiles">baseTemplate</result>
    </action>


    <action name="setup_lead_faculty">
        <result type="tiles">setup_lead_faculty</result>
    </action>

    <action name="setup_LeadFacultyAction" class="com.tpc.action.LeadFacultyAction" method="formAction">
        <result name="SAVE_SUCCESS" type="tiles">setup_lead_faculty</result>
        <result name="UPDATE_SUCCESS" type="tiles">setup_lead_faculty</result>
        <result name="DELETE_SUCCESS" type="tiles">setup_lead_faculty</result>
        <result name="SAVE_ERROR" type="tiles">setup_lead_faculty</result>
        <result name="UPDATE_ERROR" type="tiles">setup_lead_faculty</result>
        <result name="DELETE_ERROR" type="tiles">setup_lead_faculty</result>
        <result name="input" type="tiles">setup_lead_faculty</result>
    </action>

    <action name="setup_LeadFaculty_list_view_Action" class="com.tpc.action.LeadFacultyAction" method="viewAllLeadFaculty">
        <result type="tiles" name="success">setup_lead_faculty_list_view</result>
    </action>

    <action name="setup_LeadFacultyAction_selected_from_list" class="com.tpc.action.LeadFacultyAction" method="getByIdLeadFaculty">
        <result type="tiles" name="success">setup_lead_faculty</result>
    </action>

</package>

      

This is my JSP file:

 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
 <c:set value="/lms/" var="baseUrl" />
<s:form method="post" action="setup_LeadFacultyAction">
<div class="buttontab">
    <input type="submit" name="lead_faculty_formAction" value="Save"
        class="form_button" /> &nbsp;&nbsp;&nbsp; <input type="submit"
        name="lead_faculty_formAction" value="Submit" class="form_button" />
    &nbsp;&nbsp;&nbsp; <input type="submit" name="lead_faculty_formAction"
        value="Delete" class="form_button" /> &nbsp;&nbsp;&nbsp; <input
        type="submit" name="lead_faculty_formAction" value="Reset"     disabled="disabled"
        class="form_button" /> &nbsp;&nbsp;&nbsp; <span class="span"
        style="float: right;"> <i><a   href="${baseUrl}lead/setup_LeadFaculty_list_view_Action"> <img
            src="${baseUrl}icons/gridview.png" width="12px" height="12px" /></a> </i> </span>&nbsp;&nbsp;&nbsp;
    <span class="span" style="float: right;"> <i><img
            src="${baseUrl}icons/formview.png" width="12px" height="12px" /> </i> </span>&nbsp;&nbsp;&nbsp;
    <span class="span" style="float: right;"> <i><img
            src="${baseUrl}icons/tileview.png" width="12px" height="12px" /> </i> </span>&nbsp;&nbsp;&nbsp;
</div>
<div id="content_wrap">
    <div class="unidiv1">

        <s:if test="hasActionErrors()">
            <div class="errors">
                <s:actionerror/>
            </div>
        </s:if>
        <s:if test="hasActionMessages()">
            <div>
                <p><s:actionmessage/></p>
            </div>      
        </s:if>
        <s:if test="hasFieldErrors()">
            <div>
                <p><s:fielderror/></p>
            </div>      
        </s:if>

        <div class="field_wrapper">
            <div class="left_box">
                <label>ID</label>
            </div>
            <div class="right_box">
                <input type="text" name="leadFacultyModel.lead_string_FacultyId" value="${leadFacultyModel.lead_string_FacultyId}"
                    class="input_id" />
            </div>
        </div>
        <div class="field_wrapper">
            <div class="left_box">
                <label>Faculy</label>
            </div>
            <div class="right_box">
                <input type="text" name="leadFacultyModel.lead_string_FacultyName" value="${leadFacultyModel.lead_string_FacultyName }" />
            </div>

        </div>
        <div class="field_wrapper">
            <div class="left_box">
                <label>Remarks</label>
            </div>
            <div class="right_box">
                <textarea name="leadFacultyModel.lead_string_FacultyRemarks"
                    class="textarea_address">${leadFacultyModel.lead_string_FacultyRemarks}</textarea>
            </div>
        </div>


    </div>
</div>

      

+1


source to share


1 answer


The only difference is that Struts detects validation annotations by intercepting the action that processes those annotations to perform validation, applying the validation rules set by the annotations. The same goes for analysis -validation.xml

. You can use both xml based validation methods and annotations based on each other, or with the addition of custom validation (excluding custom validators).

For example, if I have a field phone

and I want to validate it, it is not empty and contains a predefined format, I will just put two annotations on it.

  private String phone;

  public String getPhone() {
    return phone;
  }

  @RequiredStringValidator(type= ValidatorType.FIELD, message="Phone required.")
  @RegexFieldValidator(type= ValidatorType.FIELD, message="Invalid Phone",
    regexExpression="\\([0-9][0-9][0-9]\\)\\s[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]")
  public void setPhone(String phone) {
    this.phone = phone;
  }

      

then I have an action execute

that I don't want to test

  @SkipValidation
  public String execute() throws Exception {

      



then I have another activity save

that I want to test questions

, but I don't want to test a phone

.

  private String myQuestionq1;
  private String myQuestionq2;

  public String getMyQuestionq1() {
    return myQuestionq1;
  }

  public void setMyQuestionq1(String myQuestionq1) {
    this.myQuestionq1 = myQuestionq1;
  }

  public String getMyQuestionq2() {
    return myQuestionq2;
  }

  public void setMyQuestionq2(String myQuestionq2) {
    this.myQuestionq2 = myQuestionq2;
  }

  @Action(value="save", results = {
    @Result(name="input", location = "/default.jsp"),
    @Result(name="back", type="redirect", location = "/")

  },interceptorRefs = @InterceptorRef(value="defaultStack", params = {"validation.validateAnnotatedMethodOnly", "true"}))
  @Validations(requiredFields = {
      @RequiredFieldValidator(type = ValidatorType.FIELD, fieldName = "myQuestionq1", message = "You must enter a value for field myQuestionq1."),
      @RequiredFieldValidator(type = ValidatorType.FIELD, fieldName = "myQuestionq2", message = "You must enter a value for field myQuestionq2.")
  })
  public String save() throws SQLException {

      

only validators will be executed for this action.

Other examples you can always find on the Apache website:

Validation using sample annotations

+1


source







All Articles