Spring-Boot集成kaptcha实现表单图片验证

Kaptcha是一个基于SimpleCaptcha的验证码开源项目,Kaptcha的使用比较方便,只需添加jar包依赖之后简单地配置就可以使用了。

添加依赖

如果你使用maven来统一管理jar包,则在工程的pom.xml中添加dependency

<dependency>
    <groupId>com.google.code.kaptcha</groupId>
    <artifactId>kaptcha</artifactId>
    <version>2.3.2</version>
</dependency>

如果是非maven管理的项目,则直接在官网下载kaptcha的jar包,然后添加到项目lib库中,下载地址:

Kaptcha

原理

  • 后台生成验证码图片,将图片传到前台。
  • 后台在session中保存验证码内容。
  • 前台输入验证码后传到后台在后台取出session中保存的验证码进行校验。

注意,验证码的明文是不能传送到前端的。前端内容都是透明的,不安全。验证码是用来防机器人并不是单单防人。如果把验证码明文传到前端很容易就会被破解。

图片验证码的配置类KaptchaConfig

定义图片的信息,包括边框,颜色等等

import org.springframework.stereotype.Component;

import java.util.Properties;

import org.springframework.context.annotation.Bean;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;

/**
 * @program: component
 * @author: ***
 * @description: 这是图片验证的配置类
 * @create: 2019/4/5 10:51
 **/
@Component
public class KaptchaConfig {

    @Bean
    public DefaultKaptcha getDefaultKaptcha() {
        com.google.code.kaptcha.impl.DefaultKaptcha defaultKaptcha = new com.google.code.kaptcha.impl.DefaultKaptcha();
        Properties properties = new Properties();
        // 图片边框
        properties.setProperty("kaptcha.border", "yes");
        // 边框颜色
        properties.setProperty("kaptcha.border.color", "105,179,90");
        // 字体颜色
        properties.setProperty("kaptcha.textproducer.font.color", "red");
        // 图片宽
        properties.setProperty("kaptcha.image.width", "110");
        // 图片高
        properties.setProperty("kaptcha.image.height", "40");
        // 字体大小
        properties.setProperty("kaptcha.textproducer.font.size", "30");
        // session key
        properties.setProperty("kaptcha.session.key", "code");
        // 验证码长度
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        // 字体
        properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
        Config config = new Config(properties);
        defaultKaptcha.setConfig(config);

        return defaultKaptcha;
    }
}

KaptchaController类实现图片的生成与校验

首先一定要注入验证码工具 DefaultKaptcha

@Autowired
    DefaultKaptcha defaultKaptcha;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.google.code.kaptcha.impl.DefaultKaptcha;

/**
 * @program: component
 * @author: ***
 * @description: Kaptcha控制
 * @create: 2019/4/5 10:54
 **/
@Controller
public class KaptchaController {
    /**
     * 1、验证码工具
     */
    @Autowired
    DefaultKaptcha defaultKaptcha;

    /**
     * 2、生成验证码
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @throws Exception
     */
    @RequestMapping("/defaultKaptcha")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws Exception {
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            // 生产验证码字符串并保存到session中
            String createText = defaultKaptcha.createText();
            httpServletRequest.getSession().setAttribute("rightCode", createText);
            // 使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // 定义response输出类型为image/jpeg类型,使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

    /**
     * 3、校对验证码
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @return
     */
    @RequestMapping("/imgvrifyControllerDefaultKaptcha")
    public ModelAndView imgvrifyControllerDefaultKaptcha(HttpServletRequest httpServletRequest,
                                                         HttpServletResponse httpServletResponse) {
        ModelAndView andView = new ModelAndView();
        String rightCode = (String) httpServletRequest.getSession().getAttribute("rightCode");
        String ClientCode = httpServletRequest.getParameter("ClientCode");
//        rightCode是生成码,ClientCode是表单提交码
        System.out.println("rightCode:" + rightCode + " ———— ClientCode:" + ClientCode);
        if (!rightCode.equals(ClientCode)) {
            andView.addObject("info", "验证码错误");
            andView.setViewName("index");
        } else {
            andView.addObject("info", "登录成功");
            andView.setViewName("success");
        }
        return andView;
    }

    @RequestMapping("/toIndex")
    public String toIndex() {
        return "index";
    }
}

前端页面Login.html

简单的一个表单就可以,此处需要注意几点:

