jsp中验证码生成类:
View Code
1 package com.tenchong.util; 2 3 import java.awt.Color; 4 import java.awt.Font; 5 import java.awt.Graphics; 6 import java.awt.image.BufferedImage; 7 import java.io.IOException; 8 import java.util.Random; 9 import javax.servlet.ServletOutputStream; 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 import com.sun.image.codec.jpeg.JPEGCodec; 13 import com.sun.image.codec.jpeg.JPEGImageEncoder; 14 public class VerifyCodeGenerator { 15 private static final VerifyCodeGenerator generator = new VerifyCodeGenerator(); 16 17 private final String ATTRIBUTE_NAME = "verifycode"; 18 private final int WIDTH = 16; 19 private final int HEIGHT=20; 20 private final int CODE_LENGTH = 4; 21 22 private final String RAND_RANGE = "abcdefghijklmnopqrstuvwxyz" 23 + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 24 + "1234567890"; 25 26 private final char[] CHARS = RAND_RANGE.toCharArray(); 27 28 private Random random = new Random(); 29 30 private VerifyCodeGenerator(){ 31 } 32 33 public static VerifyCodeGenerator getInstance(){ 34 return generator; 35 } 36 37 private String getRandString(){ 38 StringBuilder sb = new StringBuilder(); 39 for (int i = 0; i < CODE_LENGTH; i++) 40 sb.append(CHARS[random.nextInt(CHARS.length)]); 41 return sb.toString(); 42 } 43 44 private Color getRandColor(int ll, int ul){ 45 if (ll > 255) ll = 255; 46 if (ll < 1) ll = 1; 47 if (ul > 255) ul = 255; 48 if (ul < 1) ul = 1; 49 if (ul == ll) ul = ll + 1; 50 int r = random.nextInt(ul - ll) + ll; 51 int g = random.nextInt(ul - ll) + ll; 52 int b = random.nextInt(ul - ll) + ll; 53 Color color = new Color(r,g,b); 54 return color; 55 } 56 57 58 private BufferedImage getImage(String verifyCode){ 59 60 BufferedImage image = new BufferedImage(WIDTH * CODE_LENGTH, HEIGHT, BufferedImage.TYPE_INT_RGB); 61 Graphics graphics = image.getGraphics(); 62 graphics.setColor(getRandColor(200,250)); 63 graphics.fillRect(0, 0, WIDTH*4, HEIGHT); 64 graphics.setColor(getRandColor(160,200)); 65 for (int i=0; i<50; i++){ 66 int x = random.nextInt(WIDTH); 67 int y = random.nextInt(HEIGHT); 68 int xl = random.nextInt(12); 69 int yl = random.nextInt(12); 70 graphics.drawLine(x,y,x+xl,y+yl); 71 } 72 graphics.setFont(new Font("Times New Roman", Font.PLAIN, 22)); 73 for (int i=0; i<this.CODE_LENGTH; i++){ 74 String temp = verifyCode.substring(i, i+1); 75 graphics.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110))); 76 graphics.drawString(temp, 13 * i + 6, 16); 77 } 78 graphics.dispose(); 79 80 return image; 81 } 82 public void printImage(HttpServletRequest request, 83 HttpServletResponse response){ 84 response.setContentType("image/jpeg"); 85 response.setHeader("Pragma", "No-cache"); 86 response.setHeader("Cache-Control", "no-cache"); 87 response.setDateHeader("Expires", 2000); 88 89 String verifyCode = this.getRandString(); 90 String str = "ssss"; 91 for(int i=0; i<10; i++) 92 str = str + str; 93 BufferedImage bi = this.getImage(verifyCode); 94 request.getSession().setAttribute("ATTRIBUTE_NAME", verifyCode); 95 try{ 96 ServletOutputStream outStream = response.getOutputStream(); 97 98 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outStream); 99 encoder.encode(bi); 100 outStream.flush(); 101 102 outStream.close(); 103 }catch(IOException ex){ 104 ex.printStackTrace(); 105 } 106 } 107 public boolean check(HttpServletRequest request){ 108 if (((String)request.getParameter(ATTRIBUTE_NAME)) 109 .equalsIgnoreCase((String)request.getSession(true).getAttribute("ATTRIBUTE_NAME"))){ 110 request.getSession().removeAttribute(ATTRIBUTE_NAME); 111 return true; 112 } 113 return false; 114 } 115 116 }
代码中的check方法用于验证正确性,如:
if(!verify.check(request)){ request.setAttribute("error", "验证码错误!"); return mapping.findForward("error"); }
android中验证码生成类:
View Code
1 package cn.itcast.mp3; 2 import java.util.Random; 3 4 import android.graphics.Bitmap; 5 import android.graphics.Canvas; 6 import android.graphics.Color; 7 import android.graphics.Paint; 8 import android.graphics.Bitmap.Config; 9 10 public class BPUtil { 11 12 private static final char[] CHARS = { 13 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 14 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 15 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 16 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 17 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' 18 }; 19 20 private static BPUtil bpUtil; 21 22 public static BPUtil getInstance() { 23 if(bpUtil == null) 24 bpUtil = new BPUtil(); 25 return bpUtil; 26 } 27 28 // width="60" height="30" 29 // base_padding_left="5" 30 // range_padding_left="10" 31 // base_padding_top="15" 32 // range_padding_top="10" 33 // codeLength="4" 34 // line_number="3" 35 // font_size="20" 36 37 //default settings 38 private static final int DEFAULT_CODE_LENGTH = 4; 39 private static final int DEFAULT_FONT_SIZE = 20; 40 private static final int DEFAULT_LINE_NUMBER = 3; 41 private static final int BASE_PADDING_LEFT = 5, RANGE_PADDING_LEFT = 10, BASE_PADDING_TOP = 15, RANGE_PADDING_TOP = 10; 42 private static final int DEFAULT_WIDTH = 60, DEFAULT_HEIGHT = 30; 43 44 //settings decided by the layout xml 45 //canvas width and height 46 private int width = DEFAULT_WIDTH, height = DEFAULT_HEIGHT; 47 48 //random word space and pading_top 49 private int base_padding_left = BASE_PADDING_LEFT, range_padding_left = RANGE_PADDING_LEFT, 50 base_padding_top = BASE_PADDING_TOP, range_padding_top = RANGE_PADDING_TOP; 51 52 //number of chars, lines; font size 53 private int codeLength = DEFAULT_CODE_LENGTH, line_number = DEFAULT_LINE_NUMBER, font_size = DEFAULT_FONT_SIZE; 54 55 //variables 56 private String code; 57 private int padding_left, padding_top; 58 private Random random = new Random(); 59 60 public Bitmap createBitmap() { 61 padding_left = 0; 62 63 Bitmap bp = Bitmap.createBitmap(width, height, Config.ARGB_8888); 64 Canvas c = new Canvas(bp); 65 66 code = createCode(); 67 68 c.drawColor(Color.WHITE); 69 Paint paint = new Paint(); 70 paint.setTextSize(font_size); 71 72 for (int i = 0; i < code.length(); i++) { 73 randomTextStyle(paint); 74 randomPadding(); 75 c.drawText(code.charAt(i) + "", padding_left, padding_top, paint); 76 } 77 78 for (int i = 0; i < line_number; i++) { 79 drawLine(c, paint); 80 } 81 82 c.save( Canvas.ALL_SAVE_FLAG );//保存 83 c.restore();// 84 return bp; 85 } 86 87 public String getCode() { 88 return code; 89 } 90 91 private String createCode() { 92 StringBuilder buffer = new StringBuilder(); 93 for (int i = 0; i < codeLength; i++) { 94 buffer.append(CHARS[random.nextInt(CHARS.length)]); 95 } 96 return buffer.toString(); 97 } 98 99 private void drawLine(Canvas canvas, Paint paint) { 100 int color = randomColor(); 101 int startX = random.nextInt(width); 102 int startY = random.nextInt(height); 103 int stopX = random.nextInt(width); 104 int stopY = random.nextInt(height); 105 paint.setStrokeWidth(1); 106 paint.setColor(color); 107 canvas.drawLine(startX, startY, stopX, stopY, paint); 108 } 109 110 private int randomColor() { 111 return randomColor(1); 112 } 113 114 private int randomColor(int rate) { 115 int red = random.nextInt(256) / rate; 116 int green = random.nextInt(256) / rate; 117 int blue = random.nextInt(256) / rate; 118 return Color.rgb(red, green, blue); 119 } 120 121 private void randomTextStyle(Paint paint) { 122 int color = randomColor(); 123 paint.setColor(color); 124 paint.setFakeBoldText(random.nextBoolean()); //true为粗体,false为非粗体 125 float skewX = random.nextInt(11) / 10; 126 skewX = random.nextBoolean() ? skewX : -skewX; 127 paint.setTextSkewX(skewX); //float类型参数,负数表示右斜,整数左斜 128 // paint.setUnderlineText(true); //true为下划线,false为非下划线 129 // paint.setStrikeThruText(true); //true为删除线,false为非删除线 130 } 131 132 private void randomPadding() { 133 padding_left += base_padding_left + random.nextInt(range_padding_left); 134 padding_top = base_padding_top + random.nextInt(range_padding_top); 135 } 136 }
调用方式:
ImageView imageView = (ImageView)findViewById(R.id.imageView);
imageView.setImageBitmap(BPUtil.getInstance().createBitmap());
通过getcode可以获取验证码字符串。