servlet验证码

生成验证码工具类:

  1 package servlet;
  2 
  3 import java.awt.Color;
  4 import java.awt.Font;
  5 import java.awt.Graphics;
  6 import java.awt.Graphics2D;
  7 import java.awt.RenderingHints;
  8 import java.awt.geom.AffineTransform;
  9 import java.awt.image.BufferedImage;
 10 import java.io.File;
 11 import java.io.FileOutputStream;
 12 import java.io.IOException;
 13 import java.io.OutputStream;
 14 import java.util.Arrays;
 15 import java.util.Random;
 16  
 17 import javax.imageio.ImageIO;
 18 /**
 19  * <p><b>VerifyCodeUtils Description:</b> (验证码生成)</p>
 20  * <b>DATE:</b> 2016年6月2日 下午3:53:34
 21  */
 22 public class VerifyCodeUtils{
 23      
 24     //使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符
 25     public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
 26     private static Random random = new Random();
 27  
 28  
 29     /**
 30      * 使用系统默认字符源生成验证码
 31      * @param verifySize    验证码长度
 32      * @return
 33      */
 34     public static String generateVerifyCode(int verifySize){
 35         return generateVerifyCode(verifySize, VERIFY_CODES);
 36     }
 37     /**
 38      * 使用指定源生成验证码
 39      * @param verifySize    验证码长度
 40      * @param sources   验证码字符源
 41      * @return
 42      */
 43     public static String generateVerifyCode(int verifySize, String sources){
 44         if(sources == null || sources.length() == 0){
 45             sources = VERIFY_CODES;
 46         }
 47         int codesLen = sources.length();
 48         Random rand = new Random(System.currentTimeMillis());
 49         StringBuilder verifyCode = new StringBuilder(verifySize);
 50         for(int i = 0; i < verifySize; i++){
 51             verifyCode.append(sources.charAt(rand.nextInt(codesLen-1)));
 52         }
 53         return verifyCode.toString();
 54     }
 55      
 56     /**
 57      * 生成随机验证码文件,并返回验证码值
 58      * @param w
 59      * @param h
 60      * @param outputFile
 61      * @param verifySize
 62      * @return
 63      * @throws IOException
 64      */
 65     public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException{
 66         String verifyCode = generateVerifyCode(verifySize);
 67         outputImage(w, h, outputFile, verifyCode);
 68         return verifyCode;
 69     }
 70      
 71     /**
 72      * 输出随机验证码图片流,并返回验证码值
 73      * @param w
 74      * @param h
 75      * @param os
 76      * @param verifySize
 77      * @return
 78      * @throws IOException
 79      */
 80     public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException{
 81         String verifyCode = generateVerifyCode(verifySize);
 82         outputImage(w, h, os, verifyCode);
 83         return verifyCode;
 84     }
 85      
 86     /**
 87      * 生成指定验证码图像文件
 88      * @param w
 89      * @param h
 90      * @param outputFile
 91      * @param code
 92      * @throws IOException
 93      */
 94     public static void outputImage(int w, int h, File outputFile, String code) throws IOException{
 95         if(outputFile == null){
 96             return;
 97         }
 98         File dir = outputFile.getParentFile();
 99         if(!dir.exists()){
100             dir.mkdirs();
101         }
102         try{
103             outputFile.createNewFile();
104             FileOutputStream fos = new FileOutputStream(outputFile);
105             outputImage(w, h, fos, code);
106             fos.close();
107         } catch(IOException e){
108             throw e;
109         }
110     }
111      
112     /**
113      * 输出指定验证码图片流
114      * @param w
115      * @param h
116      * @param os
117      * @param code
118      * @throws IOException
119      */
120     public static void outputImage(int w, int h, OutputStream os, String code) throws IOException{
121         int verifySize = code.length();
122         BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
123         Random rand = new Random();
124         Graphics2D g2 = image.createGraphics();
125         g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
126         Color[] colors = new Color[5];
127         Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN,
128                 Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
129                 Color.PINK, Color.YELLOW };
130         float[] fractions = new float[colors.length];
131         for(int i = 0; i < colors.length; i++){
132             colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
133             fractions[i] = rand.nextFloat();
134         }
135         Arrays.sort(fractions);
136          
137         g2.setColor(Color.GRAY);// 设置边框色
138         g2.fillRect(0, 0, w, h);
139          
140         Color c = getRandColor(200, 250);
141         g2.setColor(c);// 设置背景色
142         g2.fillRect(0, 2, w, h-4);
143          
144         //绘制干扰线
145         Random random = new Random();
146         g2.setColor(getRandColor(160, 200));// 设置线条的颜色
147         for (int i = 0; i < 20; i++) {
148             int x = random.nextInt(w - 1);
149             int y = random.nextInt(h - 1);
150             int xl = random.nextInt(6) + 1;
151             int yl = random.nextInt(12) + 1;
152             g2.drawLine(x, y, x + xl + 40, y + yl + 20);
153         }
154          
155         // 添加噪点
156         float yawpRate = 0.05f;// 噪声率
157         int area = (int) (yawpRate * w * h);
158         for (int i = 0; i < area; i++) {
159             int x = random.nextInt(w);
160             int y = random.nextInt(h);
161             int rgb = getRandomIntColor();
162             image.setRGB(x, y, rgb);
163         }
164          
165         shear(g2, w, h, c);// 使图片扭曲
166  
167         g2.setColor(getRandColor(100, 160));
168         int fontSize = h-4;
169         Font font = new Font("Algerian", Font.ITALIC, fontSize);
170         g2.setFont(font);
171         char[] chars = code.toCharArray();
172         for(int i = 0; i < verifySize; i++){
173             AffineTransform affine = new AffineTransform();
174             affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize/2, h/2);
175             g2.setTransform(affine);
176             g2.drawChars(chars, i, 1, ((w-10) / verifySize) * i + 5, h/2 + fontSize/2 - 10);
177         }
178          
179         g2.dispose();
180         ImageIO.write(image, "jpg", os);
181     }
182      
183     private static Color getRandColor(int fc, int bc) {
184         if (fc > 255)
185             fc = 255;
186         if (bc > 255)
187             bc = 255;
188         int r = fc + random.nextInt(bc - fc);
189         int g = fc + random.nextInt(bc - fc);
190         int b = fc + random.nextInt(bc - fc);
191         return new Color(r, g, b);
192     }
193      
194     private static int getRandomIntColor() {
195         int[] rgb = getRandomRgb();
196         int color = 0;
197         for (int c : rgb) {
198             color = color << 8;
199             color = color | c;
200         }
201         return color;
202     }
203      
204     private static int[] getRandomRgb() {
205         int[] rgb = new int[3];
206         for (int i = 0; i < 3; i++) {
207             rgb[i] = random.nextInt(255);
208         }
209         return rgb;
210     }
211  
212     private static void shear(Graphics g, int w1, int h1, Color color) {
213         shearX(g, w1, h1, color);
214         shearY(g, w1, h1, color);
215     }
216      
217     private static void shearX(Graphics g, int w1, int h1, Color color) {
218  
219         int period = random.nextInt(2);
220  
221         boolean borderGap = true;
222         int frames = 1;
223         int phase = random.nextInt(2);
224  
225         for (int i = 0; i < h1; i++) {
226             double d = (double) (period >> 1)
227                     * Math.sin((double) i / (double) period
228                             + (6.2831853071795862D * (double) phase)
229                             / (double) frames);
230             g.copyArea(0, i, w1, 1, (int) d, 0);
231             if (borderGap) {
232                 g.setColor(color);
233                 g.drawLine((int) d, i, 0, i);
234                 g.drawLine((int) d + w1, i, w1, i);
235             }
236         }
237  
238     }
239  
240     private static void shearY(Graphics g, int w1, int h1, Color color) {
241  
242         int period = random.nextInt(40) + 10; // 50;
243  
244         boolean borderGap = true;
245         int frames = 20;
246         int phase = 7;
247         for (int i = 0; i < w1; i++) {
248             double d = (double) (period >> 1)
249                     * Math.sin((double) i / (double) period
250                             + (6.2831853071795862D * (double) phase)
251                             / (double) frames);
252             g.copyArea(i, 0, 1, h1, 0, (int) d);
253             if (borderGap) {
254                 g.setColor(color);
255                 g.drawLine(i, (int) d, i, 0);
256                 g.drawLine(i, (int) d + h1, i, h1);
257             }
258  
259         }
260  
261     }
262     public static void main(String[] args) throws IOException{
263         File dir = new File("F:/verifies");
264         int w = 200, h = 80;
265         for(int i = 0; i < 50; i++){
266             String verifyCode = generateVerifyCode(4);
267             File file = new File(dir, verifyCode + ".jpg");
268             outputImage(w, h, file, verifyCode);
269         }
270     }
271 }
VerifyCodeUtils

