java实现简单的动态验证码

在服务端实现简单的动态验证码

不废话,直接见代码

1、首先:CheckCodeServlet.java ,实现动态画图功能

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * 实现简单的验证码
 */
@WebServlet("/checkcode")
public class CheckCodeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        int width = 100;
        int height = 50;

        //1.创建一对象,在内存中图片(验证码图片对象)
        BufferedImage image = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);
        //2.美化图片
        //2.1 填充背景色
        Graphics g = image.getGraphics();//画笔对象
        g.setColor(Color.PINK);//设置画笔颜色
        g.fillRect(0,0,width,height);

        //2.2画边框
        g.setColor(Color.BLUE);
        g.drawRect(0,0,width - 1,height - 1);

        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789";
        //生成随机角标
        Random ran = new Random();

        for (int i = 1; i <= 4; i++) {
            int index = ran.nextInt(str.length());
            //获取字符
            char ch = str.charAt(index);//随机字符
            //2.3写验证码
            g.drawString(ch+"",width/5*i,height/2);
        }
        //2.4画干扰线
        g.setColor(Color.GREEN);

        //随机生成坐标点

        for (int i = 0; i < 10; i++) {
            int x1 = ran.nextInt(width);
            int x2 = ran.nextInt(width);

            int y1 = ran.nextInt(height);
            int y2 = ran.nextInt(height);
            g.drawLine(x1,y1,x2,y2);
        }

        //3.将图片输出到页面展示
        ImageIO.write(image,"jpg",response.getOutputStream());

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.doPost(request,response);
    }
}

2、index.html 页面的实现

<%--
  Created by IntelliJ IDEA.
  User: huangshun
  Date: 3/2/19
  Time: 1:51 PM
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
    <script>

      window.onload=function () {
        var checkcode = document.getElementById("checkcode");
        checkcode.onclick=function () {
          var date=new Date().getTime();
          checkcode.src="/checkcode?"+date;
        }
        var ahref = document.getElementById("change");
        ahref.onclick=function () {
          var date=new Date().getTime();
          checkcode.src="/checkcode?"+date;

        }

      }
    </script>
  </head>
  <body>
  <p>二维码的简单实现<p/>
  <img src="/checkcode" id="checkcode"/>
  <a  id="change" href="#">换一张</a>

  </body>
</html>

二 , 还可以通过session  在服务器端存储生成的验证码与客户端提交的验证码进行校验,这里链接数据库的操作就不进行了,简单使用request 和session 域对象

1)CheckCodeServlet.java

package ImgCode;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        int width = 100;
        int height = 50;

        //1.创建一对象,在内存中图片(验证码图片对象)
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);


        //2.美化图片
        //2.1 填充背景色
        Graphics g = image.getGraphics();//画笔对象
        g.setColor(Color.PINK);//设置画笔颜色
        g.fillRect(0,0,width,height);

        //2.2画边框
        g.setColor(Color.BLUE);
        g.drawRect(0,0,width - 1,height - 1);

        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789";
        //生成随机角标
        Random ran = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= 4; i++) {
            int index = ran.nextInt(str.length());
            //获取字符
            char ch = str.charAt(index);//随机字符
            sb.append(ch);

            //2.3写验证码
            g.drawString(ch+"",width/5*i,height/2);
        }
        String checkCode_session = sb.toString();
        //将验证码存入session
        request.getSession().setAttribute("checkCode_session",checkCode_session);

        //2.4画干扰线
        g.setColor(Color.GREEN);

        //随机生成坐标点

        for (int i = 0; i < 10; i++) {
            int x1 = ran.nextInt(width);
            int x2 = ran.nextInt(width);

            int y1 = ran.nextInt(height);
            int y2 = ran.nextInt(height);
            g.drawLine(x1,y1,x2,y2);
        }


        //3.将图片输出到页面展示
        ImageIO.write(image,"jpg",response.getOutputStream());


    }

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

2)LoginServlet.java

package ImgCode;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String check_code = request.getParameter("check_code");
        System.out.println("username="+username+"--password="+password+"--check_code="+check_code);
        // 1 先取出 session 里面的 验证码
        HttpSession session = request.getSession();
        String web_check_code = (String)session.getAttribute("checkCode_session");
        session.removeAttribute("web_check_code");// 清除服务器端session
        if(web_check_code!=null && web_check_code.equalsIgnoreCase(check_code)){
            // 验证码相等 验证用户名
            if("admin".equals(username) && "admin".equals(password)){
                System.out.println("登录成功");
                //response.getWriter().write("<h1>登录成功</h1>");
                session.setAttribute("username",username);
                response.sendRedirect(this.getServletContext().getContextPath()+"/success.jsp");//重定向
                System.out.println(this.getServletContext().getContextPath()+"/success.jsp");

            }else{
                request.setAttribute("login_msg","用户名或密码错误,请重试");
                request.getRequestDispatcher("/index.jsp").forward(request,response);
                System.out.println("用户名或者密码错误");
            }

        }else{
            request.setAttribute("login_msg","验证码错误,请重试");
            request.getRequestDispatcher("/index.jsp").forward(request,response);

            System.out.println("验证码错误");
        }






    }

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

3)success.jsp

<%--
  Created by IntelliJ IDEA.
  User: huangshun
  Date: 3/4/19
  Time: 8:55 AM
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <%
    HttpSession session1 = request.getSession();
    String username = (String)session1.getAttribute("username");

  %>
  欢迎你:<%= username%>
  </body>
</html>

4)index.jsp

<%--
  Created by IntelliJ IDEA.
  User: huangshun
  Date: 3/4/19
  Time: 8:55 AM
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
    <script>
      window.onload=function () {
        var check_code = document.getElementById("check_code");
        check_code.onclick=function () {
          check_code.src="/checkCodeServlet?"+new Date().getTime();
        }
      }
    </script>

  </head>
  <body>
  <form action="/LoginServlet" method="post">
    <table>
      <tr>
        <td>姓名</td>
        <td><input type="text" name="username"></td>
      </tr>
      <tr>
        <td>密码</td>
        <td><input type="password" name="password"></td>
      </tr>
      <tr>
        <td>验证码</td>
        <td><input type="text" name="check_code"></td>
      </tr>

    </table>
    <img src="/checkCodeServlet" id="check_code"/>
    <input type="submit" value="提交"/>
    <%
      String login_msg = (String)request.getAttribute("login_msg");
    %>
    <%= login_msg%>
  </form>
  </body>
</html>

路径的话.可能需要自己配置下

猜你喜欢

转载自blog.csdn.net/huangshun9541/article/details/88075390