• Session应用之验证码


     1 package com.aeolia.view;
     2 
     3 import java.awt.Color;
     4 import java.awt.Font;
     5 import java.awt.image.BufferedImage;
     6 import java.io.IOException;
     7 import javax.imageio.ImageIO;
     8 import javax.servlet.ServletException;
     9 import javax.servlet.http.HttpServlet;
    10 import javax.servlet.http.HttpServletRequest;
    11 import javax.servlet.http.HttpServletResponse;
    12 
    13 public class CheckCode extends HttpServlet {
    14     public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    15 
    16         //禁止浏览器缓存随即图片
    17         response.setDateHeader("Expires", -1);
    18         response.setHeader("Cache-Control", "no-cache");
    19         response.setHeader("Pragma", "no-cahce");
    20         //通知客户机以图片方式打开发送过去的数据
    21         response.setHeader("Content-Type","image/jpeg");
    22         //在内存中创建一幅图片
    23         java.awt.image.BufferedImage image=new BufferedImage(80,30,BufferedImage.TYPE_INT_RGB);
    24         //向图片上写数据
    25         java.awt.Graphics g=image.getGraphics();
    26         //设置背景色
    27         g.setColor(Color.white);
    28         //设置矩形框
    29         g.fillRect(0,0,80,30);
    30         //设置背景色写入数据的字体和颜色
    31         g.setColor(Color.red);
    32         g.setFont(new Font(null,Font.BOLD,20));
    33         //向图片上写数据
    34         String nums=makeNums();
    35         request.getSession().setAttribute("checkcode", nums);
    36         g.drawString(nums, 0,20);
    37         //把写好的数据的图片输出给浏览器
    38         ImageIO.write(image, "jpg", response.getOutputStream());
    39     }
    40     private String makeNums() {
    41         java.util.Random r=new java.util.Random();
    42         String nums=r.nextInt(9999)+"";
    43         StringBuffer sb=new StringBuffer(nums);
    44         for(int i=0;i<4-nums.length();i++){
    45             sb.append("0");
    46         }
    47         return sb.toString();
    48     }
    49     public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    50 
    51         this.doGet(request, response);
    52     }
    53 }
  • 相关阅读:
    软件测试_禅道
    软件测试_Fiddler抓包工具二
    软件测试_Fiddler抓包工具一
    软件测试_缺陷
    软件测试_测试用例
    软件测试_项目实践
    软件测试_MYSQL
    高级案例(2018年下答案**)
    高级案例(2018年下题目)
    高级案例(2019年上题目)
  • 原文地址:https://www.cnblogs.com/aeolia/p/4163037.html
Copyright © 2020-2023  润新知