生成验证码JSP【复用代码】

今天药忘吃喽~ 2021-09-17 06:42 481阅读 0赞

该JSP可以生成验证码。以后用到的时候就方便了。

  1. <%@ page language="java" pageEncoding="UTF-8"%>
  2. <%@ page contentType="image/jpeg" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" %>
  3. <%!
  4. public Color getColor(){
  5. Random random = new Random();
  6. int r = random.nextInt(256);//0-255
  7. int g = random.nextInt(256);
  8. int b = random.nextInt(256);
  9. return new Color(r,g,b);
  10. }
  11. public String getNum(){
  12. String str = "";
  13. Random random = new Random();
  14. for(int i=0;i<4;i++){
  15. str += random.nextInt(10);//0-9
  16. }
  17. return str;
  18. }
  19. %>
  20. <%
  21. response.setHeader("pragma", "mo-cache");
  22. response.setHeader("cache-control", "no-cache");
  23. response.setDateHeader("expires", 0);
  24. BufferedImage image = new BufferedImage(80,30,BufferedImage.TYPE_INT_RGB);
  25. Graphics g = image.getGraphics();
  26. g.setColor(new Color(200,200,200));
  27. g.fillRect(0,0,80,30);
  28. for (int i = 0; i < 30; i++) {
  29. Random random = new Random();
  30. int x = random.nextInt(80);
  31. int y = random.nextInt(30);
  32. int xl = random.nextInt(x+10);
  33. int yl = random.nextInt(y+10);
  34. g.setColor(getColor());
  35. g.drawLine(x, y, x + xl, y + yl);
  36. }
  37. g.setFont(new Font("serif", Font.BOLD,16));
  38. g.setColor(Color.BLACK);
  39. String checkNum = getNum();//"2525"
  40. StringBuffer sb = new StringBuffer();
  41. for(int i=0;i<checkNum.length();i++){
  42. sb.append(checkNum.charAt(i)+" ");//"2 5 2 5"
  43. }
  44. g.drawString(sb.toString(),15,20);
  45. session.setAttribute("CHECKNUM",checkNum);//2525
  46. ImageIO.write(image,"jpeg",response.getOutputStream());
  47. out.clear();
  48. out = pageContext.pushBody();
  49. %>

发表评论

表情:
评论列表 (有 0 条评论,481人围观)

还没有评论,来说两句吧...

相关阅读

    相关 jsp验证代码

    在开发中验证码是比较常用到有效防止这种问题对某一个特定注册用户用特定程序破解方式进行不断的登陆尝试的方式。 此演示程序 [包][Link 1]括三个文件: 1.logi