当前位置: 代码迷 >> 综合 >> 第二章-开发社区登录模块-4-利用Kapthca生成验证码
  详细解决方案

第二章-开发社区登录模块-4-利用Kapthca生成验证码

热度:29   发布时间:2024-03-09 15:25:44.0

Kaptcha

  • -导入jar包
  • -编写Kaptcha配置类
  • -生成随机字符(服务端需要再保留下来)、生成图片
@Configuration
public class KaptchaConfig {@Beanpublic Producer kaptchaProducer(){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.string","0123456789ABCDEFGHIGKLMNOPQRSTUVWXYZ");properties.setProperty("kaptcha.textproducer.char.length", "4");properties.setProperty("kaptcha.noise.impl","com.google.code.kaptcha.impl.NoNoise"); //加上噪声,默认就是为了防破解DefaultKaptcha kaptcha = new DefaultKaptcha();Config config = new Config(properties);kaptcha.setConfig(config);return kaptcha;}
}

在LoginController方法中添加生成随机图片的访问方法

@RequestMapping(path="/kaptcha", method = RequestMethod.GET)public void getKaptcha(HttpServletResponse response, HttpSession session){//生成验证码,需要先注入Bean,生成一个四位的字符串String text = kaptchaProducer.createText();System.out.println(text);BufferedImage image = kaptchaProducer.createImage(text); //利用字符串去生成图片//将验证码存入sessionsession.setAttribute("kaptcha", text);//将图片输出给浏览器,人工输出(也就是直接输出)response.setContentType("image/png");try {OutputStream os = response.getOutputStream();ImageIO.write(image, "png", os);}catch (IOException e){e.printStackTrace();logger.error("响应验证码失败:" + e.getMessage());}
}

将前端页面中对应地方改成动态数据

<div class="col-sm-4"><img th:src="@{/kaptcha}" style="width:100px;height:40px;" class="mr-2"/><a href="javascript:;" class="font-size-12 align-bottom">刷新验证码</a>
</div>

希望的是点击超链接的时候刷新验证码,因此需要在js中实现

<a href="javascript:refresh_kaptcha();" class="font-size-12 align-bottom">刷新验证码</a>
function refresh_kaptcha(){
//随机添加一个参数,请求欺骗,防止缓存var path = CONTEXT_PATH + "/kaptcha?p=" + Math.random();$("#kaptcha").attr("src",path);
}

 

  相关解决方案