java web開發(fā)之servlet圖形驗(yàn)證碼功能的實(shí)現(xiàn)
一 驗(yàn)證碼的由來
在web項(xiàng)目開發(fā)中,為了防止部分人使用自動工具(如:自動注冊機(jī))等進(jìn)行批量的數(shù)據(jù)處理,在不同的功能節(jié)點(diǎn)部分,添加了驗(yàn)證碼進(jìn)行驗(yàn)證,達(dá)到對自動軟件的屏蔽效果
最經(jīng)典的應(yīng)用如:網(wǎng)站注冊圖形驗(yàn)證碼;接下來,通過java技術(shù),結(jié)合servlet實(shí)現(xiàn)一個網(wǎng)站注冊需要的圖形驗(yàn)證碼程序,提供大家參考。
二 實(shí)現(xiàn)注冊頁面圖形驗(yàn)證碼效果
1. 創(chuàng)建web項(xiàng)目:java_servlet_verifyimg
2. 創(chuàng)建自動生成圖形驗(yàn)證碼的控制器——VerifyImgServlet
package com.phome.util; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGImageEncoder; public class VerifyImgServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; // 設(shè)置隨機(jī)字符字典。其中不包含0,o,1,I等難以辨認(rèn)的字符 public static final char[] CHARS = { '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; public static Random random = new Random(); // 隨機(jī)數(shù)對象 public static String getRandomString() { StringBuffer buffer = new StringBuffer(); // 字符串緩存 for (int i = 0; i < 6; i++) // 六次循環(huán)獲取字符 { buffer.append(CHARS[random.nextInt(CHARS.length)]); // 每次隨機(jī)取一個字符 } return buffer.toString(); } public static Color getRandomColor() { return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)); } public static Color getReverseColor(Color c) { return new Color(255 - c.getRed(), 255 - c.getGreen(), 255 - c.getBlue()); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("image/jpeg"); // 設(shè)置輸出類型 不可省略 String randomString = getRandomString(); // 調(diào)用生成隨機(jī)字符串方法獲取并接受隨機(jī)字符串 request.getSession(true).setAttribute("randomString", randomString); // 將字符串存儲到Session中 int width = 100; // 圖片寬度 int height = 30; // 圖片高度 Color color = getRandomColor(); // 獲取隨機(jī)顏色 用于背景色 Color reverse = getReverseColor(color); // 反色 用于前景色 BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 創(chuàng)建一個彩色圖片 Graphics2D g = bi.createGraphics(); // 獲取繪圖對象 g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 16)); // 設(shè)置字體 g.setColor(color); // 設(shè)置顏色 g.fillRect(0, 0, width, height); // 繪制背景 g.setColor(reverse); // 設(shè)置顏色 g.drawString(randomString, 18, 20); // 繪制隨機(jī)字符 for (int i = 0, n = random.nextInt(100); i < n; i++) // 畫最多一百個噪音點(diǎn) { g.drawRect(random.nextInt(width), random.nextInt(height), 1, 1); // 隨機(jī)噪音點(diǎn) } ServletOutputStream out = response.getOutputStream(); // 好像是獲取輸出流 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); // 編碼器 encoder.encode(bi); // 對圖片進(jìn)行編碼 out.flush(); // 輸出到客戶端 } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
3. 創(chuàng)建注冊控制器——RegistServlet
package com.phome.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * 注冊控制器 * @author ZuoYi * */ public class RegistServlet extends HttpServlet{ /** * */ private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 從session中獲取注冊隨機(jī)驗(yàn)證碼 HttpSession session = req.getSession(); String randomString = (String)session.getAttribute("randomString"); // 獲取用戶輸入驗(yàn)證碼 String inputRandomString = req.getParameter("randomStr"); // 判斷驗(yàn)證碼通過,模擬進(jìn)行注冊 if (randomString.equals(inputRandomString)) { req.setAttribute("resinfo", "恭喜!注冊成功!"); } else { req.setAttribute("resinfo", "驗(yàn)證碼輸入有誤,請檢查后重新進(jìn)行注冊!"); } // 注冊成功或者失敗,都跳轉(zhuǎn)到result.jsp頁面,查看注冊結(jié)果。。。 req.getRequestDispatcher("result.jsp").forward(req, resp); } }
4. 配置servlet
<?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" 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"> <display-name>simg</display-name> <!-- 配置用戶注冊servlet --> <servlet> <servlet-name>registservlet</servlet-name> <servlet-class>com.phome.servlet.RegistServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>registservlet</servlet-name> <url-pattern>/regist.action</url-pattern> </servlet-mapping> <!-- 配置圖形驗(yàn)證碼servlet --> <servlet> <servlet-name>verifyimg</servlet-name> <servlet-class>com.phome.servlet.VerifyImgServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>verifyimg</servlet-name> <url-pattern>/verifyimg.action</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>
5. 創(chuàng)建注冊視圖測試頁面——regist.jsp
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>" rel="external nofollow" rel="external nofollow" > <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css" rel="external nofollow" rel="external nofollow" > --> </head> <body> <form action="${pageContext.request.contextPath}/regist.action" method="post"> 用戶名:<input type="text" name="username"/> <br /> 密碼:<input type="text" name="password"/> <br /> 請輸入驗(yàn)證碼進(jìn)行注冊: <img src="${pageContext.request.contextPath }/verifyimg.action"/> <input type="text" name="randomStr"/> <br /> <input type="submit" value="regist"/> </form> </body> </html>
5.1 創(chuàng)建注冊結(jié)果頁面——result.jsp
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>" rel="external nofollow" rel="external nofollow" > <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css" rel="external nofollow" rel="external nofollow" > --> </head> <body> ${requestScope.resinfo } </body> </html>
6.測試
(1)a.打開瀏覽器,輸入測試地址:http://localhost:8080/java_servlet_verifyimg;出現(xiàn)如下圖所示頁面
b.輸入注冊賬號、密碼和驗(yàn)證碼后點(diǎn)擊regist提交
c.測試結(jié)果,跳轉(zhuǎn)會注冊頁面,提示注冊成功
(2)打開注冊頁面
輸入錯誤注冊碼
測試結(jié)果頁面
over!
更多關(guān)于驗(yàn)證碼的文章請點(diǎn)擊查看:《java驗(yàn)證碼》
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java數(shù)據(jù)結(jié)構(gòu)常見幾大排序梳理
Java常見的排序算法有:直接插入排序、希爾排序、選擇排序、冒泡排序、歸并排序、快速排序、堆排序等。本文詳解介紹它們的實(shí)現(xiàn)以及圖解,需要的可以參考一下2022-03-03如何使用Idea中的 Deployment 實(shí)現(xiàn)打包自動部署
這篇文章主要介紹了使用Idea中的 Deployment 實(shí)現(xiàn)打包自動部署,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-08-08如何使用JCTools實(shí)現(xiàn)Java并發(fā)程序
這篇文章主要介紹了如何使用JCTools實(shí)現(xiàn)Java并發(fā)程序,幫助大家更好的理解和學(xué)習(xí)使用Java,感興趣的朋友可以了解下2021-03-03Debian 7 和 Debian 8 用戶安裝 Java 8的方法
Oracle Java 8 穩(wěn)定版本近期已發(fā)布,有很多新的特征變化。其中,有功能的程序支持通過“Lambda項(xiàng)目 ”,收到了一些安全更新和界面改進(jìn)上的bug修復(fù),使得開發(fā)人員的工作更容易。2014-03-03Netty + ZooKeeper 實(shí)現(xiàn)簡單的服務(wù)注冊與發(fā)現(xiàn)
服務(wù)注冊和發(fā)現(xiàn)一直是分布式的核心組件。本文介紹了借助 ZooKeeper 做注冊中心,如何實(shí)現(xiàn)一個簡單的服務(wù)注冊和發(fā)現(xiàn)。,需要的朋友可以參考下2019-06-06Java中的InputStreamReader和OutputStreamWriter源碼分析_動力節(jié)點(diǎn)Java學(xué)院整理
本文通過示例代碼給大家解析了Java中的InputStreamReader和OutputStreamWriter知識,需要的的朋友參考下吧2017-05-05