首页 > 代码库 > JAVAWeb 使用HTML页面创建验证码
JAVAWeb 使用HTML页面创建验证码
实际的项目中登录中需要用到验证码,接下来是我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="http://www.mamicode.com/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 + random44 .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 %>
JAVAWeb 使用HTML页面创建验证码
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。