JSP檔案做驗證碼圖片並使用
阿新 • • 發佈:2020-12-15
新建jsp檔案
<%@ page import="java.awt.*" %> <%@ page import="java.util.Random" %> <%@ page import="java.awt.image.BufferedImage" %> <%@ page import="javax.imageio.ImageIO" %> <%@ page contentType="image/jpeg;charset=UTF-8" language="java" %> <%! //產生隨機顏色 public Color getColor() { Random random = new Random(); int r = random.nextInt(256); int g = random.nextInt(256); int b = random.nextInt(256); return new Color(r, g, b); } //產生驗證碼數值 public String getNumber() { int number = (int) (Math.random() * 9000) + 1000; return String.valueOf(number); } %> <% //禁止快取,防止驗證碼過期 response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-control", "no-cache"); response.setHeader("Expires", "0"); //繪製驗證碼 BufferedImage bufferedImage = new BufferedImage(80, 30, BufferedImage.TYPE_INT_BGR); //畫筆 Graphics graphics = bufferedImage.getGraphics(); graphics.fillRect(0, 0, 80, 30); //繪製干擾線條 for (int i = 0; i < 60; i++) { Random random = new Random(); //線條開始位置 int xBegin = random.nextInt(80); int yBegin = random.nextInt(30); //線條結束位置 int xEnd = random.nextInt(xBegin + 15); int yEnd = random.nextInt(yBegin + 15); //線條顏色 graphics.setColor(getColor()); //線條位置 graphics.drawLine(xBegin, yBegin, xEnd, yEnd); } graphics.setFont(new Font("微軟雅黑",Font.BOLD,20)); //繪製驗證碼 //驗證碼的顏色 Black graphics.setColor(Color.BLACK); //獲取隨機四位數的數值 String checkNumber = getNumber(); StringBuffer stringBuffer = new StringBuffer(); //把每個數遍歷出來,在中間新增空格更好看 for(int i=0;i<checkNumber.length();i++){ stringBuffer.append(checkNumber.charAt(i)+" "); } //驗證碼在圖片中的開始位置 graphics.drawString(stringBuffer.toString(),10,21); //將驗證碼的值放到session中,和使用者輸入的比較 session.setAttribute("checkNumber",checkNumber); //產生圖片 ImageIO.write(bufferedImage,"jpeg",response.getOutputStream()); //關閉操作 out.clear(); out = pageContext.pushBody(); %>
使用
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title></title> <style> </style> <script src="js/jquery-3.5.1.min.js"></script> <script> function reloadimage() { //重新整理驗證碼圖片 $($("img")[0]).attr("src", "getImage.jsp?t=" + new Date().getTime()); } $(function () { //失去焦點觸發事件 $("#checkn").blur(function () { //獲取文字框的數值 var checknumber = $("#checkn").val(); //呼叫ajax方法 $.ajax({ method: "post", url: "checknumber", data: {"number": checknumber} }).done(function (cc) { $("#test").text(cc); }); }); }); </script> </head> <body> <input type="text" name="checkNumber" id="checkn"/> <a href="javascript:reloadimage();"><img src="getImage.jsp"/></a> <div id="test"></div> </body> </html>