后端验证码文件

  1. package web;
  2. import java.awt.Color;
  3. import java.awt.Font;
  4. import java.awt.Graphics;
  5. import java.awt.image.BufferedImage;
  6. import java.io.IOException;
  7. import java.io.OutputStream;
  8. import java.util.Random;
  9. import javax.servlet.ServletException;
  10. import javax.servlet.http.HttpServlet;
  11. import javax.servlet.http.HttpServletRequest;
  12. import javax.servlet.http.HttpServletResponse;
  13. import javax.servlet.http.HttpSession;
  14. public class CheckcodeServlet extends HttpServlet {
  15. public void service(HttpServletRequest request, HttpServletResponse response)
  16. throws ServletException, IOException {
  17. System.out.println("CheckcodeServlet's service");
  18. /*
  19. * 一、绘图
  20. */
  21. /*
  22. * step1,创建一个内存映像对象(画布)
  23. * BufferedImage(宽度,高度,类型)
  24. */
  25. BufferedImage image =
  26. new BufferedImage(80,30,
  27. BufferedImage.TYPE_INT_RGB);
  28. /*
  29. * step2,获得一个画笔
  30. */
  31. Graphics g = image.getGraphics();
  32. /*
  33. * step3,给笔设置颜色
  34. */
  35. Random r = new Random();
  36. g.setColor(new Color(255,255,255));
  37. /*
  38. * step4,给画布设置背景颜色
  39. * fillRect(x,y,width,height)
  40. */
  41. g.fillRect(0, 0, 80, 30);
  42. /*
  43. * step5,绘图
  44. */
  45. g.setColor(new Color(r.nextInt(255),
  46. r.nextInt(255),r.nextInt(255)));
  47. //Font(字体,风格,大小)
  48. g.setFont(new Font(null,Font.ITALIC,22));
  49. String number = getNumber(5);
  50. //将number绑订到session对象上
  51. HttpSession session =
  52. request.getSession();
  53. session.setAttribute("number", number);
  54. //drawString(String,x,y) x,y是左下角的坐标
  55. g.drawString(number, 2, 23);
  56. //step6,加一些干扰线
  57. for(int i=0;i<6;i++){
  58. g.drawLine(r.nextInt(80),
  59. r.nextInt(30),
  60. r.nextInt(80), r.nextInt(30));
  61. }
  62. /*
  63. * 二、将图片压缩并发送给浏览器
  64. */
  65. //设置content-type消息头,告诉
  66. //浏览器返回的是图片
  67. response.setContentType("image/jpeg");
  68. //一定要获得字节输出流
  69. OutputStream ops = response.getOutputStream();
  70. //write方法会对原始图片(image)按照
  71. //指定的压缩算法(jpeg)进行压缩,并且
  72. //将压缩之后的数据输出到指定的流(ops)。
  73. javax.imageio.ImageIO.write(image, "jpeg", ops);
  74. ops.close();
  75. }
  76. /*
  77. * 生成一个验证码,该验证码由"A~Z","0~9"中
  78. 随机选取5个字符组成
  79. */
  80. private String getNumber(int size) {
  81. String rs = "";
  82. String strs = "ABCDEFGHIJKLMNOPQ" +
  83. "RSTUVWXYZ0123456789";
  84. Random r = new Random();
  85. for(int i=0;i<size;i++){
  86. rs += strs.charAt(r.nextInt(strs.length()));
  87. }
  88. return rs;
  89. }
  90. }

前台的验证码的获取方式

  1. $(this).find( "img").attr("src" ,"../getcode.htm?num=" +num);