首页 > 编程语言 >java + springmvc 酷炫验证码分享

java + springmvc 酷炫验证码分享

时间:2022-10-28 15:03:17浏览次数:54  
标签:github java springmvc 酷炫 patchca new bingoohuang import com


java + springmvc 酷炫验证码分享


一、maven 依赖

<!-- https://mvnrepository.com/artifact/com.github.bingoohuang/patchca -->
<!-- 验证码 -->
<dependency>
<groupId>com.github.bingoohuang</groupId>
<artifactId>patchca</artifactId>
<version>0.0.1</version>
</dependency>
<!-- 验证码 -->




二、spring mvc 控制器


import java.awt.Color;
import java.io.IOException;
import java.util.Random;


import javax.servlet.http.*;


import com.github.bingoohuang.patchca.background.*;
import com.github.bingoohuang.patchca.color.*;
import com.github.bingoohuang.patchca.custom.*;
import com.github.bingoohuang.patchca.filter.predefined.*;
import com.github.bingoohuang.patchca.font.*;
import com.github.bingoohuang.patchca.utils.encoder.EncoderHelper;
import com.github.bingoohuang.patchca.word.*;


@Controller
@RequestMapping("/login")
public class DemoController {
/**
* 彩色,验证码
* @param request
* @param response
* @throws IOException
*/
@RequestMapping("/verfiy-code")
public void VerifyCode(HttpServletRequest request, HttpServletResponse response) {
//生成验证码并写入输出流
String code = com.galaxyf.xd.web.utilis.VerifyCode.outputCaptcha(request, response);
//记录验证码到 session
/*
HttpSession session = req.getSession();
session.setAttribute("verify-code", code);
* */
}
}


三、验证码生产类(VerifyCode.java)


package com.springdemo.controller;


import java.awt.Color;
import java.io.IOException;
import java.util.Random;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import com.github.bingoohuang.patchca.background.MyCustomBackgroundFactory;
import com.github.bingoohuang.patchca.color.ColorFactory;
import com.github.bingoohuang.patchca.custom.ConfigurableCaptchaService;
import com.github.bingoohuang.patchca.filter.predefined.CurvesRippleFilterFactory;
import com.github.bingoohuang.patchca.filter.predefined.DiffuseRippleFilterFactory;
import com.github.bingoohuang.patchca.filter.predefined.DoubleRippleFilterFactory;
import com.github.bingoohuang.patchca.filter.predefined.MarbleRippleFilterFactory;
import com.github.bingoohuang.patchca.filter.predefined.WobbleRippleFilterFactory;
import com.github.bingoohuang.patchca.font.RandomFontFactory;
import com.github.bingoohuang.patchca.utils.encoder.EncoderHelper;
import com.github.bingoohuang.patchca.word.RandomWordFactory;


public class VerifyCode {
static Logger log = Logger.getLogger(VerifyCode.class);
private static ConfigurableCaptchaService cs = new ConfigurableCaptchaService();
private static Random random = new Random();
static int verifyCodeType=1;//验证码字符集
/**
* 参数初始化
*/
static {
// cs.setColorFactory(new SingleColorFactory(new Color(25, 60, 170)));
// 设置颜色
cs.setColorFactory(new ColorFactory() {
@Override
public Color getColor(int x) {
int[] c = new int[3];
int i = random.nextInt(c.length);
for (int fi = 0; fi < c.length; fi++) {
if (fi == i) {
c[fi] = random.nextInt(71);
} else {
c[fi] = random.nextInt(256);
}
}
return new Color(c[0], c[1], c[2]);
}
});
RandomWordFactory wf = new RandomWordFactory();
//验证码字符集
switch (verifyCodeType) {
case 1: //纯数字
wf.setCharacters("0123456789");
break;
case 2: //纯字母
wf.setCharacters("abcdefghigkmnpqrstuvwxyzABCDEFGHIGKLMNPQRSTUVWXYZ");
break;
default: //数字字母混合
wf.setCharacters("23456789abcdefghigkmnpqrstuvwxyzABCDEFGHIGKLMNPQRSTUVWXYZ");
break;
}
// 验证码位数
wf.setMaxLength(4); // 最大
wf.setMinLength(4); // 最小
cs.setWordFactory(wf);
// 设置图片大小
cs.setWidth(170);
cs.setHeight(60);
// 设置字体大小
RandomFontFactory font = new RandomFontFactory();
font.setMaxSize(32);
font.setMinSize(42);
cs.setFontFactory(font);
// 干扰线
MyCustomBackgroundFactory background = new MyCustomBackgroundFactory();
cs.setBackgroundFactory(background);
}


/**
* 设置 http 相应头信息
*
* @param response
*/
protected static void setResponseHeaders(HttpServletResponse response) {
response.setContentType("image/png");
response.setHeader("Cache-Control", "no-cache, no-store");
response.setHeader("Pragma", "no-cache");
long time = System.currentTimeMillis();
response.setDateHeader("Last-Modified", time);
response.setDateHeader("Date", time);
response.setDateHeader("Expires", time);
}


/**
* 输出验证码到响应流
*
* @param request
* @param response
* @throws IOException
*/
public static String outputCaptcha(HttpServletRequest request, HttpServletResponse response) {
//验证码效果
switch (random.nextInt(5)) {
case 0:
cs.setFilterFactory(new CurvesRippleFilterFactory(cs.getColorFactory()));
break;
case 1:
cs.setFilterFactory(new MarbleRippleFilterFactory());
break;
case 2:
cs.setFilterFactory(new DoubleRippleFilterFactory());
break;
case 3:
cs.setFilterFactory(new WobbleRippleFilterFactory());
break;
case 4:
cs.setFilterFactory(new DiffuseRippleFilterFactory());
break;
}
HttpSession session = request.getSession(false);
if (session == null) {
session = request.getSession();
}
setResponseHeaders(response);
String verifyCode="";
try {
// 验证码
verifyCode = EncoderHelper.getChallangeAndWriteImage(cs, "png", response.getOutputStream());
} catch (Exception e) {
log.error(e.getMessage(),e);
verifyCode="....";
}
return verifyCode;
}
}





