当前位置: 首页 > news >正文

SpringIoc 基础练习 验证码

三层架构

1.表示层      和客服端(比如前端)的交互,参数的接收,数据的返回     Controller

2.业务逻辑层    对数据进行处理(业务方面)   Service

3.数据层           数据的管理(存储,查询)     Dao

高内聚,低耦合

验证码:

定义接口

1.返回验证码

2.校验验证码是否正确

代码如下:

controller→CaptchaController

model→CaptchaProperties

static→index.html    success.html

templates→application.yml


CaptchaController

package com.bite.captchademo.controller;import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import com.bite.captchademo.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.io.IOException;@RequestMapping("/captcha")
@RestController
public class CaptchaController {@Autowiredprivate CaptchaProperties captchaProperties;private static long VALID_TIME = 60*1000;@RequestMapping("/get")public void getCaptcha(HttpSession session, HttpServletResponse response){ICaptcha captcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());try {captcha.write(response.getOutputStream());//禁止缓存response.setHeader("Prama", "No-cache");//设置返回的格式response.setContentType("image/jpeg");//打印验证码System.out.println(captcha.getCode());//存储Sessionsession.setAttribute(captchaProperties.getSession().getCode(), captcha.getCode());session.setAttribute(captchaProperties.getSession().getDate(), System.currentTimeMillis());//Servlet的OutputStream记得自行关闭哦!response.getOutputStream().close();} catch (IOException e) {throw new RuntimeException(e);}}@RequestMapping("/check")public Boolean check(String captchaCode,HttpSession session){System.out.println("接收captchaCode:"+captchaCode);//参数校验//判断用户输入的验证码是否和session中存储的一致//是否在有效期内if (!StringUtils.hasLength(captchaCode)){return false;}String sessionCode = (String)session.getAttribute(captchaProperties.getSession().getCode());Long sessionDate = (Long)session.getAttribute(captchaProperties.getSession().getDate());if (captchaCode.equalsIgnoreCase(sessionCode)&& sessionDate!=null&& (System.currentTimeMillis() - sessionDate) < VALID_TIME){return true;}return false;}
}

CaptchaProperties

package com.bite.captchademo.model;import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;@Configuration
@ConfigurationProperties(prefix = "captcha")
@Data
public class CaptchaProperties {private Integer width;private Integer height;private Session session;@Datapublic static class Session {private String code;private String date;}}

index.html

<!DOCTYPE html>
<html lang="en"><head><meta charset="utf-8"><title>验证码</title><style>#inputCaptcha {height: 30px;vertical-align: middle;}#verificationCodeImg{vertical-align: middle;}#checkCaptcha{height: 40px;width: 100px;}</style>
</head><body>
<h1>输入验证码</h1>
<div id="confirm"><input type="text" name="inputCaptcha" id="inputCaptcha"><img id="verificationCodeImg" src="/captcha/get" style="cursor: pointer;" title="看不清?换一张" /><input type="button" value="提交" id="checkCaptcha">
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>//点击图片, 重新加载$("#verificationCodeImg").click(function(){$(this).hide().attr('src', '/captcha/get?dt=' + new Date().getTime()).fadeIn();});$("#checkCaptcha").click(function () {$.ajax({type: "post",url: "/captcha/check",data:{captchaCode: $("#inputCaptcha").val()},success:function(result){if(result){location.href = "success.html";}else{alert("验证码错误!!");}}});});</script>
</body></html>

success.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>验证成功页</title>
</head>
<body>
<h1>验证成功</h1>
</body>
</html>

application.yml

captcha:width: 100height: 40session:code: CAPTCHA_SESSION_CODEdate: CATPCHA_SESSION_DATE

运行结果:

 

http://www.dtcms.com/a/391571.html

相关文章:

  • 前端项目,CDN预热有什么用?
  • TF卡的存储数据结构—fat32格式
  • led的带宽在模拟太阳光中设备中的影响
  • go资深之路笔记(三) sync.WaitGroup, sync.errgroup和 sync.go-multierror
  • Docker 与数据库环境
  • Node.js 模块系统详解
  • proxy代理应用记录
  • 基于python大数据的汽车数据分析系统设计与实现
  • WebSocket实现原理
  • 从保存到加载Docker镜像文件操作全图解
  • IDEA文件修改后改变文件名和文件夹颜色
  • 【MySQL 】MySQL 入门之旅 · 第十篇:子查询与嵌套查询
  • TM52F1376 SSOP24电子元器件 HITENX海速芯 8位微控制器MCU 芯片 深度解析
  • 基于Matlab图像处理的工件表面缺陷检测系统
  • 业务上云实践MYSQL架构改造
  • 深入解析TCP/IP协议分层与通信原理
  • 【人工智能通识专栏】第二十讲:科创项目选题
  • 数据治理系列(三):SQL2API 平台格局与发展趋势
  • 软考-系统架构设计师 软件项目管理详细讲解
  • three.js添加CSS2DRenderer对象
  • 磁共振成像原理(理论)9:射频回波 (RF Echoes)-三脉冲回波(2)
  • 栈的主要知识
  • question:使用同一请求数据且渲染顺序不确定时复用
  • Redis群集三种模式介绍和创建
  • 【LeetCode 每日一题】1935. 可以输入的最大单词数
  • eeprom和flash的区别
  • [vibe code追踪] 分支图可视化 | SVG画布 | D3.js
  • [硬件电路-264]:数字电路的电源系统的主要特性包括哪些
  • 算法题(212):01背包(空间优化)
  • TP4054和TP4056对比