image.jsp的内容如下:(大部分内容来源于网络)
其中字体与字体的样式是随机的。字体的样式只有三种形式:PLAIN,BOLD,ITALIC。字体只存放了八种。因为有的字体显示的时候很难识别,所以对于系统支持的字体需要试一下效果才能放到程序中,很需要时间。以后有时间再做吧。
<%@ page contentType="image/jpeg" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*"%> <%!Color getRandColor(int fc, int bc) {//给定范围获得随机颜色 Random random = new Random(); if (fc > 255) fc = 255; if (bc > 255) bc = 255; int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); }%> <%! String getFontName() { //返回随机字体名 String [] fontName = {"Dialog","DialogInput","Monospaced","Serif","SansSerif","SimSun","Times New Roman","Arial"}; Random random = new Random(); int index = random.nextInt(fontName.length); return String.valueOf(fontName[index]); } %> <% //out.clear();//这句针对resin服务器,如果是tomcat可以不要这句 response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); // 在内存中创建图象 int width = 80, height = 20; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 获取图形上下文 Graphics g = image.getGraphics(); //生成随机类 Random random = new Random(); // 设定背景色 g.setColor(getRandColor(200, 250)); g.fillRect(0, 0, width, height); // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到 //g.setColor(getRandColor(160, 200)); //for (int i = 0; i < 155; i++) { // int x = random.nextInt(width); // int y = random.nextInt(height); // int xl = random.nextInt(10); // int yl = random.nextInt(10); // g.drawLine(x, y, x + xl, y + yl); //}
char c[] = new char[62];
for (int i = 65, j = 0; i < 91; i++, j++) { c[j] = (char) i; } for (int o = 65, p = 26; o < 91; o++, p++) { c[p] = (char) o; } for (int m = 48, n = 52; m < 58; m++, n++) { c[n] = (char) m; }
String sRand = ""; for (int i = 0; i < 4; i++) { int x = random.nextInt(62); String rand = String.valueOf(c[x]); sRand += rand;
g.setColor(new Color(20 + random.nextInt(110), 20 + random .nextInt(110), 20 + random.nextInt(110))); //设定字体 //random.nextInt(3)返回的0,1,2为字体的样式,0为PLAIN,1为BOLD,2为ITALIC。 g.setFont(new Font(getFontName(), random.nextInt(3) , 19)); g.drawString(rand, 15 * i + 6, 16); }
// 将认证码存入SESSION session.setAttribute("rand", sRand); System.out.println(sRand); g.dispose(); ImageIO.setUseCache(true); ImageIO.write(image, "JPEG", response.getOutputStream()); // 「サーブレット jsp のServlet.service()が例外を投げました」BUG対応Start out.clear(); out = pageContext.pushBody(); // 「サーブレット jsp のServlet.service()が例外を投げました」BUG対応End %>
在需要验证码的地方如下调用:
<img style="height:24px;" border=0 src="include/image.jsp" id="imgCode">