手把手教你繪制網頁驗證碼
阿新 • • 發佈:2018-02-19
ucc success blur script ack pattern instance javascrip ext
驗證碼
本文的中的驗證碼使用Java的awt進行繪制,樣式如下圖所示
接下來開始進行繪制。
(1)創建一個Web項目,項目的目錄結構如下
(2)創建Servlet類,繼承HttpServlet,重寫doGet和doPost方法
PicCodeServlet.java
package com.ghq.controller; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException;import java.io.PrintWriter; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;public class PicCodeServlet extends HttpServlet{ private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } @Overridepublic void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String method = request.getParameter("whichrequest"); if (method.equals("getCode")) { getCode(request, response); }else if (method.equals("checkCode")) { checkCode(request, response); } } //驗證輸入驗證碼是否正確 private void checkCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //獲取session中存儲的驗證碼 HttpSession session = request.getSession(); String syscode = (String)session.getAttribute("checkcode"); //獲取輸入的驗證碼 String inputcode = request.getParameter("code"); response.setContentType("text/html;charset=utf-8"); PrintWriter writer = response.getWriter(); //判斷驗證碼是否相同 if (!syscode.equalsIgnoreCase(inputcode)) { writer.print("驗證碼不正確"); } writer.close(); } //獲取驗證碼的方法 private void getCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Random ran = new Random(); //定義驗證碼區域的長和寬 int w = 100; int h = 30; //創建圖片, bi指向了一個可以訪問緩沖區的圖片 BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); //獲得畫筆 Graphics g = bi.getGraphics(); //創建顏色對象 參數範圍是[0-255]; Color c = new Color(200+ran.nextInt(50), 200+ran.nextInt(50), 200+ran.nextInt(50)); //存放字體對象 Font f = null; //設置畫筆顏色 g.setColor(c); //填充矩形 g.fillRect(0, 0, w, h); //存放驗證碼的StringBuffer StringBuffer stringbuffer = new StringBuffer(); //在圖片上寫驗證碼 for (int i = 0; i < 4; i++) { c = new Color(100+ran.nextInt(50), 100+ran.nextInt(50), 100+ran.nextInt(50)); f = new Font("隸書", Font.BOLD, 18); g.setFont(f); g.setColor(c); //產生大小寫字母的Unicode碼和數字隨機數 a為97 ,A為65 int lowUni = 97+ran.nextInt(26); int upUni = 65+ran.nextInt(26); int num = ran.nextInt(10); //將Unicode碼轉為字符串 String lowUnistr = String.valueOf((char)lowUni); String upUnistr = String.valueOf((char)upUni); String nstr = String.valueOf(num); //隨機產生大小寫字母或數字中的一個 String checkcode1 = ran.nextInt(2) < 0.5 ? (ran.nextInt(2) < 0.5 ? lowUnistr : upUnistr) : nstr; stringbuffer.append(checkcode1); //在圖片上寫驗證碼 g.drawString(checkcode1, (i+1)*20, 20); } //將驗證碼保存在session中以便進行校驗 HttpSession session = request.getSession(); session.setAttribute("checkcode", stringbuffer.toString()); //繪制幹擾線 for (int i = 0; i < 30; i++) { c = new Color(150+ran.nextInt(50), 150+ran.nextInt(50), 150+ran.nextInt(50)); g.setColor(c); //兩點確定一條直線 int x1 = ran.nextInt(90); int y1 = ran.nextInt(20); int x2 = ran.nextInt(20)+x1; int y2 = ran.nextInt(20)+y1; g.drawLine(x1, y1, x2, y2); } //將圖片繪制到響應的輸出流中 ImageIO.write(bi, "jpg", response.getOutputStream()); } }
(3)在web.xml中配置Servlet
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <servlet> <servlet-name>PicCodeServlet</servlet-name> <servlet-class>com.ghq.controller.PicCodeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>PicCodeServlet</servlet-name> <url-pattern>/PicCodeServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
(4)開發jsp頁面
index.jsp
<script type="text/javascript" src="<%=path %>/js/jquery-1.9.1.min.js"></script> <script type="text/javascript"> function changeCode(){ $("#img").attr("src","<%=path %>/PicCodeServlet?whichrequest=getCode&t="+Math.random()); } function judgeCode(code){ $.ajax({ type:"post", url:"<%=path%>/PicCodeServlet", data:"whichrequest=checkCode&code="+code, success:function(resText){ if (resText == "") { $("#spancode").html(resText); }else{ $("#spancode").html(resText); changeCode(); } }, error:function(){ window.location.href="<%=path%>/building.jsp"; } }); } function judgename(name){ if (name.trim().length <= 0) { $("#spanname").html("用戶名不能為空"); }else{ $("#spanname").html(""); } } function judgepass(pass){ if (pass.trim().length <= 0) { $("#spanpass").html("密碼不能為空"); }else{ $("#spanpass").html(""); } } </script> <body> <form action="" method="post"> 用戶名:<input type="text" name="username" onblur="judgename(this.value)"><span id="spanname"></span><br> 密碼:<input type="password" name="userpass" onblur="judgepass(this.value)"><span id="spanpass"></span><br> 驗證碼:<input type="text" name="checkcode" onblur="judgeCode(this.value)"> <img src="<%=path %>/PicCodeServlet?whichrequest=getCode" onclick="changeCode()" id="img"><span id="spancode"></span> </form> </body>
效果展示
點擊驗證碼的圖片,實現驗證碼的更換。
手把手教你繪制網頁驗證碼