servlet实现验证码登陆功能

验证码登陆还是很常用的功能。今天用servelt实现了一下,验证码的实现代码是我综合了网上和学习视频的代码整合而成。先看一下效果图。
测试效果:
在这里插入图片描述
使用模板后的效果:
在这里插入图片描述
前端的登陆页面如下:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
  <form action="/login" method="post">
      姓名:<input name="name" type="text"><br><br>
      密码:<input name="password" type="password"><br><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
      <input name="vericode" placeholder="验证码" value="" style="width: 60px">&nbsp;&nbsp;
      <img id="vericodeImg" src="imageCode">&nbsp;&nbsp;
      <a id="kanbuq" href="javascript:changeImg();">看不清,换一张</a><br><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
      <input type="submit" value="提交">
  </form>
  <%--需要将jquery下载到本地,再在页面中引用--%>
  <script type="text/javascript" src="lib/jquery/jquery-3.4.1.min.js"></script>
  <script type="text/javascript">
      function changeImg() {
          //需要让每次请求的url都发生变化。否则服务器会认为访问的时一张图片,就不会刷新请求了
          //每次url一样,服务器会认为访问的url是同一张图片,没变化啊
          $("#vericodeImg").attr("src","imageCode?"+Math.random())
      }
  </script>
</body>
</html>

后端的LoginServlet登陆实现逻辑如下:

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf8");
        String name=req.getParameter("name");
        String password=req.getParameter("password");
        String vericode=req.getParameter("vericode");
        String generatedCode= (String) req.getSession().getAttribute("verityCode");
        if (name.equals("bob")&&password.equals("123")&&vericode.toLowerCase().equals(generatedCode.toLowerCase())){
            resp.getWriter().write("登录成功");
        }else {resp.getWriter().write("登录失败");}
    }
}

下面是两个工具代码:一个是生成验证码字符串,一个是生成验证码图片(它是基于生成验证码字符串类的)

public class CreateVerificationCode {
    /**
     * 验证码难度级别
     */
    public enum SecurityCodeLevel {
        Simple,
        Medium,
        Hard
    }

    public static String getSecurityCode() {
        return (String) getSecurityCode(4, SecurityCodeLevel.Medium, false);
    }

    public static String getSecurityCode(int length, SecurityCodeLevel level, boolean isCanRepeat) {
        int len = length;
        //除去容易混淆的0和o,1和l
        char[] codes = {
                '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
                'j', 'm', 'n', 'p', 'q', 'r', 's', 't','u',
                'v', 'w', 'x', 'y', 'z','A','B','C','D','E',
                'F','G','H','J','K','L','M','N','P','Q','R','S',
                'T','U','V','W','X','Y','Z'};
        if(level==SecurityCodeLevel.Simple){
            codes= Arrays.copyOfRange(codes,0,9);
        }else if (level==SecurityCodeLevel.Medium){
            codes= Arrays.copyOfRange(codes,0,33);
        }
        int n=codes.length;
        //抛出运行时异常
        if (len>n&&isCanRepeat==false){
            throw new RuntimeException(
                    String.format("调用securitycode.getSecurityCode(%1$s,len,level,isCanRepeat,n)"));}
                    char[] result=new char[len];
        //判断能否出现重复的字符
        if (isCanRepeat){
            for(int i=0;i<result.length;i++){
                //索引0 and n-1
                int r=(int)(Math.random()*n);
                //将result中的第i个元素设为codes[r]存放的数值
                result[i]=codes[r];
            }
        }else {
            for (int i=0;i<result.length;i++){
                int r=(int)(Math.random()*n);
                //将result中的第i个元素设为codes[r]存放的数值
                result[i]=codes[r];
                codes[r]=codes[n-1];
                n--;
            }
        }
        return String.valueOf(result);
        }
}
package com.bbs.utils.validCode;

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

/**
 * 可生成数字,大写,小写字母及三者混合类型的验证码,支持自定义干扰线,图文颜色
 */
