本文内容来自Java实现验证码制作
Java验证码
验证码(CAPTCHA):是一种区分用户是计算机还是人的公共全自动程序
作用:可以防止恶意破解密码、刷票、论坛灌水,有效防止某个黑客对某一个特定注册用户用特定程序暴力破解方式进行不断的登录尝试
使用Servlet实现验证码
Servlet实现验证码生成图片用到的类:
1.BufferedImage
图像数据缓冲区
2.Graphics
绘制图片
3.Color
获取颜色
4.Random
生成随机数
5.ImageIO
输出图片
html页面如下:
<body>
<form action="<%=request.getContextPath() %>/servlet/LoginServlet" method="get">
验证码:<input type="text" name="checkcode" >
<img id="imagecode" alt="验证码" src="<%=request.getContextPath() %>/servlet/ImageServlet">
<a href="javascript:reloadCode()">看不清楚</a>
<input type="submit" value="提交">
</form>
<script type="text/javascript">
function reloadCode(){
//有缓存,所以添加上time
var time = new Date().getTime();
document.getElementById("imagecode").src="<%=request.getContextPath() %>/servlet/ImageServlet?d="+time;
}
</script>
</body>
如下所示:
ImageServlet
实现验证码的主要步骤如下:
1.定义BufferedImage对象
2.获取Graphics对象
3.通过Random产生随机验证码信息
4.使用Graphics绘制图片
5.记录验证码到session中
6.使用ImageIO输出图片
ImageServlet.java
代码如下:
package com.imooc;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*
* 图片Servlet
*/
public class ImageServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
BufferedImage bi = new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
Color c = new Color(200, 150, 255);
g.setColor(c);
g.fillRect(0, 0, 68, 22);
//画内容
char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
Random r = new Random();
int len = ch.length, index;
StringBuffer sb = new StringBuffer();
for(int i=0; i<4; i++){
index = r.nextInt(len);
g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt(255)));
g.drawString(ch[index]+"", i*15+3, 18);//绘制字符
//保存字符
sb.append(ch[index]);
}
//字符串保存到session中
req.getSession().setAttribute("piccode", sb.toString());
try {
ImageIO.write(bi, "JPG", resp.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
验证过程如下:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
String piccode = (String) req.getSession().getAttribute("piccode");
String checkcode = req.getParameter("checkcode").toUpperCase();
resp.setContentType("text/html;charset=utf8");
try {
PrintWriter out = resp.getWriter();
if (checkcode.equals(piccode)) {
out.println("验证码输入正确");
}else{
out.println("验证码输入错误");
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
使用Jcaptcha组件实现验证码
JCAPTCHA 表示的是 Java Completely Automated Public Test to tell Computers and Humans Apart
Jcaptcha是一个用来生成图形验证码的Java开源组件,使用起来也是非常的简单方便。与Spring组合使用,可以产生多种形式的验证码。
首先在web.xml中配置如下:
<!-- Jcaptcha -->
<servlet>
<servlet-name>jcaptcha</servlet-name>
<servlet-class>com.octo.captcha.module.servlet.image.SimpleImageCaptchaServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>submit</servlet-name>
<servlet-class>com.imooc.jcaptcha.SubmitActionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>jcaptcha</servlet-name>
<url-pattern>/jcaptcha.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>submit</servlet-name>
<url-pattern>/submit.action</url-pattern>
</servlet-mapping>
验证页面如下:
<form action="submit.action" method="post">
<img src="jcaptcha.jpg" /> <input type="text" name="japtcha" value="" />
<input type="submit"/>
</form>
验证过程如下:
public class SubmitActionServlet extends HttpServlet {
private static final long serialVersionUID = -441893585716434992L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userCaptchaResponse = request.getParameter("japtcha");
boolean captchaPassed = SimpleImageCaptchaServlet.validateResponse(request, userCaptchaResponse);
if (captchaPassed)
response.getWriter().write("captcha passed");
else {
response.getWriter().write("captcha failed");
}
response.getWriter().write("<br/><a href='index.jsp'>Try again</a>");
}
}
使用Kaptcha组件使用验证码
Kaptcha是一个非常实用的验证码工具,可以生成各种样式的验证码,它是可配置的
Kaptcha组件实现验证码步骤:
1.下载kaptcha-2.3.jar
2.将jar包导入项目
3.编写页面
4.配置web.xml
在web.xml
中配置servlet
<!-- kcaptcha -->
<servlet>
<servlet-name>kaptcha</servlet-name>
<servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>kaptcha</servlet-name>
<url-pattern>/randomcode.jpg</url-pattern>
</servlet-mapping>
使用方式如下:
<img alt="random" src="randomcode.jpg" onclick="changeR(this)" style="cursor: pointer;">
<form action="check.jsp">
<input type="text" name="r"> <input type="submit" value="submit">
</form>
<script type="text/javascript">
function changeR(node){
// 用于点击时产生不同的验证码
node.src = "randomcode.jpg?time="+new Date().getTime() ;
}
</script>
验证方式如下:
// 检查是否是正确的验证码
String k = (String) session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
String str = request.getParameter("r");
if (k.equals(str)){
out.print("true");
}
out.print(k + "---" + str);
效果如下:
配置
1.是否有边框
在servlet的init-param中,配置是否有边框,默认是有边框的
<init-param>
<description>图片边框,合法值:yes, no</description>
<param-name>kaptcha.border</param-name>
<param-value>no</param-value>
</init-param>
2.其它配置
<init-param>
<description>
边框颜色,合法值: r,g,b (and optional alpha) 或者
white,black,blue.
</description>
<param-name>kaptcha.border.color</param-name>
<param-value>black</param-value>
</init-param>
<init-param>
<description>边框厚度,合法值:>0</description>
<param-name>kaptcha.border.thickness</param-name>
<param-value>1</param-value>
</init-param>
<init-param>
<description>图片宽 200</description>
<param-name>kaptcha.image.width</param-name>
<param-value>200</param-value>
</init-param>
<init-param>
<description>图片高 50</description>
<param-name>kaptcha.image.height</param-name>
<param-value>50</param-value>
</init-param>
<init-param>
<description>图片实现类</description>
<param-name>kaptcha.producer.impl</param-name>
<param-value>
com.google.code.kaptcha.impl.DefaultKaptcha
</param-value>
</init-param>
<init-param>
<description>文本实现类</description>
<param-name>kaptcha.textproducer.impl</param-name>
<param-value>
com.google.code.kaptcha.text.impl.DefaultTextCreator
</param-value>
</init-param>
<init-param>
<description>文本集合,验证码值从此集合中获取</description>
<param-name>kaptcha.textproducer.char.string</param-name>
<param-value>1234567890</param-value>
<!--<param-value>abcde2345678gfynmnpwx</param-value>-->
<!--<param-value>慕课网教程验证码实例</param-value> -->
</init-param>
<init-param>
<description>验证码长度 5</description>
<param-name>kaptcha.textproducer.char.length</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<description>字体 Arial, Courier</description>
<param-name>kaptcha.textproducer.font.names</param-name>
<param-value>Arial, Courier</param-value>
</init-param>
<init-param>
<description>字体大小 40px.</description>
<param-name>kaptcha.textproducer.font.size</param-name>
<param-value>40</param-value>
</init-param>
<init-param>
<description>
字体颜色,合法值: r,g,b 或者 white,black,blue.
</description>
<param-name>kaptcha.textproducer.font.color</param-name>
<param-value>black</param-value>
</init-param>
<init-param>
<description>文字间隔 2</description>
<param-name>kaptcha.textproducer.char.space</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<description>干扰实现类</description>
<param-name>kaptcha.noise.impl</param-name>
<param-value>
<!-- com.google.code.kaptcha.impl.NoNoise -->
com.google.code.kaptcha.impl.DefaultNoise
</param-value>
</init-param>
<init-param>
<description>
干扰颜色,合法值: r,g,b 或者 white,black,blue.
</description>
<param-name>kaptcha.noise.color</param-name>
<param-value>black</param-value>
</init-param>
<init-param>
<description>
图片样式: 水纹com.google.code.kaptcha.impl.WaterRipple
鱼眼com.google.code.kaptcha.impl.FishEyeGimpy
阴影com.google.code.kaptcha.impl.ShadowGimpy
</description>
<param-name>kaptcha.obscurificator.impl</param-name>
<param-value>
com.google.code.kaptcha.impl.WaterRipple
</param-value>
</init-param>
<init-param>
<description>背景实现类</description>
<param-name>kaptcha.background.impl</param-name>
<param-value>
com.google.code.kaptcha.impl.DefaultBackground
</param-value>
</init-param>
<init-param>
<description>背景颜色渐变,开始颜色</description>
<param-name>kaptcha.background.clear.from</param-name>
<param-value>green</param-value>
</init-param>
<init-param>
<description>背景颜色渐变,结束颜色</description>
<param-name>kaptcha.background.clear.to</param-name>
<param-value>white</param-value>
</init-param>
<init-param>
<description>文字渲染器</description>
<param-name>kaptcha.word.impl</param-name>
<param-value>
com.google.code.kaptcha.text.impl.DefaultWordRenderer
</param-value>
</init-param>
<init-param>
<description>
session中存放验证码的key键
</description>
<param-name>kaptcha.session.key</param-name>
<param-value>KAPTCHA_SESSION_KEY</param-value>
</init-param>
<init-param>
<description>
The date the kaptcha is generated is put into the
HttpSession. This is the key value for that item in the
session.
</description>
<param-name>kaptcha.session.date</param-name>
<param-value>KAPTCHA_SESSION_DATE</param-value>
</init-param>