定义一个 Servlet 用来在内存中生成 二维码图片,并向浏览器页面输出。
1 import javax.imageio.ImageIO; 2 import javax.servlet.ServletException; 3 import javax.servlet.annotation.WebServlet; 4 import javax.servlet.http.HttpServlet; 5 import javax.servlet.http.HttpServletRequest; 6 import javax.servlet.http.HttpServletResponse; 7 import java.awt.*; 8 import java.awt.image.BufferedImage; 9 import java.io.IOException; 10 import java.util.Random; 11 12 @WebServlet("/checkCodeServlet") 13 public class CheckCodeServlet extends HttpServlet { 14 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 15 16 // 定义图片的宽高 17 int width = 100; 18 int height = 50; 19 20 // 1 创建对象,在内存中生成图片(验证码图片对象) 21 BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR); 22 23 // 2 修饰图片 24 // 2.1 填充背景色 25 Graphics g = image.getGraphics(); //获取画笔对象 26 g.setColor(Color.pink); // 设置画笔颜色 27 g.fillRect(0,0,width,height); // 绘制一个矩形,给定坐标与宽高 28 29 // 2.2 画边框 30 g.setColor(Color.blue); // 设置画笔颜色 31 g.drawRect(0,0,width-1,height-1); // 给图像绘制边框 32 33 String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789"; 34 //生成随机角标 35 Random ran = new Random(); 36 37 for (int i = 1; i <= 4; i++) { 38 int index = ran.nextInt(str.length()); 39 //获取字符 40 char ch = str.charAt(index);//随机字符 41 //2.3写验证码 42 g.drawString(ch+"",width/5*i,height/2); 43 } 44 45 //2.4画干扰线 46 g.setColor(Color.GREEN); 47 48 // 随机生成坐标点 49 50 for (int i = 0; i < 6; i++) { 51 int x1 = ran.nextInt(width); 52 int x2 = ran.nextInt(width); 53 54 int y1 = ran.nextInt(height); 55 int y2 = ran.nextInt(height); 56 g.drawLine(x1,y1,x2,y2); // 画干扰线 57 } 58 59 60 // 3 将图片输出到页面展示:通过response 的 字符流,将图片输出到浏览器上 61 ImageIO.write(image,"jpg",response.getOutputStream()); 62 } 63 64 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 65 this.doPost(request, response); 66 } 67 }
定义一个web页面,用来查看验证码,可以刷新验证码。
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>验证码</title> 6 7 <script> 8 /* 9 点击超链接或者图片,需要换一张 10 1.给超链接和图片绑定单击事件 11 12 2.重新设置图片的src属性值 13 14 */ 15 window.onload = function(){ 16 //1.获取图片对象 17 var img = document.getElementById("checkCode"); 18 //2.绑定单击事件 19 img.onclick = function(){ 20 //加时间戳 21 var date = new Date().getTime(); 22 23 img.src = "/web/checkCodeServlet?"+date; 24 } 25 26 // 获取超链接对象 27 var a = document.getElementById("change"); 28 29 a.onclick = img.onclick(); 30 31 } 32 33 34 </script> 35 36 37 </head> 38 <body> 39 40 41 <img id="checkCode" src="/web/checkCodeServlet" /> 42 43 <a id="change" href="javascript:;">看不清换一张?</a> 44 45 </body> 46 </html>
效果图
原文地址:https://www.cnblogs.com/niujifei/p/11620996.html
时间: 2024-10-10 16:07:12