【验证码输出】利用时间戳实现永远不重复的刷新
2021/11/26 23:10:46
本文主要是介绍【验证码输出】利用时间戳实现永远不重复的刷新,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
package web.response; import javax.imageio.ImageIO; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; @WebServlet(name = "CheckCodeServlet1", value = "/CheckCodeServlet1") public class CheckCodeServlet1 extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request,response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 验证码的实现 // 1.获取验证码图片对象,设置图片大小 int width = 200; int height = 100; BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); // 2.获取画笔对象 Graphics graphics = bufferedImage.getGraphics(); // 3.填充背景色,包括背景颜色,填充或者画 graphics.setColor(Color.cyan); graphics.fillRect(0,0,width,height); // 4.画边框 graphics.setColor(Color.orange); graphics.drawRect(0,0,width-1,height-1); // 5.写验证码 String str = "QWERTYUIOPASDFGHJKLZXCVBNMqazwsxedcrfvtgbyhnujmikolp0123456789"; // 随机生成验证码 Random random = new Random(); for (int i = 1; i < 5; i++) { // 随机索引值 int nextInt = random.nextInt(str.length()); char charAt = str.charAt(nextInt); // 写验证码 graphics.drawString(charAt+"",width/5*i,height/2); } // 画干扰线 graphics.setColor(Color.red); // 随机生成坐标点 for (int i = 0; i < 10; i++) { int x1 = random.nextInt(width); int x2 = random.nextInt(width); int y1 = random.nextInt(height); int y2 = random.nextInt(height); graphics.drawLine(x1,y1,x2,y2); } // 输出验证码图片到页面 ImageIO.write(bufferedImage,"jpg",response.getOutputStream()); } }
html文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>注册界面</title> <script> window.onload = function (){ //获取图片对象 var img = document.getElementById("checkcode"); // 绑定单击时间 img.onclick =function (){ // 加时间戳 var data = new Date().getTime(); img.src = "CheckCodeServlet1"+data; } } </script> </head> <body> <img id="checkcode" src="CheckCodeServlet1" ><br> <a href="" id="change">看不清,换一张</a> </body> </html>
这篇关于【验证码输出】利用时间戳实现永远不重复的刷新的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-26结对编程到底难不难?答案在这里
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?
- 2024-05-31全网首发第二弹!软考2024年5月《软件设计师》真题+解析+答案!(11-20题)
- 2024-05-31全网首发!软考2024年5月《软件设计师》真题+解析+答案!(21-30题)