java验证码相关

2023-11-13  本文已影响0人  晓晓_1931

Hutool工具类

maven创建springboot项目
pom.xml

<!-- 添加图形验证码依赖 -->
 <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-captcha</artifactId>
        <version>5.8.6</version>
 </dependency>  

ICaptcha接口定义如下方法:

createCode 创建验证码,实现类需同时生成随机验证码字符串和验证码图片
getCode 获取验证码的文字内容
verify 验证验证码是否正确,建议忽略大小写
write 将验证码写出到目标流中

1、可以写一个普通的java类用来测试

    public static void main(String[] args) {
        // 定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        // 图形验证码写出到指定文件
        lineCaptcha.write("E:/test/captcha.png");
    } 

效果:


image.png

2、写在controller中

package com.xx.controller;

import java.io.IOException; 
import javax.servlet.http.HttpServletResponse; 
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha; 

@RestController 
public class HuToolController {

    @GetMapping("/LineCaptcha")
    public void createCaptcha(HttpServletResponse response) throws IOException {
         // 定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        // 图形验证码写出,可以写出到文件,也可以写出到流
        lineCaptcha.write(response.getOutputStream());
        // 关闭流
        response.getOutputStream().close(); 
    } 
}

效果:


image.png
圆形干扰验证码:
// 定义图形验证码的长、宽、验证码字符数、干扰元素个数
CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 30);

效果:


image.png
扭曲干扰验证码:
// 定义图形验证码的长、宽、验证码字符数、干扰线宽度
ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(200, 100, 4, 4);
GIF验证码:
// 定义GIF验证码的长、宽
GifCaptcha captcha = CaptchaUtil.createGifCaptcha(200, 100); 
CircleCaptcha.gif

Kaptcha入门配置

maven创建springboot项目
pom.xml

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.3.RELEASE</version>
    </parent>

    <dependencies>
        <!--添加验证码实现库的依赖 kaptcha-->
        <dependency>
            <groupId>com.github.axet</groupId>
            <artifactId>kaptcha</artifactId>
            <version>0.0.9</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

一、配置文件方式

主启动类

package com.xx;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;

@SpringBootApplication
@ImportResource(locations = {"classpath:kaptchaConfig.xml"})
public class ManageResourcesApplication {
   public static void main(String[] args) {
      SpringApplication.run(ManageResourcesApplication.class, args);
   }
}

resources目录下创建文件:kaptchaConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- Kaptcha验证码生成器 -->
    <bean name="kaptchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha" scope="singleton">
        <property name="config">
            <bean class="com.google.code.kaptcha.util.Config">
                <constructor-arg>
                    <props>
                        <prop key="kaptcha.border">no</prop>
                        <prop key="kaptcha.textproducer.font.color">black</prop>
                        <prop key="kaptcha.textproducer.char.space">4</prop>
                        <prop key="kaptcha.textproducer.char.length">4</prop>
                        <prop key="kaptcha.textproducer.char.string">123456789</prop>
                    </props>
                </constructor-arg>
            </bean>
        </property>
    </bean>
</beans>

控制器Controller

package com.xx.controller;

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

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

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

@RequestMapping(value = "login")
@RestController
public class SysLoginController {
 
        @Autowired
        private Producer producer;
 
        @GetMapping(value = "captchat.jpg")
        public void createKacptcha(HttpServletResponse response, HttpServletRequest request) throws IOException {
            response.setHeader("Cache-Control","no-store");
            response.setContentType("image/jpeg");
            // 文字验证码
            String text = producer.createText();
            // 图片验证码
            BufferedImage image = producer.createImage(text);
            // 保存验证码到session
            request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY,text);
            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(image,"jpg",outputStream);
            IOUtils.closeQuietly(outputStream);
        }
 
} 

二、配置类方式

主启动类

@SpringBootApplication
public class ManageResourcesApplication {
   public static void main(String[] args) {
      SpringApplication.run(ManageResourcesApplication.class, args);
   }
}

配置类

package com.xx.comfig;

import java.util.Properties;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
 
/**
 * kaptcha验证码生成器配置
 * @author lwf
 * @date 2019/8/21 16:10
 */
@Configuration
public class KaptchaConfig {
 
     @Bean
        public DefaultKaptcha producer() {
            Properties properties = new Properties();
            properties.put("kaptcha.border","no");
            properties.put("kaptcha.textproducer.font,color","black");
            properties.put("kaptcha.textproducer.char.space","5");
            Config config = new Config(properties);
            DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
            defaultKaptcha.setConfig(config);
            return defaultKaptcha;
        }
 
}

控制器Controller

package com.xx.controller;

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

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

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

@RequestMapping(value = "login")
@RestController
public class SysLoginController {
 
        @Autowired
        private Producer producer;
 
        @GetMapping(value = "captchat.jpg")
        public void createKacptcha(HttpServletResponse response, HttpServletRequest request) throws IOException {
            response.setHeader("Cache-Control","no-store");
            response.setContentType("image/jpeg");
            // 文字验证码
            String text = producer.createText();
            // 图片验证码
            BufferedImage image = producer.createImage(text);
            // 保存验证码到session
            request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY,text);
            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(image,"jpg",outputStream);
            IOUtils.closeQuietly(outputStream);
        }
 
} 

测试

启动服务访问:http://localhost:8080/login/captchat.jpg
效果:

image.png

KAPTCHA 参数详解

image.png
上一篇下一篇

猜你喜欢

热点阅读