SpringMVC下获取验证码实例详解
程序员文章站
2022-06-29 13:26:21
springmvc下获取验证码实例详解
前言:
1.用户一开始登录的时候, 不建议出现验证码, 这一点在很多网站上已经体现的很好了, 只有当用户连续输错三次或者以上才会...
springmvc下获取验证码实例详解
前言:
1.用户一开始登录的时候, 不建议出现验证码, 这一点在很多网站上已经体现的很好了, 只有当用户连续输错三次或者以上才会要求用户输入验证码.
2.记录用户输错次数最好不要使用 session 来记录, 因为 session 是跟客户端浏览器会话有关的, 如果用重启浏览器或者换新的浏览器再来登录或者试错, 就是新的回话了, 原来记录的错误次数就失效了. 建议此处采用缓存机制来实现, 简单处理就是采用 map<用户登录id, 错误次数> 来实现, 如果有多台服务器负载的话, 就需要采用另外的缓存机制, 比如采用 redis.
3.当用户输入完用户名以后, 就需要用登录名进行判断, 是否需要进行验证码校验.
4.生成的验证码与 session 绑定, 是否需要校验验证码, 要根据用户规定时间内失败的次数来判断.
原生的 servlet 可以直接 write 图片到客户端. 但是刚用 springmvc 的童鞋可能不知道怎么在此框架下返回图片. 其实在本质上用 spring 返回图片跟用 servlet 是一样的。都是使用的 httpservletresponse 来返回图片.
springmvc 的 controller 里获取验证码的方法
/** * 生成验证码 * @param request * @param response */ @requestmapping(value = "login/getverifycode") public void getverifycode(httpservletrequest request,httpservletresponse response){ response.setheader("pragma","no-cache"); response.setheader("cache-control", "no-cache"); response.setdateheader("expires", 0); response.setcontenttype("image/jpeg"); //生成随机字符串 string verifycode = verifycodeutils.generateverifycode(4); //存入session, 此处可以根据自己的需求 httpsession session = request.getsession(); session.setattribute("verifycode",verifycode); //生成图片 int w = 100, h = 35; try { //将图片写入到 response 的输出流即可将图片返回到客户端了 verifycodeutils.outputimage(w, h , response.getoutputstream(), verifycode); } catch (ioexception e) { logger.error("生成验证码失败, cause by: {}", e.getmessage(), e); } }
生成验证码图片的类
网上找到的一个, 还不错.
import javax.imageio.imageio; import java.awt.*; import java.awt.geom.affinetransform; import java.awt.image.bufferedimage; import java.io.file; import java.io.fileoutputstream; import java.io.ioexception; import java.io.outputstream; import java.util.arrays; import java.util.random; /** * 生成图片流 * @description: created by zcqshine on 2017/5/18. */ public class verifycodeutils { private static final string verify_codes = "23456789abcdefghjklmnpqrstuvwxyz"; private static random random = new random(); /** * 使用系统默认字符源生成验证码 * @param verifysize 验证码长度 * @return */ public static string generateverifycode(int verifysize){ return generateverifycode(verifysize, verify_codes); } /** * 使用指定源生成验证码 * @param verifysize 验证码长度 * @param sources 验证码字符源 * @return */ public static string generateverifycode(int verifysize, string sources){ if (sources == null || sources.trim().length() == 0){ sources = verify_codes; } int codeslen = sources.length(); random rand = new random(system.currenttimemillis()); stringbuilder verifycode = new stringbuilder(verifysize); for (int i = 0; i < verifysize; i++){ verifycode.append(sources.charat(rand.nextint(codeslen -1 ))); } return verifycode.tostring(); } /** * 输出随机验证码图片流, 并返回验证码值 * @param w * @param h * @param outputfile * @param verifysize * @return */ public static string outputverifyimage(int w, int h, file outputfile, int verifysize) throws ioexception{ string verifycode = generateverifycode(verifysize); outputimage(w,h,outputfile,verifycode); return verifycode; } /** * 生成指定验证码图像文件 * @param w * @param h * @param outputfile * @param verifycode * @throws ioexception */ public static void outputimage(int w, int h, file outputfile, string verifycode) throws ioexception{ if (outputfile == null){ return; } file dir = outputfile.getparentfile(); if(!dir.exists()){ dir.mkdirs(); } try { outputfile.createnewfile(); fileoutputstream fos = new fileoutputstream(outputfile); outputimage(w, h, fos, verifycode); fos.close(); } catch (ioexception e) { throw e; } } public static void outputimage(int w, int h, outputstream os, string code) throws ioexception{ int verifysize = code.length(); bufferedimage image = new bufferedimage(w,h, bufferedimage.type_int_rgb); random rand = new random(); graphics2d g2 = image.creategraphics(); g2.setrenderinghint(renderinghints.key_antialiasing,renderinghints.value_antialias_on); color[] colors = new color[5]; color[] colorspaces = new color[]{color.white, color.cyan, color.gray, color.light_gray, color.magenta, color.orange, color.pink, color.yellow}; float[] fractions = new float[colors.length]; for (int i = 0; i < colors.length; i++){ colors[i] = colorspaces[rand.nextint(colorspaces.length)]; fractions[i] = rand.nextfloat(); } arrays.sort(fractions); g2.setcolor(color.gray); //设置边框色 g2.fillrect(0,0, w, h); color c = getrandcolor(200, 250); g2.setcolor(c); //设置背景色 g2.fillrect(0, 2, w, h-4); //绘制干扰线 random random = new random(); g2.setcolor(getrandcolor(160, 200));// 设置线条的颜色 for (int i = 0; i < 20; i++) { int x = random.nextint(w - 1); int y = random.nextint(h - 1); int xl = random.nextint(6) + 1; int yl = random.nextint(12) + 1; g2.drawline(x, y, x + xl + 40, y + yl + 20); } // 添加噪点 float yawprate = 0.05f;// 噪声率 int area = (int) (yawprate * w * h); for (int i = 0; i < area; i++) { int x = random.nextint(w); int y = random.nextint(h); int rgb = getrandomintcolor(); image.setrgb(x, y, rgb); } shear(g2, w, h, c);// 使图片扭曲 g2.setcolor(getrandcolor(100, 160)); int fontsize = h-4; font font = new font("algerian", font.italic, fontsize); g2.setfont(font); char[] chars = code.tochararray(); for(int i = 0; i < verifysize; i++){ affinetransform affine = new affinetransform(); affine.settorotation(math.pi / 4 * rand.nextdouble() * (rand.nextboolean() ? 1 : -1), (w / verifysize) * i + fontsize/2, h/2); g2.settransform(affine); g2.drawchars(chars, i, 1, ((w-10) / verifysize) * i + 5, h/2 + fontsize/2 - 10); } g2.dispose(); imageio.write(image, "jpg", os); } private static color getrandcolor(int fc, int bc) { if (fc > 255) fc = 255; if (bc > 255) bc = 255; int r = fc + random.nextint(bc - fc); int g = fc + random.nextint(bc - fc); int b = fc + random.nextint(bc - fc); return new color(r, g, b); } private static int getrandomintcolor() { int[] rgb = getrandomrgb(); int color = 0; for (int c : rgb) { color = color << 8; color = color | c; } return color; } private static int[] getrandomrgb() { int[] rgb = new int[3]; for (int i = 0; i < 3; i++) { rgb[i] = random.nextint(255); } return rgb; } private static void shear(graphics g, int w1, int h1, color color) { shearx(g, w1, h1, color); sheary(g, w1, h1, color); } private static void shearx(graphics g, int w1, int h1, color color) { int period = random.nextint(2); boolean bordergap = true; int frames = 1; int phase = random.nextint(2); for (int i = 0; i < h1; i++) { double d = (double) (period >> 1) * math.sin((double) i / (double) period + (6.2831853071795862d * (double) phase) / (double) frames); g.copyarea(0, i, w1, 1, (int) d, 0); if (bordergap) { g.setcolor(color); g.drawline((int) d, i, 0, i); g.drawline((int) d + w1, i, w1, i); } } } private static void sheary(graphics g, int w1, int h1, color color) { int period = random.nextint(40) + 10; // 50; boolean bordergap = true; int frames = 20; int phase = 7; for (int i = 0; i < w1; i++) { double d = (double) (period >> 1) * math.sin((double) i / (double) period + (6.2831853071795862d * (double) phase) / (double) frames); g.copyarea(i, 0, 1, h1, 0, (int) d); if (bordergap) { g.setcolor(color); g.drawline(i, (int) d, i, 0); g.drawline(i, (int) d + h1, i, h1); } } } public static void main(string[] args) { file dir = new file("/users/zcqshine/downloads/test"); int w = 200, h= 80; for (int i = 0; i< 50; i++){ string verifycode = generateverifycode(4); file file = new file(dir, verifycode + ".jpg"); try { outputimage(w, h, file, verifycode); } catch (ioexception e) { e.printstacktrace(); } } } }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!如有疑问请留言或到本站社区交流讨论,大家共同进步!
上一篇: PHP 文件上传限制问题