Java实现滑动验证码的示例代码

 更新时间:2022年02月28日 15:52:46   作者:灰太狼_cxh  
这篇文章主要为大家介绍了如何用Java语言实现滑动验证码的生成,项目采用了springboot,maven等技术,感兴趣的小伙伴可以跟随小编学习一下

功能:java实现滑动验证码

项目是采用springboot,maven

开发工具:采用idea

1.效果演示

2.后端代码

控制层

@Controller
public class SliderCodeController {
 
    @Autowired
    ResourceLoader resourceLoader;
 
    @Autowired
    private FileUtil fileUtil;
 
    // 设置横轴位置缓存
    public static Cache< String, Integer > cacheg = CacheBuilder.newBuilder().expireAfterWrite(60, TimeUnit.SECONDS)
            .maximumSize(666666).build();
 
    @GetMapping
    @RequestMapping("index")
    public String test(HttpServletRequest request, Model model) throws IOException {
        return "index";
    }
 
 
    @GetMapping
    @RequestMapping("getImg")
    public @ResponseBody
    Map< String, Object > getPic(HttpServletRequest request) throws IOException {
        try {
            File targetFile = fileUtil.getFile("target");
            File tempImgFile = fileUtil.getFile("temp");
            Map < String, Object > resultMap = VerifyImageUtil.pictureTemplatesCut(tempImgFile, targetFile);
            // 生成流水号,这里就使用时间戳代替
            String lno = Calendar.getInstance().getTimeInMillis() + "";
            cacheg.put(lno, Integer.valueOf(resultMap.get("xWidth") + ""));
            resultMap.put("capcode", lno);
            // 移除横坐标送前端
            resultMap.remove("xWidth");
            return resultMap;
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
 
    }
 
 
    @GetMapping
    @RequestMapping("checkImgCode")
    public @ResponseBody Map < String, Object > checkcapcode(@RequestParam("xpos") int xpos,
                                                             @RequestParam("capcode") String capcode, HttpServletRequest request) throws IOException {
        Map < String, Object > result = new HashMap< String, Object >();
        Integer x = cacheg.getIfPresent(capcode);
        if (x == null) {
            // 超时
            result.put("code", 3);
        }
        else if (xpos - x > 5 || xpos - x < -5) {
            // 验证失败
            result.put("code", 2);
        }
        else {
            // 验证成功
            result.put("code", 1);
        }
        return result;
    }
}

工具类

@Component
public class FileUtil {
 
    @Value("${file.path}")
    private String filePath;
 
    @Value("${file.target.path}")
    private String targetFilePath;
 
    @Value("${file.target.num}")
    private Integer targetfileNum;
 
    @Value("${file.temp.path}")
    private String tempFilePath;
 
    @Value("${file.temp.num}")
    private Integer tempfileNum;
 
