在Struts 中进行数据验证

来源:互联网 发布:湖南软件职业学院分数线 编辑:程序博客网 时间:2024/04/28 20:51

 

主要有两种类型的数据验证,一种是数据的输入有效性验证,可以在ActionFormvalidate方法中进行验证;另一种是数据的逻辑有效性验证,可以在Action中进行验证.

首先说明如何在ActionForm中如何对前台输入的数据进行输入有效性验证:

1>     首先配置不合法数据的校验结果信息,可以配置在properties文件中,例如:application.properties中输入一下信息:

                  error1=username is null

error2=username.length=0

error3=username.length>0

2>     struts-config.xml中声明该文件:

……

<struts-config>

  …………….

     <message-resources parameter="application"/>

</struts-config>

3>     ActionForm中继承父类的validate方法,进行校验,如果不合法,则返回原页面:

public ActionErrors validate(ActionMapping actionMapping, javax.servlet.http.HttpServletRequest httpServletRequest) {

        ActionErrors errors = new ActionErrors();

        if ((username == null)) {

            errors.add("username", new ActionMessage("error1"));

            return errors;

        } else if ((username.length() < 1)) {

            errors.add("username", new ActionMessage("error2"));

            return errors;

        } else if ((username.length() >= 1)) {

            errors.add("username", new ActionMessage("error3"));

            return errors;

        }

        return errors;

}

4>     在前台页面显示错误信息:

<html:form action="/struts/loginAction.do?action=login">

<html:errors/> (或者<html:errors property=”username”/>)

</html:form>

如果需要把errors中的所有错误信息输出到前台,则调用<html:errors/>;

如果只需要把某条指定错误信息输出到前台页面,则调用<html:errors property=”username”/>,其中username是在ActionForm中定义的messageKey.

5>     在进行输入数据的有效性验证时,有几点需要注意的:

i>         struts-config.sml中配置action,需要把validate设为true;

ii>       struts-config.sml中配置action, 需要指定验证错误时的返回页: input="/struts/login.jsp"

iii>      properties文件要放到classpath,例如,放到/com/XXXX.properties,struts-config.xml中需要指定该路径:

<message-resources parameter="com.application"/>

    其次,Action中进行数据的逻辑有效性验证,需要用硬编码来实现了,这里就不再多说