1. package com.code.monkey.web.servlet;
    2. import javax.imageio.ImageIO;
    3. import javax.servlet.ServletException;
    4. import javax.servlet.annotation.WebServlet;
    5. import javax.servlet.http.HttpServlet;
    6. import javax.servlet.http.HttpServletRequest;
    7. import javax.servlet.http.HttpServletResponse;
    8. import java.awt.*;
    9. import java.awt.image.BufferedImage;
    10. import java.io.IOException;
    11. import java.util.Random;
    12. @WebServlet("/checkCodeServlet")
    13. public class CheckCodeServlet extends HttpServlet {
    14. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    15. int width = 100;
    16. int height = 50;
    17. //1.创建一对象,在内存中图片(验证码图片对象)
    18. BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
    19. //2.美化图片
    20. //2.1 填充背景色
    21. Graphics g = image.getGraphics();//画笔对象
    22. g.setColor(Color.PINK);//设置画笔颜色
    23. g.fillRect(0,0,width,height);
    24. //2.2画边框
    25. g.setColor(Color.BLUE);
    26. g.drawRect(0,0,width - 1,height - 1);
    27. String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789";
    28. //生成随机角标
    29. Random ran = new Random();
    30. StringBuilder sb = new StringBuilder();
    31. for (int i = 1; i <= 4; i++) {
    32. int index = ran.nextInt(str.length());
    33. //获取字符
    34. char ch = str.charAt(index);//随机字符
    35. sb.append(ch);
    36. //2.3写验证码
    37. g.drawString(ch+"",width/5*i,height/2);
    38. }
    39. String checkCode_session = sb.toString();
    40. //将验证码存入session
    41. request.getSession().setAttribute("checkCode_session",checkCode_session);
    42. //2.4画干扰线
    43. g.setColor(Color.GREEN);
    44. //随机生成坐标点
    45. for (int i = 0; i < 10; i++) {
    46. int x1 = ran.nextInt(width);
    47. int x2 = ran.nextInt(width);
    48. int y1 = ran.nextInt(height);
    49. int y2 = ran.nextInt(height);
    50. g.drawLine(x1,y1,x2,y2);
    51. }
    52. //3.将图片输出到页面展示
    53. ImageIO.write(image,"jpg",response.getOutputStream());
    54. }
    55. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    56. this.doPost(request,response);
    57. }
    58. }