Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the background verification function of generating CAPTCHA at Java backend

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces how to achieve Java back-end generation of CAPTCHA background verification function, the article is very detailed, has a certain reference value, interested friends must read it!

Directly jump severlet to generate the verification code in the java background:

@ RequestMapping (value= "yzm.action") public void Yzm (HttpSession session,HttpServletResponse resp) {/ / the width of the CAPTCHA picture. Int width = 60; / / the height of the CAPTCHA image. Int height = 20; / / CAPTCHA characters int codeCount = 4; int x = 0; / / Font height int fontHeight; int codeY Char [] codeSequence = {'A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y' 'Zhuan, '0here,' 1century, '2percent,' 3percent, '4percent,' 5percent, '6percent,' 7percent, '8percent,' 9'} X = width / (codeCount + 1); fontHeight = height-2; codeY = height-4; BufferedImage buffImg = new BufferedImage (width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = buffImg.createGraphics (); / / create a random number generator class Random random = new Random (); / / fill the image with white g.setColor (Color.WHITE); g.fillRect (0,0, width, height) / / create a font. The font size should be based on the height of the picture. Font font = new Font ("Fixedsys", Font.PLAIN, fontHeight); / / sets the font. G.setFont (font); / / draw the border. / / g.setColor (Color.BLACK); / / g.drawRect (0,0, width-1, height-1); / / randomly generate 160interference lines, so that the authentication code in the image is not easily detected by other programs. G.setColor (Color.BLACK); for (int I = 0; I

< 1; i++) { int x2 = random.nextInt(width); int y2 = random.nextInt(height); int xl = random.nextInt(12); int yl = random.nextInt(12); g.drawLine(x2, y2, x + xl, y2 + yl); } // randomCode用于保存随机产生的验证码,以便用户登录后进行验证。 StringBuffer randomCode = new StringBuffer(); int red = 0, green = 0, blue = 0; // 随机产生codeCount数字的验证码。 for (int i = 0; i < codeCount; i++) { // 得到随机产生的验证码数字。 String strRand = String.valueOf(codeSequence[random.nextInt(36)]); // 产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同。 red = random.nextInt(255); green = random.nextInt(255); blue = random.nextInt(255); // 用随机产生的颜色将验证码绘制到图像中。 g.setColor(new Color(red, green, blue)); g.drawString(strRand, (i + 1) * x, codeY); // 将产生的四个随机数组合在一起。 randomCode.append(strRand); } // 将四位数字的验证码保存到Session中。 session.setAttribute("validateCode", randomCode.toString()); ServletOutputStream sos; try { sos = resp.getOutputStream(); ImageIO.write(buffImg, "jpeg", sos); sos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } jsp显示页面的代码,点击图片刷新

${validateCode} $("# img") .click (function () {$(this) .attr ("src", "yzm.action?" + new Date () .getTime ());})

Pass the value in the text box to the background and compare it with the random number that initially generated the CAPTCHA to complete the verification.

The value of the session obtained on the page is always one step behind the CAPTCHA, so it is verified in the background. I don't know why here. I hope my friends will let me know.

Another way of thinking is to generate random numbers in the background, generate canvas at the front end, and take random numbers with ajax.

/ / the background only generates the random number @ RequestMapping (value= "random.action") public void findRandom (HttpServletResponse response) throws IOException {/ / the number of CAPTCHA characters int codeCount = 4 Char [] codeSequence = {'A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y' 'Zhuan, '0here,' 1century, '2percent,' 3percent, '4percent,' 5percent, '6percent,' 7percent, '8percent,' 9'} / / create a random number generator class Random random = new Random (); / / randomCode is used to save the randomly generated CAPTCHA so that the user can verify after logging in. StringBuffer randomCode = new StringBuffer (); for (int I = 0; I < codeCount; verification +) {/ / get randomly generated CAPTCHA numbers. String strRand = String.valueOf (codeSequence.nextInt (36)); / / combine the four random numbers generated. RandomCode.append (strRand);} PrintWriter out = response.getWriter (); out.print (randomCode);}

Jsp,jq,js code

Get another $.ajax ({url: "random.action", success:function (k) {console.log (k) $("# yzms"). Attr ("value", k); drawPic ();}}) $("# img"). On ("click", function () {var _ this=$ (this) $.ajax ({url: "random.action", success:function (k) {console.log (k) $("# yzms"). Attr ("value", k); drawPic () }}) / * * generate a random number * * / function randomNum (min,max) {return Math.floor (Math.random () * (max-min) + min);} / * * generate a random color * * / function randomColor (min,max) {var r = randomNum (min,max); var g = randomNum (min,max); var b = randomNum (min,max); return "rgb (" + r + "," + g + "," + b + ")" } / * * draw CAPTCHA image * * / function drawPic () {var canvas=document.getElementById ("canvas"); var width=canvas.width; var height=canvas.height; var ctx = canvas.getContext ('2d'); ctx.textBaseline =' bottom'; / * * draw background color * * / ctx.fillStyle = randomColor (180240); / / if the color is too dark, it may cause ctx.fillRect to be blurred; / * draw text * * / / * for (var item0; I)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report