验证码

以下是涉及修改的代码:
1. pom.xml 引入kaptcha
<dependency>
<groupId>com.google.code</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
2. web.xml 添加servlet
<servlet>
<servlet-name>Kaptcha</servlet-name>
<servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
<!--
For a complete list of Init Parameters, please see:
http://code.google.com/p/kaptcha/wiki/ConfigParameters
-->
<init-param>
<param-name>kaptcha.image.width</param-name>
<param-value>150</param-value>
</init-param>
<init-param>
<param-name>kaptcha.image.height</param-name>
<param-value>50</param-value>
</init-param>
<init-param>
<param-name>kaptcha.textproducer.font.color</param-name>
<param-value>black</param-value>
</init-param>
<init-param>
<param-name>kaptcha.textproducer.char.space</param-name>
<param-value>1</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Kaptcha</servlet-name>
<url-pattern>/Kaptcha.jpg</url-pattern>
</servlet-mapping>
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) {
%>
<div>
<label class="text">验证码:</label>
<input type="text" name="kaptchafield" class="textbox340" style="width: 180px; vertical-align:middle;" value="" />
<img src="Kaptcha.jpg" style="vertical-align:middle;"/>
</div>
<%
}
%>

你可能感兴趣的:(jsp)