1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
| package com.cnblogs.jbelial.Validation;
import java.awt.*; import java.awt.image.BufferedImage; import java.io.* ; import java.util.Random;
import javax.imageio.ImageIO; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;
@SuppressWarnings("serial") public class ValidationCode extends HttpServlet {
private static String codeChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTYVWXYZ" ;
private static Color getRandomColor(int minColor , int maxColor) { Random random = new Random() ; if (minColor > 255) minColor = 255 ; if (maxColor > 255) maxColor = 255 ;
int red = minColor + random.nextInt(maxColor - minColor) ; int green = minColor + random.nextInt(maxColor - minColor) ; int blue = minColor + random.nextInt(maxColor - minColor) ; return new Color(red,green,blue) ; } public void doGet (HttpServletRequest request , HttpServletResponse response) throws IOException {
int charsLength = codeChars.length() ;
response.setHeader("ragma", "No-cache") ; response.setHeader("Cache-Control", "no-cache") ; response.setDateHeader("Expires", 0) ;
response.setContentType("image/jpeg");
int width = 90 ; int height = 20 ;
BufferedImage image = new BufferedImage(width , height, BufferedImage.TYPE_INT_RGB) ;
Graphics graphics = image.getGraphics() ;
Random random = new Random() ;
graphics.setColor(getRandomColor(180 , 250)) ;
graphics.fillRect(0, 0, width, height) ;
graphics.setFont(new Font("Time New Roman" , Font.ITALIC, height)) ; graphics.setColor(getRandomColor(120,180)) ;
StringBuilder validationCode = new StringBuilder() ;
String[] fontNames = {"Times New Roman" , "Book antiqua" , "Arial" } ;
for (int i = 0 ; i < 4 ; ++ i) {
graphics.setFont(new Font(fontNames[random.nextInt(3)] , Font.ITALIC , height)) ;
char codeChar = codeChars.charAt(random.nextInt(charsLength)) ; validationCode.append(codeChar) ; graphics.setColor(getRandomColor(20,120)) ;
graphics.drawString(String.valueOf(codeChar), 16*i+random.nextInt(7), height - random.nextInt(6) ) ; }
HttpSession session = request.getSession(); session.setMaxInactiveInterval(5*60) ;
session.setAttribute("validationCode",validationCode.toString() ) ;
graphics.dispose() ;
ImageIO.write(image,"JPEG" ,response.getOutputStream()) ;
} public void doPost (HttpServletRequest request , HttpServletResponse response) throws IOException { doGet(request , response) ; }
}
|