实际的项目中登录中需要用到验证码,接下来是我Web项目中所用到验证码技术
index.html
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 2 <html> 3 <head> 4 <title>index.html</title> 5 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 6 <meta http-equiv="description" content="this is my page"> 7 <meta http-equiv="content-type" content="text/html; charset=UTF-8"> 8 <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> 9 </head> 10 <script type="text/javascript"> 11 function clk_image(){ 12 var img = document.getElementById("sCodeImg"); 13 img.src = "Validate.jsp?" + Math.random(); 14 } 15 </script> 16 <body> 17 <input type="text" name="code" id="code"/> 18 <img id="sCodeImg" alt="请输入验证码" src="Validate.jsp?,Math.random();" onclick="return clk_image();" width="65" height="25"> 19 </body> 20 </html>
Validate.jsp
1 <%@ page contentType="text ml;charset=UTF-8" language="java"%> 2 <%@ page import="java.awt.*"%> 3 <%@ page import="java.awt.image.*"%> 4 <%@ page import="java.util.*"%> 5 <%@ page import="javax.imageio.*"%> 6 7 <%!Color getRandColor(int fc, int bc) { 8 Random random = new Random(); 9 if (fc > 255) 10 fc = 255; 11 if (bc > 255) 12 bc = 255; 13 int r = fc + random.nextInt(bc - fc); 14 int g = fc + random.nextInt(bc - fc); 15 int b = fc + random.nextInt(bc - fc); 16 return new Color(r, g, b); 17 }%> 18 <% 19 response.setHeader("Pragma", "No-cache"); 20 response.setHeader("Cache-Control", "no-cache"); 21 response.setDateHeader("Expires", 0); 22 int width = 60; 23 int height = 20; 24 BufferedImage image = new BufferedImage(width, height, 25 BufferedImage.TYPE_INT_RGB); 26 Graphics g = image.getGraphics(); 27 Random random = new Random(); 28 g.setColor(getRandColor(200, 250)); 29 g.fillRect(0, 0, width, height); 30 g.setFont(new Font("Times New Roman", Font.PLAIN, 18)); 31 g.setColor(getRandColor(160, 200)); 32 for (int i = 0; i < 155; i++) { 33 int x = random.nextInt(width); 34 int y = random.nextInt(height); 35 int x1 = random.nextInt(12); 36 int y1 = random.nextInt(12); 37 g.drawLine(x, y, x + x1, y + y1); 38 } 39 String sRand = ""; 40 for (int i = 0; i < 4; i++) { 41 String rand = String.valueOf(random.nextInt(10)); 42 sRand += rand; 43 g.setColor(new Color(20 + random.nextInt(110), 20 + random 44 .nextInt(110), 20 + random.nextInt(110))); 45 g.drawString(rand, 13 * i + 6, 16); 46 } 47 // 将验证码保存到session中,登录验证时再取出和用户输入的进行比较 48 session.setAttribute("checkCode", sRand); 49 g.dispose(); 50 ImageIO.write(image, "JPEG", response.getOutputStream()); 51 out.clear(); 52 out = pageContext.pushBody(); 53 %>
时间: 2024-11-14 11:58:30