captcha.jsp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <%@ page contentType="image/jpeg" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" %>
  2. <%!
  3. // 给定范围获得随机颜色
  4. Color getRandColor(int fc,int bc) {
  5. Random random = new Random();
  6. if(fc > 255) {
  7. fc = 255;
  8. }
  9. if(bc > 255) {
  10. bc = 255;
  11. }
  12. int r = fc + random.nextInt(bc - fc);
  13. int g = fc + random.nextInt(bc - fc);
  14. int b = fc + random.nextInt(bc - fc);
  15. return new Color(r, g, b);
  16. }
  17. %>
  18. <%
  19. //设置页面不缓存
  20. response.setHeader("Pragma", "No-cache");
  21. response.setHeader("Cache-Control", "no-cache");
  22. response.setDateHeader("Expires", 0);
  23. // 在内存中创建图象
  24. int width = 60, height = 20;
  25. BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
  26. // 获取图形上下文
  27. Graphics g = image.getGraphics();
  28. //生成随机类
  29. Random random = new Random();
  30. // 设定背景色
  31. g.setColor(getRandColor(200,250));
  32. g.fillRect(0, 0, width, height);
  33. //设定字体
  34. g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
  35. //画边框
  36. //g.setColor(new Color());
  37. //g.drawRect(0,0,width-1,height-1);
  38. // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
  39. g.setColor(getRandColor(160, 200));
  40. for (int i = 0; i < 155; i++) {
  41. int x = random.nextInt(width);
  42. int y = random.nextInt(height);
  43. int xl = random.nextInt(12);
  44. int yl = random.nextInt(12);
  45. g.drawLine(x,y,x+xl,y+yl);
  46. }
  47. // 取随机产生的认证码(4位数字)
  48. String sRand = "";
  49. for (int i = 0;i < 4; i++) {
  50. String rand = String.valueOf(random.nextInt(10));
  51. sRand += rand;
  52. // 将认证码显示到图象中
  53. // 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
  54. g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
  55. g.drawString(rand, 13 * i + 6, 16);
  56. }
  57. // 将认证码存入SESSION
  58. session.setAttribute("captcha", sRand);
  59. // 图象生效
  60. g.dispose();
  61. // 输出图象到页面
  62. ImageIO.write(image, "JPEG", response.getOutputStream());
  63. out.clear();
  64. out = pageContext.pushBody();
  65. %>