验证码

Posted zhai1997

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了验证码相关的知识,希望对你有一定的参考价值。

1、书写servlet,获取验证码的数据,并对验证码进行校验

public class ValidateServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    
            
            String code = request.getParameter("code");
    
            HttpSession session = request.getSession();
            String randStr = (String)session.getAttribute("randStr");
            response.setCharacterEncoding("gb2312");
            PrintWriter out = response.getWriter();
            if(!code.equals(randStr)){
                out.println("验证码错误");
            }
            else{
                out.println("验证码正确......");
            }        
        
    }

}

 

2、创建登录界面

<%@ page language="java" pageEncoding="gb2312"%>
<html>
    <body>
    <script type="text/javascript">
        function refresh(){
        
    document.getElementById("imgValidate").src="validate.jsp?random="+Math.random();
        }
    </script>
    欢迎登录本系统<BR>
    <form name="loginForm" action="ValidateServlet" method="post">
        请您输入账号:<input type="text" name="account" /><BR>
        请您输入密码: <input type="password" name="password" /><BR>
        请输入验证码:<input type="text" name="code" size="10"/>
        <img name="imgValidate"  id="imgValidate" src="validate.jsp" onclick="refresh()"/><BR>
        <input type="submit" value="登录"/>    
    </form>        
    </body> 
</html>

点击验证码的图片之后会调用validate.jsp生成验证码,但是,在这个过程中会传递一个随机数,在validate.jsp中对数据进行模糊处理,并将数据存储在session中。

 

3、创建生成验证码图片的jsp

<%@ page language="java"
    import="java.awt.*"
    import="java.awt.image.BufferedImage"
    import="java.util.*"
    import="javax.imageio.ImageIO"    
    pageEncoding="gb2312"%>
<%
    response.setHeader("Cache-Control","no-cache"); 
    // 在内存中创建图象 
    int width = 60, height = 20;
    BufferedImage image = new BufferedImage(width, height,
        BufferedImage.TYPE_INT_RGB);
    //获取画笔
    Graphics g = image.getGraphics();
    //设定背景色 
    g.setColor(new Color(200, 200, 200));
    g.fillRect(0, 0, width, height);
    //取随机产生的验证码(4位数字) 
    Random rnd = new Random();
    int randNum = rnd.nextInt(8999) + 1000;
    String randStr = String.valueOf(randNum);
    //将验证码存入session
    session.setAttribute("randStr", randStr);
    //将验证码显示到图象中 
    g.setColor(Color.black);
    g.setFont(new Font("", Font.PLAIN, 20));
    g.drawString(randStr, 10, 17);
    // 随机产生100个干扰点,使图象中的验证码不易被其他程序探测到 
    for (int i = 0; i < 100; i++){
        int x = rnd.nextInt(width);
        int y = rnd.nextInt(height);
        g.drawOval(x, y, 1, 1);
    }
    // 输出图象到页面 
    ImageIO.write(image, "JPEG", response.getOutputStream());
    out.clear();
    out = pageContext.pushBody();
%>

 

4、创建servlet,获取到验证码中的数据

public class ValidateServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    
            
            String code = request.getParameter("code");
    
            HttpSession session = request.getSession();
            String randStr = (String)session.getAttribute("randStr");
            response.setCharacterEncoding("gb2312");
            PrintWriter out = response.getWriter();
            if(!code.equals(randStr)){
                out.println("验证码错误");
            }
            else{
                out.println("验证码正确......");
            }        
        
    }

}

在该servlet中获取登录页面提交的验证码数据,并获取session中的数据,进行比对。成功的话就登录成功,否则,失败

 

5、在web.xml中配置servlet

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>yanzheng</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
      <servlet-name>ValidateServlet</servlet-name>
      <servlet-class>pers.zhb.test.ValidateServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>ValidateServlet</servlet-name>
      <url-pattern>/ValidateServlet</url-pattern>
  </servlet-mapping>
</web-app>

 

以上是关于验证码的主要内容,如果未能解决你的问题,请参考以下文章

git动态验证码

Android SMS Verification API 结果码始终为 0

爬虫遇到头疼的验证码?Python实战讲解弹窗处理和验证码识别

JavaScript 有用的代码片段和 trick

pbootcms对接微信扫码登录代码核心片段和步骤(前后端)

如何用JS代码判断验证码输入是不是正确