1. pom.xml 引入kaptcha
2. web.xml 添加servlet
3. 以下是登录用Action中的代码:
添加变量及常量:
private String kaptchafield;
public static final String ATTEMPT_TIMES = "attempt_times";
/**
* 显示验证码之前登录验证错误次数
*/
public static final int ATTEMPT_TIMES_UNTIL_SHOW_CAPTCHA = 2;
public void setKaptchafield(String kaptchafield) {
this.kaptchafield = kaptchafield;
}
对应的登录方法,添加:
HttpSession session = ServletActionContext.getRequest().getSession();
Integer attemptTimes = (Integer) session.getAttribute(ATTEMPT_TIMES);
if (attemptTimes == null) {
attemptTimes = 0;
}
if (attemptTimes >= ATTEMPT_TIMES_UNTIL_SHOW_CAPTCHA) {
String c = (String) session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
if (!c.equals(kaptchafield)) {
this.addActionError("验证码错误");
session.setAttribute(ATTEMPT_TIMES, attemptTimes + 1);
return INPUT;
}
}
登录失败的语句后,添加:
session.setAttribute(ATTEMPT_TIMES, attemptTimes + 1);
登录成功,添加:
session.removeAttribute(ATTEMPT_TIMES);
4. 以下是JSP中的代码:
添加:
<%
Integer attemptTimes = (Integer) request.getSession().getAttribute(UserAction.ATTEMPT_TIMES);
if (attemptTimes != null && attemptTimes >= UserAction.ATTEMPT_TIMES_UNTIL_SHOW_CAPTCHA) {
%>
<%
}
%>