servlet验证码

分手后的思念是犯贱 2022-06-11 06:07 236阅读 0赞

public class AuthImageServlet extends HttpServlet
{
private static final String CONTENT_TYPE = “text/html; charset=gb2312”;
//设置字母的大小,大小
private Font mFont = new Font(“Times New Roman”, Font.PLAIN, 17);

  1. public void init() throws ServletException
  2. \{
  3. super.init();
  4. \}
  5. Color getRandColor(int fc,int bc)
  6. \{
  7. Random random = new Random();
  8. if(fc>255) fc=255;
  9. if(bc>255) bc=255;
  10. int r=fc+random.nextInt(bc-fc);
  11. int g=fc+random.nextInt(bc-fc);
  12. int b=fc+random.nextInt(bc-fc);
  13. return new Color(r,g,b);
  14. \}
  15. public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  16. \{
  17. response.setHeader("Pragma","No-cache");
  18. response.setHeader("Cache-Control","no-cache");
  19. response.setDateHeader("Expires", 0);
  20. //表明生成的响应是图片
  21. response.setContentType("image/jpeg");
  22. int width=100, height=18;
  23. BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE\_INT\_RGB);
  24. Graphics g = image.getGraphics();
  25. Random random = new Random();
  26. g.setColor(getRandColor(200,250));
  27. g.fillRect(1, 1, width-1, height-1);
  28. g.setColor(new Color(102,102,102));
  29. g.drawRect(0, 0, width-1, height-1);
  30. g.setFont(mFont);
  31. g.setColor(getRandColor(160,200));
  32. //画随机线
  33. for (int i=0;i<155;i++)
  34. \{
  35. int x = random.nextInt(width - 1);
  36. int y = random.nextInt(height - 1);
  37. int xl = random.nextInt(6) + 1;
  38. int yl = random.nextInt(12) + 1;
  39. g.drawLine(x,y,x + xl,y + yl);
  40. \}
  41. //从另一方向画随机线
  42. for (int i = 0;i < 70;i++)
  43. \{
  44. int x = random.nextInt(width - 1);
  45. int y = random.nextInt(height - 1);
  46. int xl = random.nextInt(12) + 1;
  47. int yl = random.nextInt(6) + 1;
  48. g.drawLine(x,y,x - xl,y - yl);
  49. \}
  50. //生成随机数,并将随机数字转换为字母
  51. String sRand="";
  52. for (int i=0;i<6;i++)
  53. \{
  54. int itmp = random.nextInt(26) + 65;
  55. char ctmp = (char)itmp;
  56. sRand += String.valueOf(ctmp);
  57. g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
  58. g.drawString(String.valueOf(ctmp),15\*i+10,16);
  59. \}
  60. HttpSession session = request.getSession(true);
  61. session.setAttribute("rand",sRand);
  62. g.dispose();
  63. ImageIO.write(image, "JPEG", response.getOutputStream());
  64. \}
  65. public void destroy()
  66. \{
  67. \}

}

然后在jsp中的图片上通过src=”该servlet的路径”就可以了

发表评论

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

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

相关阅读

    相关 jsp使用servlet实现验证

    在进行表单设计中,验证码的增加恰恰可以实现是否为“人为”操作,增加验证码可以防止网站数据库信息的冗杂等... 现在,小编将讲述通过servlet实现验证码: 验证码作为一个