栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【Day 8】学习笔记Springboot仿牛客网论坛实现 -验证码生成

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Day 8】学习笔记Springboot仿牛客网论坛实现 -验证码生成

利用Kaptch

在服务端内存中画出验证码:
步骤
1 导入jar包

2 编写kaptch 配置类

3 生成随机字符,生成图片

在pom.xml 文件中导入


			com.github.penggle
			kaptcha
			2.3.2
		

新建配置类

因为springboot 针对他没有做自动配置 新建一个配置类

(config/ kaptchaConfig)

1 做@configuration 配置注解标注

@Bean 让其被spring 容器管理

要装配kaptcha 核心对象类

producer (实例化接口)

package com.nowcoder.community.config;

import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

@Configuration
public class KaptchaConfig {
    @Bean
    public Producer kaptchaProduct(){
        //实例化她的实现类
        Properties properties=new Properties();
        properties.setProperty("kaptcha.image.width","100");
        properties.setProperty("kaptcha.image.height","40");
        properties.setProperty("kaptcha.textproducer.font.size","32");
        properties.setProperty("kaptcha.textproducer.font.color","0,0,0");
        properties.setProperty("kaptcha.textproducer.char.string","0987654321QWERTYUIOPL");
        properties.setProperty("kaptcha.textproducer.char.length","4");
        properties.setProperty("kaptcha.noise.impl","com.google.code.kaptcha.impl.NoNoise");
        DefaultKaptcha kaptchat= new DefaultKaptcha();
        Config config=new Config(properties);
        kaptchat.setConfig(config);
        return  kaptchat;

    }

}

2 生成验证码的方法 在controller 里

不写在login 方法里因为 返回的是html 页面

所以要单独写一个请求返回图片。

//生成验证码
    @RequestMapping(path="/kaptcha",method=RequestMethod.GET)
    public void getKaptcha (HttpServletResponse response, HttpSession session){
        //生成验证码
        String text=kaptchaProducer.createText();

        BufferedImage image=kaptchaProducer.createImage(text);
        //将验证码存入session
        session.setAttribute("keptcha",text);
        //将图片输出给浏览器
        response.setContentType("image/png");
        try{
            OutputStream os=response.getOutputStream();
            ImageIO.write(image,"png",os);
        }catch (IOException e){
            logger.error("响应验证码失败"+e.getMessage());
        e.printStackTrace();}
    }
    }

3 修改login.html 将图片改为动态的

设置更新的方法:

tips:

在global.js 里将访问路径的/community 存为全局变量 方便如果更改的时候方便更改不要写死

加random 是因为防止不刷新

图片是个静态资源有的浏览器会认为他没有变化 所以欺骗一下他浏览器觉得他变了


   
   刷新验证码

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/944381.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号