目的:生成一个图片验证码,点击图片或者右侧链接可以切换图片。
JSP页面:
<%--
Created by IntelliJ IDEA.
User: FANG2
Date: 2018/9/16
Time: 18:34
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>验证码</title>
<script>
/*
分析:
点击超链接或者图片,需要换一张
1.给超链接和图片绑定单击事件
2.重新设置图片的src属性值
*/
window.onload=function () {
var img = document.getElementById("CheckCode");
//1.给图片绑定单击事件,单击图片更换
img.onclick = function(){
//加时间戳
var date = new Date().getTime();
img.src = "/day15/checkCodeServlet?"+date;
}
var amg = document.getElementById("change");
//2.给超链接绑定单击事件,单击超链接更换图片
amg.onclick = function(){
//加时间戳
var img = document.getElementById("CheckCode");
var date = new Date().getTime();
img.src = "/day15/checkCodeServlet?"+date;
}
}
</script>
</head>
<body>
<img id="CheckCode" src="/day15/checkCodeServlet"/>
<a id="change" href="">看不起,换一张?</a>
</body>
</html>
后台代码:
package Demo;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
/**
* 图片验证码
*/
@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int width = 100;
int height = 50;
//1.创建对象,在内存中(验证图片对象)
BufferedImage image = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB );
//2.美化图片
//2.1 填充背景色
Graphics graphics = image.getGraphics(); //画笔对象
graphics.setColor( Color.PINK ); //设置画笔颜色
graphics.fillRect( 0, 0, width, height );
//2.2 画边框
graphics.setColor( Color.BLUE );
graphics.drawRect( 0, 0, width - 1, height - 1 );
//2.3 生成验证码内容
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789";
//生成随机角标
Random ran = new Random();
for (int i = 0; i < 4; i++) {
int index = ran.nextInt( str.length() );
char ch = str.charAt( index );
graphics.drawString( ch + " ", width / 5 * i, height / 2 );
}
//2.4 画干扰线
graphics.setColor( Color.GREEN );
for (int i = 0; i < 10; i++) {
int x1 = ran.nextInt( width );
int x2 = ran.nextInt( width );
int y1 = ran.nextInt( height );
int y2 = ran.nextInt( height );
graphics.drawLine( x1, y1, x2, y2 );
}
//3.将图片响应到页面展示
ImageIO.write( image, "jpg", response.getOutputStream() );
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost( request, response );
}
}
效果图: