servlet输出随机验证码

傷城~ 2022-08-12 01:05 242阅读 0赞
  1. public static final int WIDTH = 120;
  2. public static final int HEIGHT = 25;
  3. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  4. BufferedImage image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
  5. Graphics g = image.getGraphics();
  6. //1、设置背景色
  7. setBackGroud(g);
  8. //2.设置边框
  9. setBorder(g);
  10. //3.画干扰线
  11. drawRandomLine(g);
  12. //4.写随机数
  13. drawRandomNum((Graphics2D)g);
  14. //5.图形写给浏览器
  15. response.setContentType("image/jpeg");
  16. //发图控制浏览器不要缓存
  17. response.setDateHeader("expries", -1);
  18. response.setHeader("cache-control", "no-cache");
  19. response.setHeader("Pragma", "no-cache");
  20. ImageIO.write(image, "jpg", response.getOutputStream());
  21. }
  22. private void setBackGroud(Graphics g) {
  23. g.setColor(Color.WHITE);
  24. //填充矩形
  25. g.fillRect(0, 0, WIDTH, HEIGHT);
  26. }
  27. private void setBorder(Graphics g) {
  28. g.setColor(Color.BLUE);
  29. g.drawRect(1, 1, WIDTH-2, HEIGHT-2);
  30. }
  31. private void drawRandomLine(Graphics g) {
  32. g.setColor(Color.GREEN);
  33. for(int i=0; i<5; i++){
  34. int x1 = new Random().nextInt(WIDTH);
  35. int y1 = new Random().nextInt(HEIGHT);
  36. int x2 = new Random().nextInt(WIDTH);
  37. int y2 = new Random().nextInt(HEIGHT);
  38. g.drawLine(x1, y1, x2, y2);
  39. }
  40. }
  41. private void drawRandomNum(Graphics2D g) {
  42. g.setColor(Color.RED);
  43. g.setFont(new Font("宋体",Font.BOLD,20));
  44. //中文字所在区间 [\u4e00-\u9fa5]
  45. String base = "ABCDEFGHIJK";
  46. int x = 10;
  47. for(int i=0; i<4; i++){
  48. //设置旋转角度
  49. int degree = new Random().nextInt()%30;//生成正负30内数
  50. String ch = base.charAt(new Random().nextInt(base.length()))+"";
  51. g.rotate(degree*Math.PI/180, x, 20);
  52. g.drawString(ch, x, 20);
  53. g.rotate(-degree*Math.PI/180, x, 20);//旋转回去
  54. x+=30;
  55. }
  56. }

发表评论

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

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

相关阅读

    相关 前端随机验证

    [前端随机验证码 ][Link 1] 前端登录或者注册的时候经常会有一个验证码,数字或者字母,本验证码是基于canves的。 使用方法:   <!DOCTY