本文共 2858 字,大约阅读时间需要 9 分钟。
使用Producer接口,有两个方法:创建验证码createImage、文字创建图片createText,它还有一个默认实现类DefaultKaptcha.class
@Configurationpublic class KaptchaConfig { //核心是Producer接口,有两个方法:创建验证码createImage、文字创建图片createText,有一个默认实现类DefaultKaptcha.class //服务启动时被自动装配到容器中,通过容器可以得到一个Producer实例,可以创建验证码和图片 @Bean public Producer kaptchaProducer() { //可以从配置文件中读,properties的key很长,就只在这里写了 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", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYAZ"); properties.setProperty("kaptcha.textproducer.char.length", "4"); properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.NoNoise");//采用哪个噪声类? DefaultKaptcha kaptcha = new DefaultKaptcha();//Producer接口的默认实现类,实例化 Config config = new Config(properties);//传入参数properties(相当于一个map),封装到config对象。 kaptcha.setConfig(config); return kaptcha; }}
private static final Logger logger = LoggerFactory.getLogger(LoginController.class); @Autowired private Producer kaptchaProducer; @RequestMapping(path = "/kaptcha", method = RequestMethod.GET) //向浏览器输出的不是字符串也不是网页,是一个图片,需要自己用response手动向浏览器输出 public void getKaptcha(HttpServletResponse response, HttpSession session) { // 生成验证码 String text = kaptchaProducer.createText(); BufferedImage image = kaptchaProducer.createImage(text); // 将验证码存入session(多个请求要用,这次生成,下次session) session.setAttribute("kaptcha", text); // 将图片输出给浏览器(先告诉浏览器生成的是什么格式的图片,获取输出流,输出字节流(图片)-捕获异常) response.setContentType("image/png"); try { OutputStream os = response.getOutputStream(); ImageIO.write(image, "png", os); } catch (IOException e) { logger.error("响应验证码失败:" + e.getMessage()); } }
@{/kaptcha}访问/community/kaptcha,连接到Controller层,验证码显示在浏览器上。
想要刷新验证码,写函数refresh_kaptcha()。刷新验证码函数refresh_kaptcha():在浏览器上改变路径,服务器不变。
前端语法解释:@{}的作用就是补充/community,#选择id
在任何页面都引用global.js,所以都可以引用该变量
var CONTEXT_PATH = "/community";
转载地址:http://ksnlf.baihongyu.com/