  1. onclick="this.src=‘defaultKaptcha?d=‘+new Date()*1" //每次点击图片是刷新图片,重新生成图片
  2. src="defaultKaptcha" // 访问controller中的验证方法


实现的效果

原文地址:https://www.cnblogs.com/jeemia/p/10676354.html

时间: 2024-07-30 00:15:41

Spring-Boot集成kaptcha实现表单图片验证的相关文章

170711、spring boot 集成shiro

这篇文章我们来学习如何使用Spring Boot集成Apache Shiro.安全应该是互联网公司的一道生命线,几乎任何的公司都会涉及到这方面的需求.在Java领域一般有Spring Security.Apache Shiro等安全框架,但是由于Spring Security过于庞大和复杂,大多数公司会选择Apache Shiro来使用,这篇文章会先介绍一下Apache Shiro,在结合Spring Boot给出使用案例. Apache Shiro What is Apache Shiro?

Quartz与Spring Boot集成使用

上次自己搭建Quartz已经是几年前的事了,这次项目中需要定时任务,需要支持集群部署,想到比较轻量级的定时任务框架就是Quartz,于是来一波. 版本说明 通过搜索引擎很容易找到其官网,来到Document的页面,当前版本是2.2.x. 简单的搭建操作 通过Maven引入所需的包: <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId>

Kafka 入门和 Spring Boot 集成

Kafka 入门和 Spring Boot 集成 标签:博客 [TOC] 概述 kafka 是一个高性能的消息队列,也是一个分布式流处理平台(这里的流指的是数据流).由java 和 Scala 语言编写,最早由 LinkedIn 开发,并 2011年开源,现在由 Apache 开发维护. 应用场景 下面列举了一些kafka常见的应用场景. 消息队列 : Kafka 可以作为消息队列使用,可用于系统内异步解耦,流量削峰等场景. 应用监控:利用 Kafka 采集应用程序和服务器健康相关的指标,如应用

Spring Boot集成MyBatis实现通用Mapper

前言 MyBatis关于MyBatis,大部分人都很熟悉.MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录.不管是DDD(Domain Driven Design,领域驱动建模)还是分层架构的风

Spring Boot 集成 MyBatis(四)

Spring Boot 集成 MyBatis A.ORM框架是什么? 对象关系映射(Object Relational Mapping,简称 ORM)模式是一种为了解决面向对象与关系数据库存在的 互不匹配的现象技术.简单的说,ORM 是通过使用描述对象和数据库之间映射的元数据,将程序中的对象自 动持久化到关系数据库中. B.为什么需要ORM框架 当开发一个应用程序的时候(不使用 O/R Mapping),可能会写不少数据访问层的代码,用来从数据库保存. 删除.读取对象信息等.在 DAL 中写了很

Spring boot入门(二):Spring boot集成MySql,Mybatis和PageHelper插件

上一篇文章,写了如何搭建一个简单的Spring boot项目,本篇是接着上一篇文章写得:Spring boot入门:快速搭建Spring boot项目(一),主要是spring boot集成mybatis和pagehelper 关于mybatis和pagehelper的介绍,可以自行博客,网上很多类似的博客,这里,我直接上代码和项目搭建教程. 1.配置文件:在配置文件application.yml中配置MySql数据库连接池和Mybatis扫描包以及PageHelper分页插件 1 mybati

Spring Boot集成Flyway实现数据库版本控制?

今天给大家介绍一款比较好用的数据库版本控制工具Flyway.在通过Spring Boot构建微服务的过程中,一般情况下在拆分微服务的同时,也会按照系统功能的边界对其依存的数据库进行拆分.在这种情况下,微服务的数据库版本管理对于研发工程管理来说,就会是一个比较棘手的问题. 在正常的代码管理流程中,从产品研发研发的过程看,一般会经历功能开发.研发测试.集成测试.预发布测试.上线等多个环节.而对于同一个产品功能,可能还会涉及对多个微服务代码及数据库结构的改动. 而这些改动需要我们在以上流程中每发布一个

spring boot集成mybatis 自动生成实体类和mapper文件、Dao层

1.创建spring boot集成mybatis请见 2.在resources目录下新键mybatis-generator文件夹,并在文件夹中新键mybatis-generatorConfig.xml文件和mybatis-generatorinit.properties两个文件 mybatis-generatorinit.properties jdbc_driver=oracle.jdbc.driver.OracleDriver jdbc_url=jdbc:oracle:thin:@loclho

Spring Boot集成Jasypt安全框架

Jasypt安全框架提供了Spring的集成,主要是实现 PlaceholderConfigurerSupport类或者其子类. 在Sring 3.1之后,则推荐使用PropertySourcesPlaceholderConfigurer类作为属性替换配置类,这里Spring集成Jasypt则使用Jasypt对属性替换配置类的实现.EncryptablePropertySourcesPlaceholderConfigurer. 在Spring中集成比较容易,而且Jasypt官方也给出了配置Bea