google kaptcha 验证码的使用

这边演示下idea+maven+servlet实现谷歌的kaptcha验证码的使用:

web.xml, 这边主要是kaptcha验证器,

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <servlet-name>validcode</servlet-name>
    <servlet-class>ValidCode</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>validcode</servlet-name>
    <url-pattern>/validcode</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>kaptcha</servlet-name>
    <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
    <init-param>
      <param-name>kaptcha.border</param-name>
      <param-value>no</param-value>
    </init-param>
    <init-param>
      <param-name>kaptcha.border.color</param-name>
      <param-value>105,179,90</param-value>
    </init-param>
    <init-param>
      <param-name>kaptcha.textproducer.font.color</param-name>
      <param-value>red</param-value>
    </init-param>
    <init-param>
      <param-name>kaptcha.image.width</param-name>
      <param-value>100</param-value>
    </init-param>
    <init-param>
      <param-name>kaptcha.image.height</param-name>
      <param-value>45</param-value>
    </init-param>
    <init-param>
      <param-name>kaptcha.textproducer.font.size</param-name>
      <param-value>35</param-value>
    </init-param>
    <!-- 配置session的存储的KEY -->
    <init-param>
      <param-name>kaptcha.session.key</param-name>
      <param-value>session_code</param-value>
    </init-param>
    <init-param>
      <param-name>kaptcha.textproducer.char.length</param-name>
      <param-value>4</param-value>
    </init-param>
    <init-param>
      <param-name>kaptcha.textproducer.font.names</param-name>
      <param-value>宋体,楷体,微软雅黑</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>kaptcha</servlet-name>
    <url-pattern>/code</url-pattern>
  </servlet-mapping>
</web-app>

然后是maven依赖,引入kaptcha, 阿里的快速json,以及apache的io流,

因为kaptcha依赖我这边下不下来所以就下载下来放在lib里面再导入,如图:

 

maven依赖如下:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.linewell</groupId>
  <artifactId>Kaptcha</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>Kaptcha Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>
    <dependency>
      <groupId>com.google.code</groupId>
      <artifactId>kaptcha</artifactId>
      <version>2.3.2</version>
      <scope>system</scope>
      <systemPath>${project.basedir}/src/main/webapp/WEB-INF/lib/kaptcha-2.3.2.jar</systemPath>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.54</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.6</version>
    </dependency>
  </dependencies>

  <build>
    <finalName>Kaptcha</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

 

前端的jsp代码如下:

<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>

</head>
<body>
<div style="width: 100%; margin-top: 30px;" align="center" >
    <div class="form-inline">
        <input type="text" id="text" class="form-control" style="width: 150px"/>
        <img id="img" src="/code" alt="picture dismiss" />
    </div>
    <div class="form-inline" style="margin-top: 15px;"><input type="button" id="sub" value="submit" class="btn-primary" style="width: 100px;"/></div>
</div>

<script>
    $(function () {
        $("#img").bind("click", function () {
            $("#img").attr("src", "/code?"+new Date().getTime());
            console.log($('#img').attr("src"));
        });

        $("#sub").click(function () {

            var input = $("#text").val();
            console.log(input);

            var data = {};
            data.code = input;
            $.ajax({
                type:"post",
                dataType: "json",
                url : "/validcode",
                contentType:"application/json; charset=utf-8",
                data: JSON.stringify(data),
                success: function (t) {
                    alert(t.msg);
                },
                failure: function (data) {
                    console.log(data);
                }
            });

        });
    });
</script>

</body>
</html>

 

后台测试的servlet如下:

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

public class ValidCode extends HttpServlet {
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
            throws IOException
    {
        InputStream inputStream = request.getInputStream();
        String bodyInfo = IOUtils.toString(inputStream, "utf-8");
        System.out.println(bodyInfo);
        JSONObject jsonObject = JSONObject.parseObject(bodyInfo);
        String code = jsonObject.getString("code");
        String attribute = (String) request.getSession().getAttribute("session_code");
        Data data = new Data();
        if(code.equals(attribute)){
            System.out.println("验证码正确!");
            data.setMsg("success");
        }else {
            System.out.println("验证码输入错误");
            data.setMsg("fail");
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        String jsonString = JSONObject.toJSONString(data);
        PrintWriter writer = response.getWriter();
        writer.write(jsonString);

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

}

class Data{
    private String msg;
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
}

 

最后的效果展示:

 

posted @ 2018-12-17 20:53  护花使者  Views(1975)  Comments(0Edit  收藏  举报