struts2标签标签方式的输入校验与类型转换

来源:互联网 发布:子女宫武曲天府知乎 编辑:程序博客网 时间:2024/05/16 01:41

regist2.jsp

          <table align="center" width="40%">
            <tr>
                <td>
                    <s:fielderror cssStyle="color:red" />
                </td>
            </tr>
        </table>

        <s:form action="register">
                        <s:textfield name="username" label="username"></s:textfield>
                        <s:password name="password" label="password"></s:password>
                        <s:password name="repassword" label="repassword"></s:password>
                        <s:textfield name="age" label="age"></s:textfield>
                        <s:textfield name="birthday" label="birthday"></s:textfield>
                        <s:textfield name="graduation" label="graduation"></s:textfield>
                        <s:submit value=" submit "></s:submit>
                        <s:reset value=" reset "></s:reset>
        </s:form>

struts2标签的label属性会自动在文本框前面显示

 

RegisterAction.java

public class RegisterAction extends ActionSupport {
    private String username;
    private String password;
    private String repassword;
    private int age;
    private Date birthday;
    private Date graduation;

 

    getter...   setter...

 

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

 

    @Override
    public void validate() {

            if (null == username || username.length() < 6 || username.length() > 10) {
                this.addActionError("username invalid");
            }

        if (null == password || password.length() < 6 || password.length() > 10) {
            this.addActionError("password invalid");
        }
        else if (null == repassword || repassword.length() < 6 || repassword.length() > 10) {
            this.addActionError("re-password invalid");
        }
        else if (!password.equals(repassword)) {
            this.addActionError("two passwords not the same");
        }
        if (age <= 0 || age > 150) {
            this.addActionError("age should be between 1 and 150");
        }
        if (null != birthday && null != graduation) {
            Calendar c1 = Calendar.getInstance();
            c1.setTime(birthday);
            Calendar c2 = Calendar.getInstance();
            c2.setTime(graduation);
            if (!c1.before(c2)) {
                this.addActionError("birthday should be before graduation");
            }
        }

    }

 

类型转换与输入校验的流程
1. 首先Struts2对客户端传来的数据进行类型转换
2. 类型转换完毕后再进行输入校验
3. 如果类型转换和输入校验都没有错误发生,那么进入execute方法(调用商业逻辑)
注意:如果类型转换不成功,也同样要进行输入校验