Struts2验证框架 图片验证码 自定义验证器

时间:2022-12-30 18:37:24

首先我们需要一个生成图片验证码的类
http://blog.csdn.net/ruixue0117/article/details/22829557
但是要做一点小修改:

  1. 把上述网页中的类VerifyCodeUtils改为struts2 的action,即
public class ValidationCodeAction extends ActionSupport implements SessionAware {
private Map session;
}

并实现这两个方法,实现SessionAware(怎么实现这里不说了……)是为了在生成验证码图片时把正确的验证码值放到session,用于后面的验证框架进行获取、验证
在下面这个方法加上这句即可

 public void outputImage(int w, int h, OutputStream os, String code) throws IOException {
session.put("validationCode", code);//这句

2.之后要写一个Result类,用于在网页请求图片验证码时输出图片

public class ValidationCodeResult implements Result {
@Override
public void execute(ActionInvocation actionInvocation) throws Exception {
ValidationCodeAction action = (ValidationCodeAction) actionInvocation.getAction();
HttpServletResponse response = ServletActionContext.getResponse();

response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
//生成随机字串
String verifyCode = action.generateVerifyCode(4);


//生成图片
int w = 200, h = 80;
try {
action.outputImage(w, h, response.getOutputStream(), verifyCode);
} catch (IOException e) {
e.printStackTrace();
}
}
}

然后在struts.xml里面加一个result-type和action

<struts>
<package name="nPetStore" extends="struts-default">
<result-types>
<result-type name="validationCodeResult" class="web.ValidationCodeResult"></result-type>
</result-types>

记得result-type要放在最前面,这定义了一个返回类型。关于result-type,有redirect, stream等各种类型,详情自己搜索。

  <action name="validationCode" class="web.ValidationCodeAction">
<result name="success" type="validationCodeResult"></result>
</action>

然后在需要图片验证码的jsp网页,加上:

      <s:textfield label="验证码" name="validationCode"/>
<img src="<s:url action='validationCode'/>"/>

这样,在网页上就可以显示图片验证码了。
Struts2验证框架 图片验证码 自定义验证器

现在写验证框架
首先自定义一个验证器:

public class ValidationCodeValidator extends FieldValidatorSupport {
public String getSessionValidationCode() {
return sessionValidationCode;
}

public void setSessionValidationCode(String sessionValidationCode) {
this.sessionValidationCode = sessionValidationCode;
}

private String sessionValidationCode;
private boolean trim = true;

@Override
public void validate(Object o) throws ValidationException {

Object objValidateCode = getFieldValue(sessionValidationCode, o);
String fieldName = getFieldName();
String fieldValue = (String) getFieldValue(fieldName, o);
if (fieldValue == null)
return;
if (trim)
fieldValue = fieldValue.trim();
if (fieldValue.length() == 0) {

return;
}
if (!fieldValue.equals(objValidateCode)) {
addFieldError(fieldName, o);
}
}
}

然后在src目录下创建一个validators.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
"-//Apache Struts//XWork Validator Config 1.0//EN"
"http://struts.apache.org/dtds/xwork-validator-config-1.0.dtd">

<validators>
<validator name="validationCodeValidator" class="web.ValidationCodeValidator"/>

<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="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"/>

</validators>

第一个validator就是刚刚自定义的验证器
之后在需要验证器的action的目录下创建一个xml文件
同一目录Struts2验证框架 图片验证码 自定义验证器
xml命名格式: action类名-action名-validation.xml
如AccountAction-login-validation.xml 就是对AccountAction中名为login的action进行验证
xml文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE validators PUBLIC
"-//Apache Struts//XWork Validator 1.0.2//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd">


<validators>

<field name="validationCode">
<field-validator type="requiredstring">
<message>请输入验证码</message>
</field-validator>
<field-validator type="validationCodeValidator">
<param name="sessionValidationCode">
#session.validationCode
</param>
<message>验证码不正确</message>
</field-validator>
</field>


</validators>

之后在jsp中要加一个标签显示错误信息

 <font color="red"><s:fielderror ></s:fielderror></font>

网上其他教程不加也会显示错误信息,但不知道为什么我要加了才显示……
Struts2验证框架 图片验证码 自定义验证器


over