作为应用程序的增长Struts 2的验证工作不正常 [英] Struts 2 validation not working properly as application grows

查看:189
本文介绍了作为应用程序的增长Struts 2的验证工作不正常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有替代的验证框架,同时建立复杂的Web应用程序?或者验证的指南。链接例如并不需要,因为它工作的简单形式,但不是在通过多条链路复杂的形式。

Is there any alternative validation framework while building complex web app? Or any guide for validation. Links to example is not required as it working on simple Form but not in complex Form with multiple links.

这是我的动作类

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;
}   
}

这是LeadFacultyAction-validation.xml中:

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>

这是在struts.xml文件:

this is 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>

这是我的JSP文件:

 <%@ 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>

推荐答案

所不同的是只有在Struts的发现验证注解,而拦截行动就处理这些注释通过应用注释暴露验证规则进行验证。同样的事情是解析 -validation.xml 时。您可以使用基于注释和基于在一起,或者除了定制验证(不包括自定义验证器)两种验证方法XML。

The difference is only if Struts discover validation annotations while intercepting the action it processes those annotations to perform validations by applying validation rules exposed by annotations. The same thing is when parsing -validation.xml. You can use both validation methods xml based and annotation based together, or with addition to custom validation (excluding custom validators).

例如,如果我有一个电话字段,我想验证它不是空的,并包含一个predefined格式我只是把两个注解就可以了。

For example, if I have a phone field and I want to validate 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;
  }

然后我有一个执行操作我的不要的验证

  @SkipValidation
  public String execute() throws Exception {

然后我有另一个动作保存我想验证问题,但我不想验证电话

then I have another action save that I want to validate questions but I don't want to validate 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 {

这将在这个动作只执行验证。

this will execute only validators on this action.

更多的例子,你总是可以找到的Apache Web站点:

More examples you could always find on Apache web site:

这篇关于作为应用程序的增长Struts 2的验证工作不正常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