public class CreateVerificationCodeImage {
    private String securityCode;
    public CreateVerificationCodeImage(String securityCode){
        this.securityCode=securityCode;
    }
    //高度
    private static final int CAPTCHA_HEIGHT = 35;
    //宽度
    private static final int CAPTCHA_WIDTH  = 100;
    //数字的长度
    //private static final int NUMBER_CNT     = 6;
    private Random r = new Random();
    //  字体
    private String[] fontNames = { "宋体", "华文楷体", "黑体", "华文新魏", "华文隶书", "微软雅黑", "楷体_GB2312" };
    //private String[] fontNames = { "宋体",  "黑体", "微软雅黑"};

    /**
     * 机能概要:生成随机的颜色
     * @return
     */
    private Color randomColor() {
        int red = r.nextInt(150);
        int green = r.nextInt(150);
        int blue = r.nextInt(150);
        return new Color(red, green, blue);
    }

    /**
     * 机能概要:生成随机的字体
     * @return
     */
    private  Font randomFont() {
        int index = r.nextInt(fontNames.length);
        String fontName = fontNames[index];// 生成随机的字体名称
        int style = r.nextInt(4);// 生成随机的样式, 0(无样式), 1(粗体), 2(斜体), 3(粗体+斜体)
        int size = r.nextInt(5) + 24; // 生成随机字号, 24 ~ 28
       // int size = r.nextInt(5) + 15; // 生成随机字号, 20 ~ 24
        return new Font(fontName, style, size);
    }

    // 画干扰线
    private  void drawLine(BufferedImage image) {
        int num = 5;// 一共画5条
        Graphics2D g2 = (Graphics2D) image.getGraphics();
        for (int i = 0; i < num; i++) {// 生成两个点的坐标,即4个值
            int x1 = r.nextInt(CAPTCHA_WIDTH);
            int y1 = r.nextInt(CAPTCHA_HEIGHT);
            int x2 = r.nextInt(CAPTCHA_WIDTH);
            int y2 = r.nextInt(CAPTCHA_HEIGHT);
            g2.setStroke(new BasicStroke(1.5F));
            g2.setColor(randomColor()); // 随机生成干扰线颜色
            g2.drawLine(x1, y1, x2, y2);// 画线
        }
    }
    // 创建BufferedImage,生成图片
    public BufferedImage createImage() {
        BufferedImage image = new BufferedImage(CAPTCHA_WIDTH, CAPTCHA_HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = (Graphics2D) image.getGraphics();
        // 背景色,白色
        g2.setColor(new Color(255, 255, 255));
        g2.fillRect(0, 0, CAPTCHA_WIDTH, CAPTCHA_HEIGHT);

        // 向图片中画4个字符  String securityCode
        for (int i = 0; i < securityCode.length(); i++) {// 循环四次,每次生成一个字符
            String s = securityCode.charAt(i) + "";// 随机生成一个字母
           // float x = i * 1.0F * CAPTCHA_WIDTH / NUMBER_CNT; // 设置当前字符的x轴坐标
            float x = i * 1.0F * CAPTCHA_WIDTH / 4+7F; // 设置当前字符的x轴坐标
            g2.setFont(randomFont()); // 设置随机字体
            g2.setColor(randomColor()); // 设置随机颜色
            g2.drawString(s, x, CAPTCHA_HEIGHT-7); // 画图,依次将字符写入到图片的相应位置-------------------
        }
        drawLine(image); // 添加干扰线
        return image;
    }
}

调用工具类的生成验证码图片的方法,在通过response对象,将图片流返回给前端,有img标签的src属性负责解析

@WebServlet("/imageCode")
public class ImageCodeServelt extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       String vericode= CreateVerificationCode.getSecurityCode();
        HttpSession session=req.getSession();
        session.setAttribute("verityCode",vericode);
        //设置返回的内容
        resp.setContentType("img/jpeg");
        //浏览器不缓存响应内容--验证码图片,点一次就要刷新一次,所以不能有缓存出现
        resp.setHeader("Pragma","No-cache");
        resp.setHeader("Cache-Control","no-cache");
        //设置验证码失效时间
        resp.setDateHeader("Expires",0);
        //以字节流发过去,交给img的src属性去解析即可
        ImageIO.write(new CreateVerificationCodeImage(vericode).createImage(),"JPEG",resp.getOutputStream());
    }
}
  • 20
    点赞
  • 81
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值