使用ActionForm的validate()进行验证
1 Struts validate
1.1 使用ActionForm的validate()验证
总体思路:这个验证是没有添加验证框架的验证,而是直接通过ActionForm的validate()方法进行系统验证,
进行验证要处理三个方面的问题:
> 配置资源文件:配置ApplicationResources.prop内容,把验证的的内容写道其中;
> 配置FormBean: 配置FormBean中的validate()方法,处理相关验证;
> 配置Jsp:配置JSP中相关信息接受后台验证信息的处理结果;
1.1.1 验证步骤 (验证登录页面中的userName不为空为例)
1.1.1.1 打开userForm的验证
在struts-config.xml中找到相应的ActionMapping内容:
<action-mappings >
<action
attribute="insertUserForm"
name="insertUserForm"
input="regeditUser.jsp"
path="/regedit"
scope="request"
type="com.kevinb.struts.action.RegeditAction"
validate="true"> //注意:本处是最新添加的部分,开启了form的验证功能,不打开进行验证也是无效的;
<forward name="regeditOk" path="/viewUser.jsp" />
</action>
1.1.1.2 在资源文件中填写相应的错误信息,并且进行验证信息规划 ,在资源文件中添加 :
userName.required=userName is required,please input information...
其中:userName.required是key
userName is required,please input information...是value
userName.required对应后台UserForm中validate()方法中的error.add("userName",new ActionMessage("userName.required"));
和new ActionMessage("key"),对应;
1.1.1.3 在UserForm中的validate()中写代码:
//申请一个error实例,用来存放验证信息
ActionErrors error = new ActionErrors();
//验证用户名称不能够为空
if(userName == null || userName.equals("")){
error.add("userName",new ActionMessage("userName.required"));
}
...
return error;
其中:error.add("userName",new ActionMessage("userName.required"))中
userName:对应页面中的<html:errors property="userName"/>中的property中的内容;
userName.required:对应资源文件中的:userName.required=userName is required,please input information...前半部分;
所以,error.add("key","value")起到了一个连接页面和资源文件的左右,并且处理相关的信息;
注意:ActionErrors的实例用法和Map的用法类似在后台通过error.add("key","value");存入数据,
前台通过:<html:errors property="userName"/><br>进行接受,其中后台中的key的内容一定要和
前台property中的内容完全一致,前台也是通过这个key进行接受后台信息的,接受的内容是
new ActionMessage("userName.required"),其中userName.required是资源文件中的内容的key,
对应资源文件中的:userName.required=userName is required,please input information...
内容,所以前台最后呈现的内容是:userName is required,please input information...
1.1.1.4 在页面中接受错误信息
<html:form action="login.do">
userName:<html:text property="userName"></html:text>
<html:errors property="userName"/><br> //处理错误,打印资源文件中的错误信息;
还有一个验证框架 讲师提醒还是少用 比较好!
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator- rules.xml,/WEB-INF/validation.xml" />
</plug-in>
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· Ai满嘴顺口溜,想考研?浪费我几个小时
· Browser-use 详细介绍&使用文档
· 软件产品开发中常见的10个问题及处理方法