最近搜索

java web 项目 添加 验证码 支持

浏览:1523
管理员 2020-03-14 07:22


	/**
	 * @author XXXXXX
	 * @date 2018年7月11日
	 * @desc 图形验证码生成
	 */
	@RequestMapping("/createImg")
	public void createImg(HttpServletRequest request, HttpServletResponse response) throws Exception {
	    try {
	        response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
	        response.setHeader("Pragma", "No-cache");//设置响应头信息,告诉浏览器不要缓存此内容
	        response.setHeader("Cache-Control", "no-cache");
	        response.setDateHeader("Expire", 0);
	        VerifyUtil randomValidateCode = new VerifyUtil();
	        randomValidateCode.getRandcode(request, response);//输出验证码图片
	    	}catch (Exception e) {
			}
	}	


Session 空闲无任何请求超过 60 秒,session 销毁,验证码消失。

✅ 场景 1:生成验证码 → 放着不动,60 秒内不发任何请求 → 60s 后 session 失效,验证码过期(符合你的预期)

❌ 场景 2:生成验证码,30 秒的时候,点图片刷新验证码→ 刷新验证码这个请求会重置 Session 的空闲倒计时,重新又给 60 秒。哪怕第一张图片已经过去 50 秒,只要刷新图片,计时器清零。



package com.java456.util;



import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;


public class VerifyUtil {
	
	
	 public static final String RANDOMCODEKEY= "RANDOMREDISKEY";//放到session中的key
	    private String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产生数字与字母组合的字符串
	    private int width = 95;// 图片宽
	    private int height = 25;// 图片高
	    private int lineSize = 40;// 干扰线数量
	    private int stringNum = 4;// 随机产生字符数量
	 
	    private Random random = new Random();
	 
	    /**
	     * 获得字体
	     */
	    private Font getFont() {
	        return new Font("Fixedsys", Font.CENTER_BASELINE, 18);
	    }
	 
	    /**
	     * 获得颜色
	     */
	    private Color getRandColor(int fc, int bc) {
	        if (fc > 255)
	            fc = 255;
	        if (bc > 255)
	            bc = 255;
	        int r = fc + random.nextInt(bc - fc - 16);
	        int g = fc + random.nextInt(bc - fc - 14);
	        int b = fc + random.nextInt(bc - fc - 18);
	        return new Color(r, g, b);
	    }
	 
	    /**
	     * 生成随机图片
	     */
	    public void getRandcode(HttpServletRequest request, HttpServletResponse response) {
	        HttpSession session = request.getSession();
	        // BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
	        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
	        Graphics g = image.getGraphics();// 产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作
	        g.fillRect(0, 0, width, height);//图片大小
	        g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18));//字体大小
	        g.setColor(getRandColor(110, 133));//字体颜色
	        // 绘制干扰线
	        for (int i = 0; i <= lineSize; i++) {
	            drowLine(g);
	        }
	        // 绘制随机字符
	        String randomString = "";
	        for (int i = 1; i <= stringNum; i++) {
	            randomString = drowString(g, randomString, i);
	        }
	        //将生成的随机字符串保存到session中
	        session.removeAttribute(RANDOMCODEKEY);
	        session.setAttribute(RANDOMCODEKEY, randomString);
	        //设置失效时间1分钟 这个开启,系统1分钟 就会掉线,重新登录。
	        //session.setMaxInactiveInterval(60);
	        g.dispose();
	        try {
	            // 将内存中的图片通过流动形式输出到客户端
	            ImageIO.write(image, "JPEG", response.getOutputStream());
	        } catch (Exception e) {
	        }
	 
	    }
	 
	    /**
	     * 绘制字符串
	     */
	    private String drowString(Graphics g, String randomString, int i) {
	        g.setFont(getFont());
	        g.setColor(new Color(random.nextInt(101), random.nextInt(111), random
	                .nextInt(121)));
	        String rand = String.valueOf(getRandomString(random.nextInt(randString
	                .length())));
	        randomString += rand;
	        g.translate(random.nextInt(3), random.nextInt(3));
	        g.drawString(rand, 13 * i, 16);
	        return randomString;
	    }
	 
	    /**
	     * 绘制干扰线
	     */
	    private void drowLine(Graphics g) {
	        int x = random.nextInt(width);
	        int y = random.nextInt(height);
	        int xl = random.nextInt(13);
	        int yl = random.nextInt(15);
	        g.drawLine(x, y, x + xl, y + yl);
	    }
	 
	    /**
	     * 获取随机的字符
	     */
	    public String getRandomString(int num) {
	        return String.valueOf(randString.charAt(num));
	    }

	    
	    
}







