www.bersaty.com

Servlet学习-登录验证码的实现

java的画图原理

//生成验证码的servlet
public
class CreateCode extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //禁止浏览器缓存随机图片 response.setDateHeader("Expires", -1); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma","no-cache"); //通知客户机以图片的方式打开发送过去的数据 response.setHeader("Control-Type", "image/jpeg"); //在内存中创建一幅图片 BufferedImage image= new BufferedImage(80,30, BufferedImage.TYPE_INT_RGB); //创建画笔 Graphics g = image.getGraphics(); //设置背景色 g.setColor(Color.GRAY); g.fillRect(0, 0, 80, 30); //设置写入数据的颜色和字体 g.setColor(Color.blue); g.setFont(new Font(null,Font.BOLD,20)); //向图片上写数据 String num = makeNum(); //把随机生成的数据保存到session,用于验证 request.getSession().setAttribute("checkcode", num); g.drawString(num, 0, 20); //把写好数据的图片输出到浏览器 ImageIO.write(image, "jpg", response.getOutputStream()); } //生成随机数 public String makeNum() { Random r = new Random(); String num = r.nextInt(9999)+""; StringBuffer str=new StringBuffer(); for(int i=0;i<4-num.length();i++){ str.append("0"); } num = str.toString()+num; return num; } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }

调用的servlet:

//获取验证码
        String checkcode = (String) request.getSession().getAttribute("checkcode");//随机生成的
        String checkcode2 = request.getParameter("checkcode");//获取输入的
        
        if(checkcode.equals(checkcode2))//如果验证码正确
        {
            ;
        }else{
            request.setAttribute("error", "验证码错误!");
            //本地用getRequestDispatcher 效率高
            request.getRequestDispatcher("/LoginServlet").forward(request, response);
            return;
        }
//do something here

 主页显示调用画的jpg图片:

        out.println("<input type = 'checkbox' name='iskeep' value=keep>保存用户名和密码</br>");

 

 

 

 

posted @ 2013-07-29 18:41  bersaty  阅读(1811)  评论(0编辑  收藏  举报