servlet层:

 1 package servlet;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 import javax.servlet.http.HttpSession;
11 
12 public class VerifyServlet extends HttpServlet {
13 
14     /**
15      * Constructor of the object.
16      */
17     public VerifyServlet() {
18         super();
19     }
20 
21     /**
22      * Destruction of the servlet. <br>
23      */
24     public void destroy() {
25         super.destroy(); // Just puts "destroy" string in log
26         // Put your code here
27     }
28 
29     /**
30      * The doGet method of the servlet. <br>
31      *
32      * This method is called when a form has its tag value method equals to get.
33      * 
34      * @param request the request send by the client to the server
35      * @param response the response send by the server to the client
36      * @throws ServletException if an error occurred
37      * @throws IOException if an error occurred
38      */
39     public void doGet(HttpServletRequest request, HttpServletResponse response)
40             throws ServletException, IOException {
41          response.setHeader("Pragma", "No-cache"); 
42         response.setHeader("Cache-Control", "no-cache"); 
43         response.setDateHeader("Expires", 0); 
44         response.setContentType("image/jpeg"); 
45            
46         //生成随机字串 
47         String verifyCode = VerifyCodeUtils.generateVerifyCode(4); 
48         //存入会话session 
49         HttpSession session = request.getSession(true); 
50         //删除以前的
51         session.removeAttribute("verCode");
52         session.setAttribute("verCode", verifyCode.toLowerCase()); 
53         //生成图片 
54         int w = 100, h = 30; 
55         VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode); 
56     }
57 
58     /**
59      * The doPost method of the servlet. <br>
60      *
61      * This method is called when a form has its tag value method equals to post.
62      * 
63      * @param request the request send by the client to the server
64      * @param response the response send by the server to the client
65      * @throws ServletException if an error occurred
66      * @throws IOException if an error occurred
67      */
68     public void doPost(HttpServletRequest request, HttpServletResponse response)
69             throws ServletException, IOException {
70 
71         doGet(request, response);
72     }
73 
74     /**
75      * Initialization of the servlet. <br>
76      *
77      * @throws ServletException if an error occurs
78      */
79     public void init() throws ServletException {
80         // Put your code here
81     }
82 
83 }
VerifyServlet.java

