0%

struts2 Action中对表单提交数据的验证

应用中经常要对用户提交的数据进行验证,根据验证结果返回不同的页面,显示不同的信息。 struts2的表单验证流程:Action继承ActionSupport类,在执行execute()方法前,先执行validate()方法验证数据,如果有不合要求的数据,添加错误信息,当validate()方法执行完,如果发现错误信息不为空,则不再执行execute()方法,直接转发请求到struts.xml中定义的Action, result标签name属性为input对应的页面,下面的例子是直接转向到用户提交数据的页面。在用户提交的页面中,如果表单是用struts标签生成,则会自动填充之前填写的数据,还可以用struts标签输出错误信息。 提交信息的页面register.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>




Insert title here



    
    ------------------------
    
    
    
        用户名
        
        密码
        
        重复密码
        
        
    

接收用户提交的Action: RegisterAction.java

package com.struts2;

import com.opensymphony.xwork2.ActionSupport;

public class RegisterAction extends ActionSupport {
    private String username;
    private String password;
    private String repassword;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getRepassword() {
        return repassword;
    }

    public void setRepassword(String repassword) {
        this.repassword = repassword;
    }


    @Override
    public String execute() throws Exception {
        // TODO Auto-generated method stub
        System.out.println("execute");
        return SUCCESS;
    }

    @Override
    public void validate() {
        // TODO Auto-generated method stub
        // 合法的情况什么都不用干
        //有错误会自动转向struts.xml中定义的result标签name属性为input的页面,本例中即用户输入页面
        if (username == null || username.length() < 4 || username.length() > 6) {
            //两种不同的方式添加错误信息
            this.addActionError("用户名不合规则");
            //参数为字段名,错误信息
            this.addFieldError("username", "用户名不合规则");
        }
        if(password==null||repassword==null||password!=repassword||password.length()<4||password.length()>6)
        {
            this.addActionError("密码不合规则");
        }
    }

}

struts.xml中Action的声明:

        <action name="register" class="com.struts2.RegisterAction">
            <result name="success">/registerResult.jsp</result>
            <result name="input">/register.jsp</result>
        </action>

通过验证后转向的页面,registerResult.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>




Insert title here


    用户名 
    密码