07.struts2中的数据合法性验证和文件上传
1、数据合法性验证
编程式验证
1、继承ActionSupport
2、重写validate方法
该方法在Validation拦截器中被调用执行
拦截器栈的执行顺序
prepare
modelDrivem
params
validation
3、编写验证规则
如果不符合规则,则调用addFieldError方法
addFieldError(错误的字段名,错误提示信息)
当执行该方法的时候,该方法会向值栈中添加错误消息(fieldErrors),并且返回result name=input
配置式验证
Struts2提供的验证器
验证器配置文件必须放在被验证的属性的同包下
名称:被验证的属性所在类的类名-validation.xml
<!--基于验证器
type:Struts2自带验证器的别名,在struts-core/com/opensymphony/xwork2/validator/validators/default.xml可以看到
-->
<validator name="required" class="com.opensymphony.xwork2.validator.validators.RequiredFieldValidator"/>
<validator name="requiredstring" class="com.opensymphony.xwork2.validator.validators.RequiredStringValidator"/>
<validator name="int" class="com.opensymphony.xwork2.validator.validators.IntRangeFieldValidator"/>
<validator name="long" class="com.opensymphony.xwork2.validator.validators.LongRangeFieldValidator"/>
<validator name="short" class="com.opensymphony.xwork2.validator.validators.ShortRangeFieldValidator"/>
<validator name="double" class="com.opensymphony.xwork2.validator.validators.DoubleRangeFieldValidator"/>
<validator name="date" class="com.opensymphony.xwork2.validator.validators.DateRangeFieldValidator"/>
<validator name="expression" class="com.opensymphony.xwork2.validator.validators.ExpressionValidator"/>
<validator name="fieldexpression" class="com.opensymphony.xwork2.validator.validators.FieldExpressionValidator"/>
<validator name="email" class="com.opensymphony.xwork2.validator.validators.EmailValidator"/>
<validator name="creditcard" class="com.opensymphony.xwork2.validator.validators.CreditCardValidator"/>
<validator name="url" class="com.opensymphony.xwork2.validator.validators.URLValidator"/>
<validator name="visitor" class="com.opensymphony.xwork2.validator.validators.VisitorFieldValidator"/>
<validator name="conversion" class="com.opensymphony.xwork2.validator.validators.ConversionErrorFieldValidator"/>
<validator name="stringlength" class="com.opensymphony.xwork2.validator.validators.StringLengthFieldValidator"/>
<validator name="regex" class="com.opensymphony.xwork2.validator.validators.RegexFieldValidator"/>
<validator name="conditionalvisitor" class="com.opensymphony.xwork2.validator.validators.ConditionalVisitorFieldValidator"/>
基于验证器的配置
<validator type="int">
<!-- 验证哪个字段 -->
<param name="fieldName">stuAge</param>