web.xml:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app version="3.0" 
 3     xmlns="http://java.sun.com/xml/ns/javaee" 
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 5     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
 6     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
 7   <display-name></display-name>
 8 
 9   <servlet>
10     <description>This is the description of my J2EE component</description>
11     <display-name>This is the display name of my J2EE component</display-name>
12     <servlet-name>VerifyServlet</servlet-name>
13     <servlet-class>servlet.VerifyServlet</servlet-class>
14   </servlet>
15 
16   <servlet-mapping>
17     <servlet-name>VerifyServlet</servlet-name>
18     <url-pattern>/servlet/VerifyServlet</url-pattern>
19   </servlet-mapping>    
20 
21   <welcome-file-list>
22     <welcome-file>index.jsp</welcome-file>
23   </welcome-file-list>
24 
25 </web-app>
web.xml

jsp:

 1 <body>
 2   <!-- 验证码 -->
 3     <tr>
 4        <td nowrap width="437"></td>
 5         <td>
 6             <img id="img" src="servlet/VerifyServlet" />
 7             <a href='#' onclick="javascript:changeImg()" style="color:white;"><label style="color:black;">看不清?</label></a>
 8         </td>
 9      </tr>
10       
11       
12      <!-- 触发JS刷新-->
13      <script type="text/javascript">
14         function changeImg(){
15             var img = document.getElementById("img"); 
16             img.src = "servlet/VerifyServlet?date=" + new Date();;
17         }
18     </script>
19   </body>
verify.jsp
原文地址:https://www.cnblogs.com/popcornya/p/6830675.html