博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[struts]使用struts验证框架验证表单输入如何配置Action
阅读量:7289 次
发布时间:2019-06-30

本文共 1908 字,大约阅读时间需要 6 分钟。

使用struts校验框架验证表单输入很方便,有两种使用方式:1.添加到Action类的validate方法验证用户的输入。2.使用XML表单验证Form Validation Using XML(当然也可以用注释annotation但和xml类似)。原理是一样的,这里以第一种方式说明struts校验框架执行的时机。

struts校验框架执行时机

原文:When the user presses the submit button on the register form, Struts 2 will transfer the user's input to the personBean's instance fields. Then Struts 2 will automatically execute the validate method. If any of the if statements are true, Struts 2 will call its addFieldError method (which our Action class inherited by extending ActionSupport).

If any errors have been added then Struts 2 will not proceed to call the execute method. Rather the Struts 2 framework will return "input" as the result of calling the action.

当用户填写完表单并提交时,struts首先将请求数据封装到一个personBean实例的各个数据域中(注意这里自动执行 数据类型转换,struts的优点之一),并作为参数传递给相应action处理类(有的书上称这个也是IOC,把参数注入到action实例中)。然后,执行validate方法验证输入数据是否合法,如果不合法,第一种方式,通过手动调用addFieldError()继承自ActionSupport,添加错误信息。第二种方式,自动调用此方法添加fieldError错误信息。

如果出现任何错误(类型转换、表单输入验证),struts将不再调用execute方法,而是直接调用input方法返回input视图。

错误信息的显示:

So when validation fails and Struts 2 returns input, the Struts 2 framework will redisplay the register.jsp. Since we used Struts 2 form tags, automatically Struts 2 will add the error messages.

will cause the message "First name is required" to be displayed above the firstName field on the form.

如果表单使用struts标签,且struts.ui.theme不是"simple" 默认是“xhtml”,且返回到注册页面时,相应输入错误的表单域上方就会有提示信息。

如果表单未使用struts标签,或struts.ui.theme是"simple",则需要在页面添加

<s:if test="hasFieldErrors()">

    <s:fielderror/>
</s:if>

或<s:fielderror/>即可。

 

上一篇文章中,提到了action配置时使用验证框架出现问题。校验框架使用的freemarker获取不到key。原因不是首次进入未曾填写注册页,获取不到表单信息。

对于使用struts验证框架时action的配置需要注意:(使用XML表单验证)

1.不配置action处理类,则不会应用action处理类的相应校验规则

<action name="userInfo_login">

            <result>/WEB-INF/view/user/login.jsp</result>
</action>

2.配置action处理类,则xml校验文件命名:类名-validate.xml 或者 类名-action名-validate.xml

转载于:https://www.cnblogs.com/wanping/archive/2012/10/07/2714333.html

你可能感兴趣的文章
Centos安装EPEL扩展源
查看>>
echo 颜色控制
查看>>
python学习过程-字符串说明
查看>>
mysql数据库问题杂记
查看>>
三台主机部署lamp(fast-cgi)
查看>>
ASM磁盘超过disk_repair_time导致磁盘状态为forcing
查看>>
微信小程序上拉、下拉、动态设置窗口背景色
查看>>
uboot bootargs bootcmd bootm
查看>>
Java对XML属性解析功能
查看>>
【AD用户设置系列一】让IT省心省力的漫游配置文件
查看>>
C(++) web实时消息服务器后台推送技术方案---GoEasy
查看>>
软件测试的三大测试方向比较
查看>>
Linux日知录(常用问题笔记)
查看>>
CentOS7利用yum安装node.js
查看>>
Tomcat 应用多次重启失败,查看日志:UnknownHostException,可能是DNS故障
查看>>
centos7 安装nginx 完整步骤
查看>>
第3章 代码块
查看>>
JavaWeb23-HTML篇笔记(二)
查看>>
Linux 后台运行管理
查看>>
洞悉物联网发展1000问之为什么物联网会有真假智慧?
查看>>