javaee添加验证码

package com.zh.code;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.jms.Session;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class CreateCode extends HttpServlet {


    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        response.setContentType("text/html");
        response.setHeader("Content", "image/jpeg");
        //7.禁止浏览器缓存 随机图片
        response.setDateHeader("Expires", -1);
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        
        //1.创建一个图片的内在 bufferedImage
        //BufferedImage image=new BufferedImage(80, 30, BufferedImage.TYPE_INT_ARGB);
        BufferedImage image=new BufferedImage(50,30 , BufferedImage.TYPE_INT_BGR);
        //        
        //2.得到image的画笔
        Graphics g=image.getGraphics();
        g.setColor(Color.CYAN);
        g.fillRect(0, 0, 50, 30);
        //在上面写数字 
        g.setColor(Color.BLACK);
        g.setFont(new Font(null,Font.BOLD,20));
        String num=this.getCodeNum();
        g.drawString(num, 0, 20);
        
        
        //把得到的 验证码存在session中
        request.getSession().setAttribute("code", num);
        
        //3.图片发送
         ImageIO.write(image, "jpg", response.getOutputStream());
    }
    //返回的随机数据字符串
    public String getCodeNum(){
        Random randow=new Random();
        String num=randow.nextInt(9999)+"";
        StringBuffer stringBuffer=new StringBuffer("");
        for(int i=0;i<4-num.length();i++){
            stringBuffer.append("0");
        }
        num+=stringBuffer;
        return num;
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        this.doGet(request, response);
        
    }

}

 

posted on 2013-11-13 12:34  邵邵  阅读(618)  评论(0编辑  收藏  举报

淘宝美工兼职招聘