Struts2学习笔记(6)-简单的数据校验


数据校验是在项目开发中不可缺少的一部分,用户登录时、密码验证时都需要,当然要做的首先是获得用户输入的内容,然后对内容进行验证,一般都是从数据库中读出然后校验,如果错误则显示提示信息,正确则进入用户主界面。

下面用一个简单小例子来说明下步骤:

1、index的表单

http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<base href="<%=basePath %>"/> 
<title>Insert title here</title> 
</head> 
<body> 
<h1>演示</h1> 
<form action="user/user!check" method="post"> 
姓名:<input type="text" name="user.name"></input> 
<br/> 
年龄:<input type="text" name="user.age"></input> 
<br/> 
<input type="submit" value="提交"/> 
</form> 
</body> 
</html>

提交时会有两个变量--user.name 和user.age传到server,然后调用struts.xml文件配置中的对应Action

2、struts.xml配置

http://struts.apache.org/dtds/struts-2.0.dtd"> 
 
<struts> 
    <constant name="struts.devMode" value="true" /> 
    <package name="front" namespace="/user" extends="struts-default"> 
 
        <action name="user" class="com.myservice.web.UserAction"> 
            <result>/success.jsp</result> 
            <result name="error">/error.jsp</result> 
        </action> 
    </package> 
</struts>

很明显-当返回success时调用success.jsp,error则调用error.jsp

3、Action中的check方法内容

%@taglib uri="/struts-tags" prefix="s" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<title>Insert title here</title> 
</head> 
<body> 
<h2>验证失败</h2> 
<s:property value="errors.name[0]"/> 
<br> 
<s:property value="errors.name[1]"/> 
<s:debug></s:debug> 
</body> 
</html>

里面第三行是说明的添加了struts2的标签库,并且以s开头。

而倒数第四行和第六行是重点,errors.name[0]对应的就是我们在3中通过addFieldError方法,放入到name属性中的name is error,errors.name[1]则很明显是name is too long。倒数第三行是调试信息。

整个效果最后显示为:

以上就是Struts2中简单的数据校验的全部内容,希望能给大家一个参考,也希望大家多多支持phpstudy。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3