標籤:java web 驗證碼
1 驗證碼產生類RandomCode
RandomCode是一個產生驗證碼的工具類,支援英文和數字驗證碼,驗證碼包括英文大小寫和數組,其中英文i、o和數字0、1因為容易產生混淆,不包括在產生驗證碼中。RandomCode支援輸出jpg/bmp/png/gif圖片格式的驗證碼。
/** * RandomCode驗證碼可以通過靜態方法和執行個體方法產生。 * * 靜態方法: * * //產生長度為4的隨機驗證碼 * String code = RandomCode.randomString(4); * * //把驗證碼圖片輸入到response輸出資料流中 * //圖片格式jpg * OutputStream os = response.getOutputStream(); * RandomCode.write(code, 120, 30, os, "jpg"); * * 執行個體方法: * * //執行個體化驗證碼類 * RandomCode rc = new RandomCode(4); * * //把驗證碼圖片輸入到response輸出資料流中 * //圖片格式jpg * OutputStream os = response.getOutputStream(); * rc.write(120, 30, os, "jpg"); * * //擷取驗證碼字串 * String code = rc.getCode(); * */public class RandomCode {/** * 隨機驗證碼字元 */private static String base = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";/** * 隨機驗證碼長度 */private int length = 4;/** * 驗證碼字串 */private String code;/** * 4位隨機驗證碼 */public RandomCode(){this.code = RandomCode.randomString(this.length);}public RandomCode(int length){if(length > 0){this.length = length;}this.code = RandomCode.randomString(this.length);}/** * 產生驗證碼圖片 * @param width 圖片寬度 * @param height 圖片高度 * @return */public BufferedImage toImage(int width, int height){return RandomCode.toImage(this.code, width, height);}/** * 輸出驗證碼圖片,預設圖片格式jpeg * @param width * @param height * @param os * @throws IOException */public void write(int width, int height, OutputStream os) throws IOException{RandomCode.write(code, width, height, os, "jpeg");}/** * 輸出驗證碼圖片 * @param width * @param height * @param os * @param format 圖片格式,支援jpg/jpeg/bmp/gif/png * @throws IOException */public void write(int width, int height, OutputStream os, String format) throws IOException{RandomCode.write(code, width, height, os, format);}public int getLength() {return length;}public String getCode() {return code;}/** * 靜態方法 * 產生隨機字串 * @param length 字串長度 * @return 隨機字串 */public static String randomString(int length){Random random = new Random();StringBuffer sb = new StringBuffer();for(int i = 0; i < length; i++){sb.append(base.charAt(random.nextInt(base.length())));}return sb.toString();}/** * 靜態方法 * 輸出驗證碼圖片 * @param code 驗證碼字串 * @param width 圖片寬度 * @param height 圖片高度 * @param os 圖片輸出資料流 * @param format 圖片格式,支援jpg/jpeg/bmp/gif/png * @throws IOException */public static void write(String code, int width, int height, OutputStream os, String format) throws IOException{BufferedImage image = toImage(code, width, height);ImageIO.write(image, format, os);}/** * 靜態方法 * 輸出驗證碼圖片,預設圖片格式jpeg * @param code 驗證碼字串 * @param width 圖片寬度 * @param height 圖片高度 * @param os 圖片輸出資料流 * @throws IOException */public static void write(String code, int width, int height, OutputStream os) throws IOException{write(code, width, height, os, "jpeg");}/** * 靜態方法 * 字串轉成驗證碼圖片 * @param code 驗證碼字串 * @param width 驗證碼圖片寬度,單位像素 * @param height 驗證碼圖片高度,單位像素 * @return */public static BufferedImage toImage(String code, int width, int height){//字型大小int fontSize = (int)Math.ceil(height * 0.9);if(fontSize < 20){fontSize = 20;}//字型在Y座標上的位置int positionY = (int)Math.ceil(height * 0.8);int lenCode = code.length();//計算字型寬度int fontWidth = width / (lenCode + 2);BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);Graphics g = image.getGraphics();//圖片背景隨機顏色g.setColor(randomColor(new Random(), 200, 250));g.fillRect(0, 0, width, height);//設定字型g.setFont(new Font("Times New Roman", Font.BOLD, fontSize));//在圖片上畫縱橫交錯的線,達到混淆效果drawLines(g, width, height);//在圖片上畫驗證碼drawString(g, code, fontWidth, positionY);g.dispose();return image;}/** * 靜態方法 * 在圖片上話位子 * @param g * @param code 驗證碼字串 * @param fontWidth 字型寬度 * @param positionY 字型Y座標 */private static void drawString(Graphics g, String code, int fontWidth, int positionY){int len = code.length();Random random = new Random();for(int i = 0; i < len; i++){g.setColor(randomColor(random));g.drawString(String.valueOf(code.charAt(i)), (i + 1) * fontWidth, positionY);}}private static Color randomColor(Random random){ int r = random.nextInt(255); int g = random.nextInt(255); int b = random.nextInt(255); return new Color(r, g, b); }private static Color randomColor(Random random, int fc, int bc){ if(fc > 255){ fc = 255; } if(bc > 255){ bc = 255; } int diff = bc-fc; int r = fc + random.nextInt(diff); int g = fc + random.nextInt(diff); int b = fc + random.nextInt(diff); return new Color(r,g,b); }/** * 靜態方法 * 畫縱橫交錯的線 * @param g * @param width 驗證碼圖片寬度 * @param height 驗證碼圖片高度 */private static void drawLines(Graphics g, int width, int height){Random random = new Random();//線的數量int count = ((int)(Math.ceil(random.nextDouble() * 100))) + 100;for(int i = 0; i < count; i++){int fc = 160 + (int)Math.ceil(random.nextDouble() * 40);int bc = 200 + (int)Math.ceil(random.nextDouble() * 55); g.setColor(randomColor(random, fc, bc));int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(width / 5); int yl = random.nextInt(height / 5); g.drawLine(x, y, x + xl, y + yl);} }}
2 Servlet返回驗證碼
請求路徑http://<網站路徑>/random/code/servlet
@WebServlet("/random/code/servlet")public class RandomCodeServlet extends HttpServlet {private static final long serialVersionUID = 1L;protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// 驗證碼圖片寬度,單位像素int width = 120;// 驗證碼圖片高度,單位像素int height = 30;// 驗證碼圖片格式String format = "png";// 驗證碼字元長度int len = 4;// 設定圖片格式response.setContentType("image/" + format);// 禁止瀏覽器緩衝圖片response.setHeader("Pragma", "no-cache");response.setHeader("Cache-Control", "no-cache");response.setDateHeader("Expires", 0);String code = RandomCode.randomString(len);// 把圖片輸出到response輸出資料流RandomCode.write(code, width, height, response.getOutputStream(), format);}}
3 Strust2返回驗證碼
public class RandomCodeAction extends ActionSupport {private static final long serialVersionUID = -7515645222798283236L;/** * 擷取驗證碼 */public void generateCode() {HttpServletResponse response = ServletActionContext.getResponse();// 驗證碼圖片寬度,單位像素int width = 120;// 驗證碼圖片高度,單位像素int height = 30;// 驗證碼圖片格式String format = "png";// 驗證碼字元長度int len = 4;// 設定圖片格式response.setContentType("image/" + format);// 禁止瀏覽器緩衝圖片response.setHeader("Pragma", "no-cache");response.setHeader("Cache-Control", "no-cache");response.setDateHeader("Expires", 0);String code = RandomCode.randomString(len);// 把圖片輸出到response輸出資料流try {RandomCode.write(code, width, height, response.getOutputStream(), format);} catch (IOException e) {e.printStackTrace();}}}
Struts2的驗證碼配置
<package name="pkg-random-code" namespace="/" extends="struts-default"><action name="randomCode_*" method="{1}" class="com.rhui.web.action.RandomCodeAction"></action></package>
請求路徑http://<網站路徑>/randomCode_generateCode.do
4 SpringMVC返回驗證碼
請求路徑http://<網站路徑>/random/code/generate.do
package com.rhui.web.controller;import java.io.IOException;import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import com.rhui.util.RandomCode;@Controller@RequestMapping("/random/code")public class RandomCodeController {@RequestMapping("/generate.do")public void generateCode(HttpServletResponse response) {// 驗證碼圖片寬度,單位像素int width = 120;// 驗證碼圖片高度,單位像素int height = 30;// 驗證碼圖片格式String format = "png";// 驗證碼字元長度int len = 4;// 設定圖片格式response.setContentType("image/" + format);// 禁止瀏覽器緩衝圖片response.setHeader("Pragma", "no-cache");response.setHeader("Cache-Control", "no-cache");response.setDateHeader("Expires", 0);String code = RandomCode.randomString(len);// 把圖片輸出到response輸出資料流try {RandomCode.write(code, width, height, response.getOutputStream(), format);} catch (IOException e) {e.printStackTrace();}}}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
Java Web驗證碼