JAVA驗(yàn)證碼工具實(shí)例代碼
工具類:
package com.lhy.web.servlet; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Random; import javax.imageio.ImageIO; public class VerifyCode { private int w = 70;//圖片長 private int h = 35;//圖片寬 private Random r = new Random();//Random類 生成隨機(jī)數(shù) // 列舉驗(yàn)證圖片中驗(yàn)證碼的字體類型 //{"宋體", "華文楷體", "黑體", "華文新魏", "華文隸書", "微軟雅黑", "楷體_GB2312"} private String[] fontNames = {"宋體", "華文楷體", "黑體", "微軟雅黑", "楷體_GB2312"}; // 驗(yàn)證碼可選字符 private String codes="23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ"; // 背景色 private Color bgColor = new Color(255, 255, 255); // 驗(yàn)證碼上的文本 private String text ; // 生成隨機(jī)的顏色 private Color randomColor () { int red = r.nextInt(150); int green = r.nextInt(150); int blue = r.nextInt(150); return new Color(red, green, blue); } // 生成隨機(jī)的字體 private Font randomFont () { int index = r.nextInt(fontNames.length); String fontName = fontNames[index];//生成隨機(jī)的字體名稱 int style = r.nextInt(4);//生成隨機(jī)的樣式, 0(無樣式), 1(粗體), 2(斜體), 3(粗體+斜體) int size = r.nextInt(5) + 24; //生成隨機(jī)字號(hào), 24 ~ 28 return new Font(fontName, style, size); } // 畫干擾線 private void drawLine (BufferedImage image) { int num = 3;//一共畫3條 Graphics2D g2 = (Graphics2D)image.getGraphics(); for(int i = 0; i < num; i++) {//生成兩個(gè)點(diǎn)的坐標(biāo),即4個(gè)值 int x1 = r.nextInt(w); int y1 = r.nextInt(h); int x2 = r.nextInt(w); int y2 = r.nextInt(h); g2.setStroke(new BasicStroke(1.5F)); g2.setColor(Color.BLUE); //干擾線是藍(lán)色 g2.drawLine(x1, y1, x2, y2);//畫線 } } // 隨機(jī)生成一個(gè)字符 private char randomChar () { int index = r.nextInt(codes.length()); return codes.charAt(index); } // 創(chuàng)建BufferedImage private BufferedImage createImage () { //寬,高,圖片的類型 BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = (Graphics2D)image.getGraphics(); g2.setColor(this.bgColor); g2.fillRect(0, 0, w, h); return image; } // 返回驗(yàn)證碼圖片上的文本 public String getText () { return text; } // 保存圖片到指定的輸出流 public static void output (BufferedImage image, OutputStream out) throws IOException { ImageIO.write(image, "JPEG", out); } // 調(diào)用這個(gè)方法得到驗(yàn)證碼 public BufferedImage getImage () { BufferedImage image = createImage();//創(chuàng)建圖片緩沖區(qū) Graphics2D g2 = (Graphics2D)image.getGraphics();//得到繪制環(huán)境 StringBuilder sb = new StringBuilder();//用來裝載生成的驗(yàn)證碼文本 // 向圖片中畫4個(gè)字符 for(int i = 0; i < 4; i++) {//循環(huán)四次,每次生成一個(gè)字符 String s = randomChar() + "";//隨機(jī)生成一個(gè)字母 sb.append(s); //把字母添加到sb中 float x = i * 1.0F * w / 4; //設(shè)置當(dāng)前字符的x軸坐標(biāo) g2.setFont(randomFont()); //設(shè)置隨機(jī)字體 g2.setColor(randomColor()); //設(shè)置隨機(jī)顏色 g2.drawString(s, x, h-5); //畫圖 } this.text = sb.toString(); //把生成的字符串賦給了this.text drawLine(image); //添加干擾線 return image; } public static void main(String[] args) throws FileNotFoundException, IOException { VerifyCode vc = new VerifyCode();//創(chuàng)建VerifyCode類的對象 BufferedImage bi = vc.getImage();//調(diào)用getImge()方法獲得一個(gè)BufferedImage對象 VerifyCode.output(bi, new FileOutputStream("C:/驗(yàn)證碼3.jpg"));//調(diào)用靜態(tài)方法output()方法將圖片保存在文件輸出流中 System.out.println(vc.getText());//在控制臺(tái)上打印驗(yàn)證碼的文本值 } }
VerifyCodeServlet:
package com.lhy.web.servlet; import java.awt.image.BufferedImage; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class VerifyCodeServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* * 1. 生成圖片 * 2. 保存圖片上的文本到session域中 * 3. 把圖片響應(yīng)給客戶端 */ VerifyCode vc = new VerifyCode(); BufferedImage image = vc.getImage(); request.getSession().setAttribute("session_vcode", vc.getText());//保存圖片上的文本到session域 VerifyCode.output(image, response.getOutputStream()); } }
LoginServlet:
package com.lhy.web.servlet; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class LoginServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* * 校驗(yàn)驗(yàn)證碼 * 1. 從session中獲取正確的驗(yàn)證碼 * 2. 從表單中獲取用戶填寫的驗(yàn)證碼 * 3. 進(jìn)行比較! * 4. 如果相同,向下運(yùn)行,否則保存錯(cuò)誤信息到request域,轉(zhuǎn)發(fā)到login.jsp */ String sessionCode = (String) request.getSession().getAttribute("session_vcode"); String paramCode = request.getParameter("verifyCode"); if(!paramCode.equalsIgnoreCase(sessionCode)) { request.setAttribute("msg", "驗(yàn)證碼錯(cuò)誤!"); request.getRequestDispatcher("/login.jsp").forward(request, response); return; } /* * 1. 獲取表單數(shù)據(jù) */ // 處理中文問題 request.setCharacterEncoding("utf-8"); // 獲取 String username = request.getParameter("username"); String password = request.getParameter("password"); /* * 2. 校驗(yàn)用戶名和密碼是否正確 */ if("itcast".equalsIgnoreCase(username)) {//登錄成功 /* * 附加項(xiàng):把用戶名保存到cookie中,發(fā)送給客戶端瀏覽器 * 當(dāng)再次打開login.jsp時(shí),login.jsp中會(huì)讀取request中的cookie,把它顯示到用戶名文本框中 */ Cookie cookie = new Cookie("uname", username);//創(chuàng)建Cookie cookie.setMaxAge(60*60*24);//設(shè)置cookie命長為1天 response.addCookie(cookie);//保存cookie /* * 3. 如果成功 * > 保存用戶信息到session中 * > 重定向到succ1.jsp */ HttpSession session = request.getSession();//獲取session session.setAttribute("username", username);//向session域中保存用戶名 response.sendRedirect("/Test/succ1.jsp"); } else {//登錄失敗 /* * 4. 如果失敗 * > 保存錯(cuò)誤信息到request域中 * > 轉(zhuǎn)發(fā)到login.jsp */ request.setAttribute("msg", "用戶名或密碼錯(cuò)誤!"); RequestDispatcher qr = request.getRequestDispatcher("/login.jsp");//得到轉(zhuǎn)發(fā)器 qr.forward(request, response);//轉(zhuǎn)發(fā) } } }
login.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%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" > <title>My JSP 'login.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" > --> <script type="text/javascript"> function _change() { /* 1. 得到img元素 2. 修改其src */ var imgEle = document.getElementById("img"); imgEle.src = "<%=basePath%>servlet/VerifyCodeServlet?a=" + new Date().getTime(); } </script> </head> <body> <%-- 本頁面提供登錄表單,還要顯示錯(cuò)誤信息 --%> <h1>登錄</h1> <% /* 讀取名為uname的Cookie! 如果為空顯示:"" 如果不為空顯示:Cookie的值 */ String uname = ""; Cookie[] cs = request.getCookies();//獲取請求中所有的cookie if(cs != null) {// 如果存在cookie for(Cookie c : cs) {//循環(huán)遍歷所有的cookie if("uname".equals(c.getName())) {//查找名為uname的cookie uname = c.getValue();//獲取這個(gè)cookie的值,給uname這個(gè)變量 } } } %> <% String message = ""; String msg = (String)request.getAttribute("msg");//獲取request域中的名為msg的屬性 if(msg != null) { message = msg; } %> <font color="red"><b><%=message %> </b></font> <form action="servlet/LoginServlet" method="post"> <%-- 把cookie中的用戶名顯示到用戶名文本框中 --%> 用戶名:<input type="text" name="username" value="<%=uname%>"/><br/> 密 碼:<input type="password" name="password"/><br/> 驗(yàn)證碼:<input type="text" name="verifyCode" size="3"/> <img id="img" src="<%=basePath%>servlet/VerifyCodeServlet"/> <a href="javascript:_change()" rel="external nofollow" >換一張</a> <br/> <input type="submit" value="登錄"/> </form> </body> </html>
loginsuccess:
<body> <h1>succ1</h1> <% String username = (String)session.getAttribute("username"); if(username == null) { /* 1. 向request域中保存錯(cuò)誤信息,轉(zhuǎn)發(fā)到login.jsp */ request.setAttribute("msg", "您還沒有登錄!請先登錄!"); request.getRequestDispatcher("/login.jsp").forward(request, response); return; } %>
歡迎歡迎,熱烈歡迎,歡迎<%=username %>
領(lǐng)導(dǎo)指導(dǎo)工作!
</body> </html>
配置文件:
<servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.lhy.web.servlet.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/servlet/LoginServlet</url-pattern> </servlet-mapping> <servlet> <servlet-name>VerifyCodeServlet</servlet-name> <servlet-class>com.lhy.web.servlet.VerifyCodeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>VerifyCodeServlet</servlet-name> <url-pattern>/servlet/VerifyCodeServlet</url-pattern> </servlet-mapping>
建議:生成驗(yàn)證碼的Servlet最好設(shè)置成不緩存,這樣就不用再頁面請求驗(yàn)證碼圖片的時(shí)候加上時(shí)間戳了,加上時(shí)間戳就是欺騙瀏覽器防止瀏覽器讀取緩存里的驗(yàn)證碼圖片,而點(diǎn)擊換一張后沒反應(yīng)。 這樣的不是很好的一點(diǎn)就是,每次點(diǎn)擊換一張,瀏覽器都會(huì)把新獲取的圖片緩存到本地,而在Servlet里設(shè)置不緩存,就不會(huì)緩存到本地了。
總結(jié)
以上所述是小編給大家介紹的JAVA驗(yàn)證碼工具實(shí)例代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
SpringBoot使用Prometheus采集自定義指標(biāo)數(shù)據(jù)的方法詳解
隨著微服務(wù)在生產(chǎn)環(huán)境大規(guī)模部署和應(yīng)用,隨之而來也帶來了新的問題,其中比較關(guān)鍵的就是關(guān)于微服務(wù)的運(yùn)維和監(jiān)控,本文將結(jié)合微服務(wù)運(yùn)維監(jiān)控中的指標(biāo)監(jiān)控進(jìn)行詳細(xì)的說明,需要的朋友可以參考下2024-07-07深入分析JAVA Synchronized關(guān)鍵字
這篇文章主要介紹了析JAVA Synchronized關(guān)鍵字的相關(guān)知識(shí),文中代碼非常詳細(xì),幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下2020-06-06springboot大文件上傳、分片上傳、斷點(diǎn)續(xù)傳、秒傳的實(shí)現(xiàn)
本文主要介紹了springboot大文件上傳、分片上傳、斷點(diǎn)續(xù)傳、秒傳的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07詳解如何使用ModelMapper庫進(jìn)行對象之間的屬性映射
這篇文章主要介紹了如何使用ModelMapper庫進(jìn)行對象之間的屬性映射實(shí)現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07java獲取機(jī)器碼簡單實(shí)現(xiàn)demo
這篇文章主要為大家介紹了java獲取機(jī)器碼的簡單實(shí)現(xiàn)demo,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11