kaptcha文件上传使用步骤
1.web-inf的lib中导入kaptcha-2.3.2;
2.在web.xml中配置如下servlet:
<servlet>
<servlet-name>Kaptcha</servlet-name>
<servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
<init-param>
<param-name>kaptcha.image.width</param-name>
<param-value>85</param-value>
</init-param>
<init-param>
<param-name>kaptcha.image.height</param-name>
<param-value>40</param-value>
</init-param>
<init-param>
<param-name>kaptcha.textproducer.char.length</param-name>
<param-value>4</param-value>
</init-param>
<init-param>
<param-name>kaptcha.textproducer.font.size</param-name>
<param-value>34</param-value>
</init-param>
<init-param>
<param-name>kaptcha.textproducer.font.names</param-name>
<param-value>宋体</param-value>
</init-param>
<init-param>
<param-name>kaptcha.obscurificator.impl</param-name>
<param-value>com.google.code.kaptcha.impl.ShadowGimpy</param-value>
</init-param>
<init-param>
<param-name>kaptcha.noise.impl</param-name>
<param-value>com.google.code.kaptcha.impl.NoNoise </param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Kaptcha</servlet-name>
<url-pattern>/kaptcha</url-pattern>
</servlet-mapping>
3.在login.jsp页面中编写
<li>验证码Captcha:</li>
<li><input type="text" name="code" class="inptext2" >
<img id="code" src="${pageContext.request.contextPath}/kaptcha"/ onclick="changeImg()">
function changeImg() {
document.getElementById("code").src = "${pageContext.request.contextPath}/kaptcha?"+Math.random();
}
4.测试访问:http://localhost:8080/Yanzhengma/kaptcha;
5.在servlet中代码如下:
String code = request.getParameter("code");
String imgCode = request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY).toString();
if(!code.trim().equals(imgCode.trim())) {
out.print("<script>alert('验证码输入错误');</script>");
return "redirect:LoginServlet?method=initLogin";
} else{
User user = userDao.login(new User(username, MD5.md5Encode(password)));
if(null!=user) {
request.getSession().setAttribute("user", user);
return "redirect:InitJspServlet?method=initIndex";
} else {
out.print("<script>alert('用户名输入错误');</script>");
return "redirect:LoginServlet?method=initLogin";
}
}