近日 ,遇到和驗(yàn)證碼問(wèn)題,在網(wǎng)上找了很多資料加自己的總結(jié),得到可實(shí)現(xiàn)代碼
成都創(chuàng)新互聯(lián)公司堅(jiān)持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:成都網(wǎng)站設(shè)計(jì)、成都做網(wǎng)站、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時(shí)代的舟山網(wǎng)站設(shè)計(jì)、移動(dòng)媒體設(shè)計(jì)的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!
login.jsp代碼
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>oa自動(dòng)化辦公系統(tǒng) IdentCodeServlet.java 代碼
package com.eduask.oa.servlet; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.p_w_picpath.BufferedImage; import java.io.IOException; import javax.p_w_picpathio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.eduask.oa.util.CreateRandomCode; /** * 將生成的驗(yàn)證碼作為圖片輸出 * @author Maibenben * */ public class IdentCodeServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. 禁止瀏覽器緩存隨機(jī)圖片 response.setDateHeader("Expires", -1); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); //2.通知服務(wù)器以圖片的方式發(fā)送數(shù)據(jù) response.setHeader("Content-Type", "p_w_picpath/jpeg"); //3.在內(nèi)存創(chuàng)建一張圖片 BufferedImage p_w_picpath = new BufferedImage(150, 50, BufferedImage.TYPE_INT_BGR); //4.向圖片上寫數(shù)據(jù) Graphics g = p_w_picpath.getGraphics(); //5.設(shè)置背景色 g.setColor(Color.gray); g.fillRect(0, 0, 150, 50); //6. 設(shè)置寫入數(shù)據(jù)的顏色和字體 g.setColor(Color.red); g.setFont(new Font(null, Font.BOLD, 50)); // 7.想圖片上寫數(shù)據(jù) String randomNum = new CreateRandomCode().createRandomCode(); request.getSession().setAttribute("checkRandomCode", randomNum); g.drawString(randomNum, 20, 40); System.out.println(randomNum); // 8.把寫好的圖片輸出到瀏覽器 ImageIO.write(p_w_picpath, "jpg", response.getOutputStream()); } }生成4位隨機(jī)驗(yàn)證碼代碼 CreateRandomCode.java
package com.eduask.oa.util; /** * 隨機(jī)產(chǎn)生4位 數(shù)字或字母混合 * @author Maibenben * */ public class CreateRandomCode { private char[] code = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; /** * 生成4位驗(yàn)證碼 * @return */ public String createRandomCode() { char[] codeRandom = new char[4]; //循環(huán)取得其中隨機(jī)字符 for(int i=0; i< codeRandom.length; i++) { int random = (int)(Math.random()*code.length); codeRandom[i] = code[random]; } //將字符數(shù)組轉(zhuǎn)為String StringBuffer sb = new StringBuffer(); for(int i=0; i這只是簡(jiǎn)單的驗(yàn)證碼圖片刷新,希望可以幫到正在尋找答案的你