JavaWeb实现验证码

时间:2021-05-22 13:11:06

JavaWeb实现验证码

创建一个ImageServlet类,这个类实现了输出验证码的功能。具体代码如下:

ImageServlet:


@WebServlet("/ImageServlet")
public class ImageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

public ImageServlet() {
super();

}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("image/jpg;charset=utf-8");

//在内存中创建一个图片对象,宽度120,高度30
int width = 120;
int height = 30;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//获取一个绘制的对象
Graphics g = image.getGraphics();
//设置颜色为蓝色
g.setColor(Color.BLUE);
//画一个蓝色矩形
g.drawRect(0, 0, width, height);
//设置颜色灰色
g.setColor(Color.GRAY);
//给图片进行填充灰色
g.fillRect(2, 2, width-4, height-4);
//设置颜色为红色
g.setColor(Color.RED);
//设置字体为黑体,大小20,字体样式加粗、斜体
g.setFont(new Font("黑体", Font.BOLD|Font.ITALIC, 20));

Random random = new Random();
int position = 10;
//随机绘制4个数字
for (int i = 0; i < 4; i++) {
String content= Integer.toString(random.nextInt(10));
//绘制数字
g.drawString(content,position, 20);
//排列数字的位置
position+=30;
}
//绘制8条干扰线
for (int i = 0; i < 8; i++) {
g.setColor(Color.DARK_GRAY);
//绘制深灰色的干扰线
g.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height));
}
//输出图片
ImageIO.write(image ,"jpg", response.getOutputStream());
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

doGet(request, response);
}

}

在web.xml设置ImageServlet配置

<servlet>
<servlet-name>ImageServlet</servlet-name>
<servlet-class>com.yundoku.ImageServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>ImageServlet</servlet-name>
<url-pattern>/image</url-pattern>
</servlet-mapping>

image.html代码

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function changeImage() {
var img = document.getElementsByTagName("img")[0];
img.src="/TomcatDemo/image?time="+new Date().getTime();//这个目的是防止缓存不刷新验证码
}
</script>
</head>
<body>
<form>
<table>
<tr align="left" height="30">
<td>用户名:</td>
<td><input type="text" name="username"/></td>
</tr >
<tr align="left" height="30">
<td>密码:</td>
<td><input type="password" name="password"/></td>
</tr>
<tr align="left" height="30">
<td>验证码:</td>
<td><input type="text" name="username"/>&nbsp;&nbsp;<img src="/TomcatDemo/image" onclick="changeImage()"/>&nbsp;<a href="javascript:changeImage()" >看不清,换一张</a></td>
</tr>
<tr height="24"><td colspan="2"><input type="submit" value="提交"/></td></tr>
</table>
</form>
</body>
</html>

效果如图所示:

JavaWeb实现验证码