<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title th:text="${application.config.webName}+' 登录' "></title>
    <link rel="shortcut icon" href="/favicon.ico">
    <link rel="icon" type="image/gif" href="/animated_favicon1.gif">
    <div th:include="/common/layui"></div>
    <div th:include="/common/jq"></div>
    <style>
       * {
          padding: 0px;
          margin: 0px;
       }
       html{height: 100%;}
       body{height: 100%;}
       .win{
          top:180px;
          position: absolute;
          left:50%;
          width:526px;
          height:556px;
          margin-left:-300px; /* 元素宽度的一半 */
          z-index:1005;
       }
       .yanse{ background-color:#E6A23C }
       .code-img{
          cursor: pointer;
          height:38px;
       }
    </style>
</head>
<script>
    $(function() {
       $("#name").focus();
    });
    // 刷新验证码
    function refreshCode(){
       //加随机参数,防止浏览器缓存图片
       $("#codeImg").attr("src","/user/createImg?"+Math.random());
    }
    function go_login() {
       var index = layer.load(1, {
          shade : [ 0.1, '#fff' ]
       });
       var name = $("#name").val();
       var password = $("#password").val();
       var code = $("#code").val();
       if (name == null || name == "") {
          layer.closeAll();
          layer.msg('请输入帐号!');
          return;
       }
       if (password == null || password == "") {
          layer.closeAll();
          layer.msg('请输入密码!');
          return;
       }
       if (code == null || code == "") {
          layer.closeAll();
          layer.msg('请输入验证码!');
          return;
       }
       $.post('/user/login', {
          name : name,
          password : password,
          code : code
       }, function(result) {
          if (result.success) {
             layer.closeAll();
             window.location.href = "/admin/main";
          } else {
             layer.closeAll();
             layer.msg(result.msg);
             // 登录失败自动刷新验证码
             refreshCode();
          }
       }, 'json');
    }
</script>
<body id="app">
<div style="text-align: left;font-size: 20px; padding-left: 15px;padding-top: 20px; color: #1E9FFF; ">[[${application.config.webName}]]</div>
<div style="text-align: left; padding-left:35px;font-size: 20px;  ">system </div>
<div class="win">
    <div style="text-align: center; font-size:42px; color: #E6A23C; ">[[${application.config.webName}]]</div>
    <div style="text-align: center; font-size: 12px; color: #FFB800; padding-top: 10px;">Welcome to Juncheng Tourism Management System</div>
    <div style="padding-top: 30px"></div>
    <div class="layui-tab layui-tab-brief" lay-filter="docDemoTabBrief">
       <ul class="layui-tab-title">
          <li class="layui-this">登录</li>
       </ul>
       <div class="layui-tab-content" style="height: 280px;">
          <div class="layui-tab-item layui-show">
             <div class="layui-form" action="">
                <div class="layui-form-item">
                   <label class="layui-form-label" style="width: 30px; color: #606266">帐号</label>
                   <div class="layui-input-block" style="margin-left: 60px;">
                      <input type="text" id="name" autocomplete="off"
                            placeholder="请输入帐号"
                            onkeydown="if(event.keyCode==13) $('#password').focus()"
                            class="layui-input">
                   </div>
                </div>
                <div class="layui-form-item">
                   <label class="layui-form-label" style="width: 30px; color: #606266">密码</label>
                   <div class="layui-input-block" style="margin-left: 60px;">
                      <input type="password" id="password" autocomplete="off"
                            placeholder="请输入密码"
                            onkeydown="if(event.keyCode==13) $('#code').focus()"
                            class="layui-input">
                   </div>
                </div>
                <!-- ========== 新增验证码行 ========== -->
                <div class="layui-form-item">
                   <label class="layui-form-label" style="width: 30px; color: #606266">验证码</label>
                   <div class="layui-input-block" style="margin-left: 60px;display:flex;gap:10px;">
                      <input type="text" id="code" autocomplete="off" style="flex:1"
                            placeholder="请输入验证码"
                            onkeydown="if(event.keyCode==13) go_login()"
                            class="layui-input">
                      <img id="codeImg" class="code-img" onclick="refreshCode()" src="/user/createImg" title="点击刷新">
                   </div>
                </div>
                <div class="layui-form-item">
                   <div class="layui-input-block" style="margin-left: 60px;">
                      <button class="layui-btn layui-btn-fluid yanse" onclick="go_login()">登陆</button>
                   </div>
                </div>
             </div>
          </div>
       </div>
    </div>
</div>
<script>
    layui.use([ 'laydate', 'laypage', 'layer', 'table', 'carousel', 'upload',
       'element' ], function() {
       var laydate = layui.laydate //日期
             , laypage = layui.laypage //分页
             , layer = layui.layer //弹层
             , table = layui.table //表格
             , carousel = layui.carousel //轮播
             , upload = layui.upload //上传
             , element = layui.element; //元素操作
    });
</script>
</body>
</html>






package java456.com.controller;

import com.alibaba.fastjson2.JSONObject;
import java456.com.entity.User;
import java456.com.mapper.UserMapper;
import java456.com.service.UserService;
import java456.com.service.impl.ConfigServiceImpl;
import java456.com.utils.CryptographyUtil;
import java456.com.utils.VerifyUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

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

@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private ConfigServiceImpl configService;

    /**
     * 生成验证码图片接口
     */
    @RequestMapping("/createImg")
    public void createImg(HttpServletRequest request, HttpServletResponse response) throws Exception {
       try {
          response.setContentType("image/jpeg");
          response.setHeader("Pragma", "No-cache");
          response.setHeader("Cache-Control", "no-cache");
          response.setDateHeader("Expire", 0);
          VerifyUtil randomValidateCode = new VerifyUtil();
          randomValidateCode.getRandcode(request, response);
       } catch (Exception e) {
          e.printStackTrace();
       }
    }

    @ResponseBody
    @RequestMapping("/login")
    public JSONObject login(String name, String password, String code, HttpServletRequest request) throws Exception {
       JSONObject result = new JSONObject();
       //====第一步:校验验证码====
       HttpSession session = request.getSession();
       String sessionCode = (String) session.getAttribute(VerifyUtil.RANDOMCODEKEY);
       // 忽略大小写比对;验证码不存在 / 输入不一致,直接返回
       if (sessionCode == null || !sessionCode.equalsIgnoreCase(code)) {
          result.put("success", false);
          result.put("msg", "验证码错误或已过期");
          // 清除旧验证码,防止重复使用
          session.removeAttribute(VerifyUtil.RANDOMCODEKEY);
          return result;
       }
       // 验证通过,立刻销毁验证码(一次性使用)
       session.removeAttribute(VerifyUtil.RANDOMCODEKEY);

       //====第二步:Shiro账号密码登录====
       Subject subject = SecurityUtils.getSubject();
       UsernamePasswordToken token = new UsernamePasswordToken(name, CryptographyUtil.md5(password, "java"));
       try {
          subject.login(token);
          result.put("success", true);
          result.put("msg", "登陆成功");
          User user = userService.findByName(name);
          SecurityUtils.getSubject().getSession().setAttribute("currentUser", user);
       } catch (UnknownAccountException e) {
          result.put("success", false);
          result.put("msg", "用户名不存在");
       } catch (IncorrectCredentialsException e) {
          result.put("success", false);
          // 你原来代码这里提示"用户名不存在",建议改成:密码错误,更合理
          result.put("success", false);
          result.put("msg", "用户名不存在");
       }
       return result;
    }

    /**
     * 注销
     */
    @RequestMapping("/logout")
    public String logout() throws Exception {
       SecurityUtils.getSubject().logout();
       return "redirect:/login";
    }
}


联系站长

站长微信:xiaomao0055

站长QQ:14496453