多说无益,直接上代码
package Request;
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("/responseDemo12")
public class ResponseDemo12 extends HttpServlet {
int width = 100;
int height = 50;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1、创建一对象,在内存中画图(验证码的图片对象)
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
// 2、美化图片
// 2.1、填充背景色
Graphics g = image.getGraphics();
g.setColor(Color.pink);
g.fillRect(0,0,width,height);
// 2.2、话边框
g.setColor(Color.blue);
g.drawRect(0,0,width-1,height-1);
// 2.3 写验证码
String str = "abcdefghijklmopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
// 创建一个随机类
Random random = new Random();
// 获取字符
int x = 10;
for(int i=0;i<4;i++) {
int index = random.nextInt(str.length());
String ch = str.charAt(index)+"";
g.drawString(ch,width/5*(i+1),height/2);
x+=5;
}
// 2.4画干扰线
for(int i=0;i<10;i++) {
int point1 = random.nextInt(width);
int point2 = random.nextInt(width);
int point3 = random.nextInt(width);
int point4 = random.nextInt(width);
g.setColor(Color.green);
g.drawLine(point1,point2,point3,point4);
}
// 3、将图片输出到页面展示
ImageIO.write(image, "jpg", resp.getOutputStream());
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
}
点击切换,还是直接上代码
**注意解决浏览器动态缓存图片的问题**
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<script>
/*
点击超链接或者图片,换一张
1、给超连接和图片绑定单击事件
2、重新设置图片的src属性值
*/
window.onload = function () {
//1、获取图片而对象
var img = document.getElementById("checkCode");
//2、给image绑定单击事
img.onclick = function () {
//加事件戳
var date = new Date().getTime();
img.src="/responseDemo12?"+date; //解决浏览本地缓存,图片不切换
}
var change = document.getElementById("change");
change.onclick = function () {
var date = new Date().getTime();
img.src="/responseDemo12?"+date;
}
}
</script>
<body>
<img id="checkCode" src="/responseDemo12" />
<a id="change" href="">看不清换一张</a>
</body>
</html>
效果图
此代码根据视频所学进行记录,只了解大致逻辑,具体美观代码可上网查看
禁止转载,若有侵权,将进行追究
若侵权他人,请联系我,进行删除,谢谢
来自一个写代码的小哥哥
若有错误,请联系我,进行修改
写代码,挣钱,努力,挣钱,run,run,run