如果生成动态验证码

来源:互联网 发布:淘宝上十个最辣的零食 编辑:程序博客网 时间:2024/05/15 13:59

为了防止某些用户使用软件进行登录和发布信息,很多网站在用户登录或者发布信息时,都要求用户输

入验证码,验证码通是以一幅图片形式显示的。用户按照图片中显示的数字或字母依次输入,服务器站

将对用户的输入进行比较,以判断用户是否经过验证。由于验证码是随机产生的。自动发布信息的软件

无法知道每次产生的验证码。也就无法自动发布信息了。
  实例开发主要以下步骤。
Step1:编写RandomCodeServlet.java
RandomCodeServelt 类动态生成随机的验证码,然后以图片形式输出到客户端。
             〈〈-------以下是详细代码---------〉〉

package pethospital;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.imageio.ImageIO;

public class RandomCodeServlet extends HttpServlet {
    private static final String CONTENT_TYPE = "text/html; charset=GBK";
       //验证码的高度
    private int width=60;
       //验证码的宽度
    private int height=20;
    protected void service(HttpServletRequest req,HttpServletResponse resp)
            throws ServletException,java.io.IOException
    {
        BufferedImage buffImg = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics2D g=buffImg.createGraphics();
          //创建一个随机数生成器类
        Random random = new Random();
        g.setColor(Color.WHITE);
        g.fillRect(0,0,width,height);
            //创建字体,字体大小应该根据图片高度来定。
        Font font = new Font("Times New Roman",Font.PLAIN,18);
            //设置字体
        g.setFont(font);
             //画边框
        g.setColor(Color.BLACK);
        g.drawRect(0,0,width-1,height-1);
        g.setColor(Color.GRAY);
           //随机产生160条干扰线,使图像中的认证码不易被其它程序探测到
        for(int i =0;i<160;i++)
        {
            int x=random.nextInt(width);
            int y=random.nextInt(height);
            int x1=random.nextInt(12);
            int y1=random.nextInt(12);
            g.drawLine(x,y,x+x1,y+y1);
        }
              //randomcode用于保存随机产生的验证码,以便于用户登录后进行验证
        StringBuffer randomCode = new StringBuffer();
        int red=0,green=0,blue=0;
           //随机产生四位数的验证码
        for(int i=0;i<4;i++)
        {
                  //得到随机产生的验证码数字
            String strRand=String.valueOf(random.nextInt(10));
                  //  生随机颜色的分量来构造色值,这样输出的每们数字的颜色值都将不同
            red=random.nextInt(110);
            green=random.nextInt(50);
            blue=random.nextInt(50);
               //用随机产生的颜色将验证码绘制到图像中
            g.setColor(new Color(red,green,blue));
            g.drawString(strRand,13*i+6,16);
              //产生四个随机数字组合在一起
            randomCode.append(strRand);
        }
                 //将四位数字的验证码保存到Session里面
       HttpSession session =req.getSession();
       session.setAttribute("randomCode",randomCode.toString());
          //禁止图像缓存
       resp.setHeader("Prama","no-cache");
       resp.setHeader("Coche-Control","no-cache");
       resp.setDateHeader("Expires",0);
       resp.setContentType("image/jpeg");
            //将图像输出到Servelt输出流中
       ServletOutputStream sos=resp.getOutputStream();
       ImageIO.write(buffImg,"jpeg",sos);
       sos.close();

    }
    //Initialize global variables
    public void init() throws ServletException {
    }

    //Process the HTTP Get request
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        response.setContentType(CONTENT_TYPE);
    }

    //Process the HTTP Post request
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        doGet(request, response);
    }

    //Clean up resources
    public void destroy() {
    }
}

在这个代码中,使用的是javax.imageio.ImageIO.write()方法将包含了验证码的图像数据输出到客户端

Step2:编写Login.jsp
   login.jsp是一个登录页面,用户登录时,需要输入图像中的验证码,服务器端的程序在得到用户输

入的验证码后,与保存在Session中的验证码进行对比。

</head>
<body bgcolor="#ffffff">
<br/>
<br/>
<br/>
<%if (request.getAttribute("msg") == null) {%>
<%} else {%>
<h1 align="center"><%=request.getAttribute("msg")%></h1>
<%}%>
<h1 align="center">员工登录</h1>
<form action="loginchk" method="POST" name="frm">
<table align="center" bgcolor="#00800">
  <tr bgcolor="#cccccc">
    <td>用户名称:</td>
    <td>
      <input type="text" name="username"/>
    </td>
  </tr>
  <tr bgcolor="#cccccc">
    <td>口令:</td>
    <td>
      <input type="password" name="password" maxlength="16"/>
    </td>
  </tr>
  <tr>
      <td>验证码:</td>
    <td>
     <input type="text",name="random",maxlength="4">
     <img src="imgcode">   
    </td>
  </tr>
</table>
<table align="center">
  <tr>
    <td align="center">      &nbsp;&nbsp;&nbsp;
      <input type="submit" name="submit" value="提交"/>
      &nbsp;&nbsp;&nbsp;
      <input type="reset" name="reset" value="重置"/>
    </td>
  </tr>
</table>
</form>
</body>
</html>


Step3:编写LoginCheckServlet.java
  这个Servlet类用于对用户输入的验证码时行校验,它首先从请求对象中得到用户输入的验证码,然后

与保存在Session中的验证码进行比对。看是否一致。为简单起见,这个类仅仅实现了验证码的校验。对

于用户名和密码没有做任何处理。


import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.sql.*;
import java.sql.PreparedStatement;

public class LoginCheckServlet extends HttpServlet {
    private static final String CONTENT_TYPE = "text/html; charset=GBK";

    //Initialize global variables
    public void init() throws ServletException {
    }

    //Process the HTTP Get request
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        j
        response.setContentType(CONTENT_TYPE);
        PrintWriter out = response.getWriter();
        request.setCharacterEncoding("GBK");
        HttpSession session = request.getSession();
         String randomCode=(String)session.gerAttribute("randomCode");
           if(null==randomCode)
                {
                   resp.sendRedirect("Login.jsp");
                         return;
                }
              String reqRandom=req.getParameter("random");
                
            if (randomCode.equals(reqRandom))
            {
                 out.print("验证码匹配");
            }
            else
            {
                 out.print("验证码校验失败,请返回重新登录");
            }
    }

    //Process the HTTP Post request
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {

        doGet(request, response);
    }

    //Clean up resources
    public void destroy() {
    }
}

Step4:部署Servlet
编辑WEB-INF\web.xml文件,添加本例中的Servlet  的配置


……
<servlet>
    <servlet-name>randomcodeservlet</servlet-name>
    <servlet-class>RandomCodeServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>randomcodeservlet</servlet-name>
    <url-pattern>/imgCode</url-pattern>
  </servlet-mapping>

<servlet>
    <servlet-name>LoginCheckServlet</servlet-name>
    <servlet-class>LoginCheckServlet</servlet-class>
  </servlet>
  <serv
……
谢谢~~~~~~~~~~~!!!!!!!

原创粉丝点击