Java基础--生成验证码

HTML

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <title>验证码</title>
 7 <script type="text/javascript">
 8     function refresh(obj) {
 9         obj.src = "imageServlet?" + Math.random();
10     }
11 </script>
12 </head>
13 <body>
14     <form action="checkServlet" method="post">
15         <label>输入验证码</label><br /> 
16         <input type="text" name="randomCode" />
17         <img title="点击更换" onclick="javascript:refresh(this);" src="imageServlet"><br />
18         <input type="submit" value="提交">
19     </form>
20 </body>
21 </html>

web.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app version="2.5" 
 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_2_5.xsd">
 7   <servlet>
 8     <servlet-name>ImageServlet</servlet-name>
 9     <servlet-class>com.yan.ImageServlet</servlet-class>
10   </servlet>
11 
12   <servlet-mapping>
13     <servlet-name>ImageServlet</servlet-name>
14     <url-pattern>/imageServlet</url-pattern>
15   </servlet-mapping>
16   <servlet>
17     <servlet-name>CheckServlet</servlet-name>
18     <servlet-class>com.yan.CheckServlet</servlet-class>
19   </servlet>
20 
21   <servlet-mapping>
22     <servlet-name>CheckServlet</servlet-name>
23     <url-pattern>/checkServlet</url-pattern>
24   </servlet-mapping>
25   <welcome-file-list>
26     <welcome-file>index.jsp</welcome-file>
27   </welcome-file-list>
28 </web-app>

ImageServlet

 1 package com.yan;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.servlet.ServletException;
 6 import javax.servlet.http.HttpServlet;
 7 import javax.servlet.http.HttpServletRequest;
 8 import javax.servlet.http.HttpServletResponse;
 9 
10 public class ImageServlet extends HttpServlet{
11 
12     /**
13      * 
14      */
15     private static final long serialVersionUID = 1L;
16     public void doGet(HttpServletRequest request, HttpServletResponse response)
17             throws ServletException, IOException {
18 
19         response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
20         response.setHeader("Pragma", "No-cache");//设置响应头信息,告诉浏览器不要缓存此内容
21         response.setHeader("Cache-Control", "no-cache");
22         response.setDateHeader("Expire", 0);
23         RandomValidateCode randomValidateCode = new RandomValidateCode();
24         try {
25             randomValidateCode.getRandcode(request, response);//输出图片方法
26         } catch (Exception e) {
27             e.printStackTrace();
28         }
29     }
30 
31     public void doPost(HttpServletRequest request, HttpServletResponse response)
32             throws ServletException, IOException {
33         doGet(request, response);
34     }
35 }

RandomValidateCode

  1 package com.yan;
  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.util.Random;
  8 
  9 import javax.imageio.ImageIO;
 10 import javax.servlet.http.HttpServletRequest;
 11 import javax.servlet.http.HttpServletResponse;
 12 import javax.servlet.http.HttpSession;
 13 
 14 public class RandomValidateCode {
 15     public static final String RANDOMCODEKEY = "RANDOMVALIDATECODEKEY";//放到session中的key
 16     private Random random = new Random();
 17     private String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产生的字符串
 18     
 19     private int width = 80;//图片宽
 20     private int height = 26;//图片高
 21     private int lineSize = 40;//干扰线数量
 22     private int stringNum = 4;//随机产生字符数量
 23     /*
 24      * 获得字体
 25      */
 26     private Font getFont(){
 27         return new Font("Fixedsys",Font.CENTER_BASELINE,18);
 28     }
 29     /*
 30      * 获得颜色
 31      */
 32     private Color getRandColor(int fc,int bc){
 33         if(fc > 255)
 34             fc = 255;
 35         if(bc > 255)
 36             bc = 255;
 37         int r = fc + random.nextInt(bc-fc-16);
 38         int g = fc + random.nextInt(bc-fc-14);
 39         int b = fc + random.nextInt(bc-fc-18);
 40         return new Color(r,g,b);
 41     }
 42     /**
 43      * 生成随机图片
 44      */
 45     public void getRandcode(HttpServletRequest request,
 46             HttpServletResponse response) {
 47         HttpSession session = request.getSession();
 48         //BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
 49         BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
 50         Graphics g = image.getGraphics();//产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作
 51         g.fillRect(0, 0, width, height);
 52         g.setFont(new Font("Times New Roman",Font.ROMAN_BASELINE,18));
 53         g.setColor(getRandColor(110, 133));
 54         //绘制干扰线
 55         for(int i=0;i<=lineSize;i++){
 56             drowLine(g);
 57         }
 58         //绘制随机字符
 59         String randomString = "";
 60         for(int i=1;i<=stringNum;i++){
 61             randomString=drowString(g,randomString,i);
 62         }
 63         session.removeAttribute(RANDOMCODEKEY);
 64         session.setAttribute(RANDOMCODEKEY, randomString);
 65         System.out.println(randomString);
 66         g.dispose();
 67         try {
 68             ImageIO.write(image, "JPEG", response.getOutputStream());//将内存中的图片通过流动形式输出到客户端
 69         } catch (Exception e) {
 70             e.printStackTrace();
 71         }
 72     }
 73     /*
 74      * 绘制字符串
 75      */
 76     private String drowString(Graphics g,String randomString,int i){
 77         g.setFont(getFont());
 78         g.setColor(new Color(random.nextInt(101),random.nextInt(111),random.nextInt(121)));
 79         String rand = String.valueOf(getRandomString(random.nextInt(randString.length())));
 80         randomString +=rand;
 81         g.translate(random.nextInt(3), random.nextInt(3));
 82         g.drawString(rand, 13*i, 16);
 83         return randomString;
 84     }
 85     /*
 86      * 绘制干扰线
 87      */
 88     private void drowLine(Graphics g){
 89         int x = random.nextInt(width);
 90         int y = random.nextInt(height);
 91         int xl = random.nextInt(13);
 92         int yl = random.nextInt(15);
 93         g.drawLine(x, y, x+xl, y+yl);
 94     }
 95     /*
 96      * 获取随机的字符
 97      */
 98     public String getRandomString(int num){
 99         return String.valueOf(randString.charAt(num));
100     }
101 }

CheckServlet

package com.yan;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckServlet extends HttpServlet{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException
    {
        System.out.println("CheckServlet");
        String generateCode = (String) request.getSession().getAttribute(RandomValidateCode.RANDOMCODEKEY);
        String inputCode = request.getParameter("randomCode");
        if (generateCode.equalsIgnoreCase(inputCode)) {
            response.getWriter().write("OK!");
        }
    }
}

参考:

Java生成验证码

posted @ 2017-06-29 21:06  舒山  阅读(283)  评论(0编辑  收藏  举报