四、测试


访问:http://localhost:8080/xxxxx/login/verfiy-code


标签:github,java,springmvc,酷炫,patchca,new,bingoohuang,import,com
From: https://blog.51cto.com/u_4518216/5804883

相关文章

  • Java8新特性4:Optional
    1Optional介绍Optional类是一个可以为null的容器对象。如果值存在则isPresent()方法会返回true,调用get()方法会返回该对象。Optional是个容器:它可以保存类型T的值,或者......
  • java-guava 布隆筛选器用法及比较
    java-guava布隆筛选器用法及比较布隆筛选器使用场景:   一般用于一个字符串是否存的预测,如爬虫是否抓取过这个URL等。优点:   对于特大的集合来说,检索快、占用内......
  • java springboot 2.x 环境搭建
    环境:javaversion1.8ApacheMaven3.2.2 ide:ideaspringboot:2.1.3.RELEASE创建步骤:1file=>new=>mudule...2选择SpringInitializr:modulesdk选择1.7,其他默认......
  • java-字符串拼接几种方法的性能比较
    java-字符串拼接几种方法的性能比较一、测试方法:String.format();MessageFormat.format();StringBuilder();二、测试结果:性能:StringBuilder>MessageFormat>String三......
  • 力扣907(java)-子数组的最小值之和(中等)
    题目:给定一个整数数组arr,找到min(b) 的总和,其中b的范围为arr的每个(连续)子数组。由于答案可能很大,因此返回答案模10^9+7。 示例1:输入:arr=[3,1,2,4]输......
  • java-floyd最短距离算法
    java-floyd最短距离算法publicstaticvoidmain(String[]args){MatrixDGmatrixDG=newMatrixDG();System.out.println("初始化邻接矩阵");matrixDG.print......
  • Java-五种线程池,四种拒绝策略,三类阻塞队列
    Java-五种线程池,四种拒绝策略,三类阻塞队列(常用)三类阻塞队列:   //1有界队列   workQueue=newArrayBlockingQueue<>(5);//基于数组的先进先出(FIFO)队列,支持公......
  • java-并发集合-阻塞队列 LinkedBlockingQueue 演示
    java-并发集合-阻塞队列LinkedBlockingQueue演示packageme.grass.demo.concuronte;importjava.util.Date;importjava.util.concurrent.CountDow......
  • java-并发集合-并发hash表 ConcurrentHashMap 演示
    java-并发集合-并发hash表 ConcurrentHashMap演示packageme.grass.demo.concurrent;importjava.util.Date;importjava.util.concurrent.Concurr......
  • java-并发集合-并发队列 ConcurrentLinkedQueue 演示
    java-并发集合-并发队列ConcurrentLinkedQueue演示目标:模拟5个线程同时并发读取“并发队列”,并使用CountDownLatch类协助计算消费耗时。pack......