验证码
1.1.1
PicCodeServlet代码
package
com.itheima.servlet;
import
java.awt.Color;
import
java.awt.Font;
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;
public
class
PicCodeServlet
extends
HttpServlet {
//
创建随机类
private
Random
random
=
new
Random();
/**
* 1)
创建方法:随机得到一种颜色
*/
private
Color getColor() {
int
r =
random
.nextInt(256);
//
红
int
g =
random
.nextInt(256);
//
绿
int
b =
random
.nextInt(256);
//
蓝
return
new
Color(r, g, b);
}
public
void
doGet(HttpServletRequest request, HttpServletResponse response)
throws
ServletException, IOException {
// 2)
创建缓存图片:指定宽
width=90
,高
height=30
int
width = 90, height = 30;
BufferedImage img =
new
BufferedImage(width, height, BufferedImage.
TYPE_INT_RGB
);
// 3)
获取画笔对象
Graphics graphics = img.getGraphics();
// 4)
设置画笔颜色,并且填充矩形区域
graphics.setColor(Color.
WHITE
);
graphics.fillRect(0, 0, width, height);
// 5)
从字符数组中随机得到字符
char
[] arr = {
'A'
,
'B'
,
'C'
,
'D'
,
'N'
,
'E'
,
'W'
,
'b'
,
'o'
,
'y'
,
'1'
,
'2'
,
'3'
,
'4'
};
for
(
int
i = 0; i < 4; i++) {
int
index =
random
.nextInt(arr.
length
);
char
c = arr[index];
//
设置颜色
graphics.setColor(getColor());
// 6)
设置字体,大小为
18
,设置字的颜色随机
graphics.setFont(
new
Font(Font.
DIALOG
, Font.
BOLD
+ Font.
ITALIC
, 18));
// 7)
将每个字符画到图片,位置:
5+(i*20), 20
graphics.drawString(String.
valueOf
(c), 5 + (i * 20), 20);
}
// 8)
画干扰线
10
条线,线的位置是随机的,
x
范围在
width
之中,
y
的范围在
height
之中。
for
(
int
i = 0; i < 7; i++) {
int
x1 =
random
.nextInt(width);
int
y1 =
random
.nextInt(height);
int
x2 =
random
.nextInt(width);
int
y2 =
random
.nextInt(height);
//
得到一种颜色
graphics.setColor(getColor());
graphics.drawLine(x1, y1, x2, y2);
}
// 9)
将缓存的图片输出到响应输出流中
ImageIO.
write
(img,
"jpg"
, response.getOutputStream());
}
public
void
doPost(HttpServletRequest request, HttpServletResponse response)
throws
ServletException, IOException {
doGet(request, response);
}
}
1.1.1
Servlet的配置
<
servlet
>
<
servlet-name
>
PicCodeServlet
</
servlet-name
>
<
servlet-class
>
com.itheima.servlet.PicCodeServlet
</
servlet-class
>
</
servlet
>
<
servlet-mapping
>
<
servlet-name
>
PicCodeServlet
</
servlet-name
>
<
url-pattern
>
/vcode
</
url-pattern
>
</
servlet-mapping
>
1.1.2
验证页面
<h3>
用户登录
</h3>
<form action="login" method="post">
用户名:
<input type="text" name="user"/><br/>
密码:
<input type="password" name="pwd"><br/>
验证码:
<input type="text" name="code" ><img alt="
验证码
" src="vcode" οnclick="refreshCode()" id="vcode"> <br/>
<input type="submit" value="
登录
">
</form>
<script type="text/javascript">
function refreshCode() {
//
随机产生一个参数,通过
?
传递给图片
src
属性,点击的时候,让浏览器认为地址栏参数发生变化,就会重新访问服务器
document.getElementById("vcode").src = "vcode?t=" + Math.random();
}
</script>