Java实现后台产生验证码前台检测登录

话不多说,直接上代码:

package com.ioe.utils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * <h3>TestService</h3>
 * <p>生成验证码工具</p>
 *
 * @author : zhangmin
 * @date : 2019-04-09 15:19
 **/
public class CheckCode {
    private int width;
    private int height;
    private int num;
    private String code;
    private static final Random ran=new Random();
    /**
     * 单例模式获取对象方法
     */
    private static CheckCode checkCode;
    private CheckCode(){
        code="012345789ABCDEFGHIJKLMNOPQRSTUVWSYZ";
        num=4;
    }
    public static CheckCode getInstance(){
        if(checkCode==null){
            checkCode=new CheckCode();
        }
        return checkCode;
    }
    public void set(int width,int height,int num,String code){
        this.width=width;
        this.height=height;
        this.setNum(num);
        this.setCode(code);
    }

    public void set(int width, int height) {
        this.width = width;
        this.height = height;
    }

    public int getWidth() {
        return width;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String generateCheckCode(){
        StringBuffer cc = new StringBuffer();
        for(int i=0;i<num;i++){
            cc.append(code.charAt(ran.nextInt(code.length())));
        }
        return cc.toString();
    }

    /**
     * 画画
     * @param checkcode 验证码
     * @return img
     */
    public BufferedImage generateCheckImg(String checkcode){
        //创建一个图片对象
        BufferedImage img = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics2D graphic =img.createGraphics();
        graphic.setColor(Color.WHITE);
        graphic.fillRect(0,0,width,height);
        graphic.setColor(Color.BLACK);
        graphic.drawRect(0,0,width-1,height-1);
        Font font =new Font("微软雅黑",Font.BOLD+Font.ITALIC,(int)(height*0.8));
        graphic.setFont(font);
        for(int i=0;i<num;i++){
            graphic.setColor(new Color(ran.nextInt(155),ran.nextInt(255),ran.nextInt(255)));
            graphic.drawString(String.valueOf(checkcode.charAt(i)),i*(width/num)+4,(int)(height*0.8));
        }
        //加一些点
        for(int i=0;i<(width+height);i++){
            graphic.setColor(new Color(ran.nextInt(155),ran.nextInt(255),ran.nextInt(255)));
            graphic.drawOval(ran.nextInt(width),ran.nextInt(height),1,1);
        }
        //加一些线
        for(int i=0;i<2;i++){
            graphic.setColor(new Color(ran.nextInt(155),ran.nextInt(255),ran.nextInt(255)));
            graphic.drawLine(0,ran.nextInt(height),width,ran.nextInt(height));
        }
        return img;
    }

}

以上就是产生验证码代码
再通过servlet获取随机产生的代码:

package com.ioe.servlets;

import com.ioe.utils.CheckCode;

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.io.IOException;
import java.io.OutputStream;

/**
 * <h3>TestService</h3>
 * <p>DrawCode</p>
 *
 * @author : zhangmin
 * @date : 2019-04-09 15:31
 **/

@WebServlet("/drawCode")
public class DrawCode extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       resp.setContentType("img/jpg");
       int width=150;
       int height=40;
       //具体实现验证码
       CheckCode c= CheckCode.getInstance();
       c.set(width,height);
       String cc = c.generateCheckCode();
       req.getSession().setAttribute("checkcode",cc);
        OutputStream os = resp.getOutputStream();
        ImageIO.write(c.generateCheckImg(cc),"jpg",os);
    }
}

前台进行检测,直接检测结果之后该如何跳转,取决于具体需求:

package com.ioe.servlets;

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;

/**
 * <h3>TestService</h3>
 * <p>检查输入验证码是否正确</p>
 *
 * @author : zhangmin
 * @date : 2019-04-09 16:56
 **/

@WebServlet("/check")
public class CheckingCode extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String cc =req.getParameter("checkcode");
        String scc = (String)req.getSession().getAttribute("checkcode");
        resp.setCharacterEncoding("utf-8");
        if(!cc.equals(scc)){
           // String note ="验证码错误";
            resp.sendRedirect("/login.html");
        }else{
            resp.sendRedirect("/main.html");
            //System.out.println("验证码正确");
        }
    }
}

前台可以这样获取servlet的url:

 <%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2019/4/9 0009
  Time: 15:25
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>用户登录</title>
</head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<form action="<%=request.getContextPath()%>/check">
    <h2>用户登录</h2>
  请输入验证码: <input type="text" name="checkcode"><a href="login.jsp"><img src="<%=request.getContextPath()%>/drawCode"></a>
   <br><br>
    <input type="submit" value="登录">
</form>
</body>
</html>

最后可以看一下效果图,感觉还是可以的

虽然有点简陋,但还是可以的,本博客主要针对验证码的实现过程,望谅解,感兴趣的朋友可以了解一下。

猜你喜欢

转载自blog.csdn.net/weixin_43734184/article/details/89233339