本文共 1900 字,大约阅读时间需要 6 分钟。
在浏览网页时,我们会经常看到验证码,尤其是登录和注册的时候,今天就为大家介绍一下如何使用JSP生成验证码图片,原理其实是很简单的,直接上代码:
<%@ page contentType="image/jpeg;charset=utf-8" pageEncoding="GBK" %><%@ page import="java.util.*,java.awt.*,java.awt.image.*,javax.imageio.*" import="java.io.OutputStream" %><%! Color getRandColor(int fc,int bc) { Random rd = new Random(); if (fc > 255) fc = 255; if (bc > 255) bc = 255; int red = fc + rd.nextInt(bc - fc); int green = fc + rd.nextInt(bc - fc); int blue = fc + rd.nextInt(bc - fc); return new Color(red, green, blue); }%> <% Random r = new Random(); response.addHeader("Pragma", "No-cache"); response.addHeader("Cache-Control", "no-cache"); response.addDateHeader("expires", 0); int width = 80; int height = 32; BufferedImage pic = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics gc = pic.getGraphics(); gc.setColor(getRandColor(200, 250)); gc.fillRect(0, 0, width, height); String[] rNum = { "1", "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", "W", "X", "Y", "Z"}; int[] style = {Font.PLAIN, Font.BOLD, Font.ITALIC, Font.PLAIN + Font.BOLD, Font.BOLD + Font.ITALIC, Font.PLAIN + Font.ITALIC, Font.PLAIN + Font.BOLD + Font.ITALIC}; gc.setColor(getRandColor(60,150)); String rt = ""; for(int i = 0; i < 4; i++) { String temp = rNum[r.nextInt(rNum.length)]; rt = rt + temp; gc.setFont(new Font("Times New Roman", style[r.nextInt(7)], 21)); gc.drawString(temp, 15 + 13 * i + r.nextInt(2), 23); } gc.dispose(); OutputStream os = response.getOutputStream(); ImageIO.write(pic, "JPEG", os); os.flush(); os.close(); os = null; response.flushBuffer(); out.clear(); out = pageContext.pushBody();%>
运行程序,通过浏览器访问,我们会看到浏览器上显示
大家可以自己尝试在绘图的时候增加一些删除线之类的,提高验证码识别难度。