CSDN博客

img yangtom

页面数字验证主程序

发表于2004/10/19 19:37:00  540人阅读

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Font;
import java.util.Random;
import javax.imageio.ImageIO;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.image.codec.jpeg.JPEGCodec;
import javax.servlet.ServletOutputStream;

public class CheckCode extends HttpServlet {
  private Font imgFont = new Font("宋体",Font.BOLD,16); //设置字体

        public void doGet(HttpServletRequest request,HttpServletResponse response)
          throws ServletException,IOException
        {
                doPost(request,response);
        }

        public void doPost(HttpServletRequest request,HttpServletResponse response)
          throws ServletException,IOException
        {
          String session_name = request.getParameter("session_name");

          String vCode = "";
          int  intCode = 0;


          intCode = (new Random()).nextInt(9999);
          if(intCode<1000)
             intCode += 1000;
          vCode = intCode+"";

          /*
           * 绘图
           */
          int width = 50;
          int height = 20;
          response.setContentType("image/gif");
          ServletOutputStream vout = response.getOutputStream();
          BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
          Graphics graph = image.getGraphics();// 获取图形上下文

          // 设置背景颜色
          graph.setColor(Color.white);
          graph.fillRect(1,1,48,18);

          // 将认证码显示到图象中
          //设置字体颜色
          graph.setColor(Color.black);
          graph.setFont(imgFont);
          graph.drawString(vCode,10,15);
//                char c;
//                for(int i=0;i<4;i++)
//                {
//                        c = vCode.charAt(i);
//                        graph.drawString(c+"",9*i+4,16);
//                }

          // 图象生效
          //graph.dispose();
          // 输出图象到页面
          //ImageIO.write(image, "JPEG", response.getOutputStream());
          JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(vout);
          encoder.encode(image);

          // 对session赋值
          if(session_name==null || session_name.equals("")){
            session_name = "CheckCode";
          }
          System.out.println("session_name: "+session_name);
          HttpSession session = request.getSession(true);
          session.removeAttribute(session_name);
          session.setAttribute(session_name, vCode);

          vout.close();
        }


}

阅读全文
0 0

相关文章推荐

img
取 消
img