struts2 check frame check

struts2 provides the validate framework for validation

example

The first step is to create ValidateAction.java

public class validate extends ActionSupport{
    private String username;
    private String password;
    //get()和set()方法,构造方法

The second step is to write the validation rule configuration file

Create a ValidationAction-validation.xml file under the current package.
This file can be found in the struts2 package we downloaded: the path is as follows: struts-2.3.15.3\apps\struts2-blank\WEB-INF\classes\example\Login-validation.xml

In Struts2, the naming of the validation rule configuration file in XML format is also specified, and it needs to be named in the following format:
ActionClassName-validation.xml
or
ActionClassName-ActionName-validation.xml
where ActionName is the name of the action configuration in struts.xml, Here we use the first naming convention

ValidationAction-validation.xml

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

<validators>
    <field name="username">
        <field-validator type="requiredstring"><!-- 必须输入 -->
            <message>用户名不能为空</message>
        </field-validator>
    </field>
    <field name="age">
        <field-validator type="int"><!-- 必须是整数 -->
            <param name="min">13</param>
            <param name="max">20</param>
            <message>必须是数字在13到20之间</message>
        </field-validator>
    </field>
    <field name="password">
        <field-validator type="stringlength"><!--字符串长度 -->
            <param name="minLength">6</param>
            <param name="maxLength">10</param>
            <message>密码最少6位最多10位</message>
        </field-validator>
    </field>
</validators>

Step 3: Configure the Action class in struts.xml

<package name="formTest03" namespace="/" extends="struts-default">

        <action name="validate" class = "formTest03.validate" method="execute">
            <result name="success">/success.jsp</result>
            <result name="input">/validate2.jsp</result>
        </action>       
    </package>

Step 4: Write JSP page validation.jsp


  <body>
    <s:form action="validate" method="post">
        <s:fielderror>
            <s:param>username</s:param>
            <s:param>password</s:param>
            <s:param>age</s:param>
        </s:fielderror>
        <s:textfield name="username" label="姓名"></s:textfield>
        <s:textfield name="password" label="密码"></s:textfield>
        <s:textfield name ="age" label="年龄"></s:textfield>      
        <s:submit value="提交"></s:submit>
    </s:form>
  </body>

write picture description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325769859&siteId=291194637