    public File getFile(String type){
        int num = 0;
        String imgType = ".jpg";
        String oldFilePath = "";
        if(type.equals("target")){
            num = new Random().nextInt(targetfileNum)  + 1;
            oldFilePath = targetFilePath;
        } else  if(type.equals("temp")){
            num = new Random().nextInt(tempfileNum)  + 1;
            imgType = "-w.png";
            oldFilePath = tempFilePath;
        }
        String path = filePath;
        String fileImg =   num + imgType;
        String filePath = path + fileImg;
        File pathFile = new File(path);
        if(!pathFile.exists()){
            pathFile.mkdirs();
        }
        File file = new File(filePath);
        if(!file.exists()){
            try {
                file.createNewFile();
                ClassPathResource classPathResource = new ClassPathResource(oldFilePath + fileImg);
                InputStream inputStream = classPathResource.getInputStream();
                if(inputStream.available() != 0){
                    FileUtils.copyInputStreamToFile(inputStream, file);
                }
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }
 
}

3.前端页面

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>滑动验证码</title>
<link rel="stylesheet" href="/css/slide.css" rel="external nofollow" >
<script src="/js/jquery-1.11.1.min.js"></script>
<script src="/js/jquery.lgyslide.js"></script>
</head>
<body>
	<div id="imgscode"></div>
	<script>
		$(function() {
			setTimeout(function() {
				createcode();
			}, 1000)
		}());
		//显示验证码
		function createcode() {
			$
					.ajax({
						type : 'POST',
						url : '/getImg',
						dataType : 'json',
						success : function(data) {
							if (data != null) {
								$("#imgscode")
										.imgcode(
												{
													frontimg : 'data:image/png;base64,'
															+ data.slidingImage,
													backimg : 'data:image/png;base64,'
															+ data.backImage,
													yHeight : data.yHeight,
													refreshcallback : function() {
														//刷新验证码
														createcode();
													},
													callback : function(msg) {
														console.log(msg);
														var $this = this;
														$
																.ajax({
																	type : 'POST',
																	url : '/checkImgCode',
																	data : {
																		xpos : msg.xpos,
																		capcode : data.capcode
																	},
																	dataType : 'json',
																	success : function(
																			data) {
																		console
																				.log(data)
																		if (data.code == 1) {
																			$this
																					.getsuccess();
																		} else {
																			if (data.code == 4) {
																				createcode();
																			} else if (data.code == 3) {
																				$this
																						.getfail("验证码过期,请刷新");
																			} else {
																				$this
																						.getfail("验证不通过");
																			}
																		}
 
																	}
																})
													}
												});
							}
						}
					})
		}
	</script>
</body>
</html>

到此这篇关于Java实现滑动验证码的示例代码的文章就介绍到这了,更多相关Java滑动验证码内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Mybatis-Plus自动填充更新操作相关字段的实现

    Mybatis-Plus自动填充更新操作相关字段的实现

    数据库表中应该都要有create_time、update_time字段;那么在开发中,对于这些共有字段的处理应该要进行统一,这样就可以简化我们的开发过程。那么本文就对Mybatis-Plus中的字段自动填充进行记录
    2021-11-11
  • 浅谈Java中强制类型转换的问题

    浅谈Java中强制类型转换的问题

    下面小编就为大家带来一篇浅谈Java中强制类型转换的问题。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-05-05
  • Java多线程下载的实现方法

    Java多线程下载的实现方法

    复习多线程的时候,练习了下,顺便记录一下:
    2013-03-03
  • 详解Java中格式化日期的DateFormat与SimpleDateFormat类

    详解Java中格式化日期的DateFormat与SimpleDateFormat类

    DateFormat其本身是一个抽象类,SimpleDateFormat 类是DateFormat类的子类,一般情况下来讲DateFormat类很少会直接使用,而都使用SimpleDateFormat类完成,下面我们具体来看一下两个类的用法:
    2016-05-05
  • Java的AQS基本原理详细分析

    Java的AQS基本原理详细分析

    这篇文章主要介绍了Java的AQS基本原理详细分析,AQS是Abstract Queued Synchronizer的简称,AQS提供了一种实现阻塞锁和一系列依赖FIFO等待队列的同步器的框架,本文主要讲解分析其基本原理,需要的朋友可以参考下
    2024-01-01
  • SpringBoot预防XSS攻击的实现

    SpringBoot预防XSS攻击的实现

    XSS攻击是一种在web应用中的计算机安全漏洞,它允许恶意web用户将代码植入到提供给其它用户使用的页面,本文主要介绍了SpringBoot预防XSS攻击的实现,感兴趣的可以了解一下
    2023-08-08
  • springboot2.x实现oauth2授权码登陆的方法

    springboot2.x实现oauth2授权码登陆的方法

    这篇文章主要介绍了springboot2.x实现oauth2授权码登陆的方法,本文给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-08-08
  • Java栈的应用之括号匹配算法实例分析

    Java栈的应用之括号匹配算法实例分析

    这篇文章主要介绍了Java栈的应用之括号匹配算法,结合实例形式分析了Java使用栈实现括号匹配算法的相关原理、操作技巧与注意事项,需要的朋友可以参考下
    2020-03-03
  • 解决try-catch捕获异常信息后Spring事务失效的问题

    解决try-catch捕获异常信息后Spring事务失效的问题

    这篇文章主要介绍了解决try-catch捕获异常信息后Spring事务失效的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-06-06
  • 浅析SpringBoot多数据源实现方案

    浅析SpringBoot多数据源实现方案

    现在很多项目的开发过程中,可能涉及到多个数据源,像读写分离的场景,或者因为业务复杂,导致不同的业务部署在不同的数据库上,那么这样的场景,我们应该如何在代码中简洁方便的切换数据源呢,本文介绍SpringBoot多数据源实现方案,感兴趣的朋友跟随小编一起看看吧
    2024-02-02

最新评论