使用servlet画验证码

/**

*servlet

*/

public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  response.setContentType("text/html");
  response.setCharacterEncoding("utf-8");
  request.setCharacterEncoding("utf-8");

  //生成随机数字
  int width =80;
  int height=30;
  String code = "";
  Random random = new Random();
  //循环连接字符串
  for(int i=0;i<4;i++){
   code+= String.valueOf((char)(65 + random.nextInt(26)));
  }
  //保存这个字符到session
  HttpSession session = request.getSession();
  session.setAttribute("code", code);
  
  //生成图片
  BufferedImage bg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
  
  //将验证码写到图片上
  Graphics2D g  = bg.createGraphics();
  g.setColor(Color.white);
  g.fillRect(0, 0, width, height);
  
  g.setColor(Color.darkGray);
  for(int i = 0 ; i < 5; i++){
   int x1 = random.nextInt(width);
   int x2 = random.nextInt(width);
   int y1 = random.nextInt(height);
   int y2 = random.nextInt(height);
   g.drawLine(x1, y1, x2, y2);
  }
  
  g.setColor(Color.LIGHT_GRAY);
  for(int i = 0 ; i < 1000 ; i++){
   int x = random.nextInt(width);
   int y = random.nextInt(height);
   g.drawLine(x, y, x, y);
  }
  
  // 边框
  g.setColor(Color.gray);
  g.drawRect(0, 0, width -1, height -1);
  
  // 写字
  g.setColor(Color.GRAY);
  g.setFont(new Font("微软雅黑",Font.BOLD , 18));
  
  g.drawString(code, 10, 22);
  
  //响应到客户端
  response.setContentType("image/gif");
  ServletOutputStream sos = response.getOutputStream();
  ImageIO.write(bg, "gif", sos);
  sos.close();
 }

 

<!--调用的页面的javascript-->

<script type="text/javascript">
  function changeCode(sender){
   //在servlet后面要添加一个随机数来保证每次的点击都是获得不同的图片
   sender.src = 'checkPic?rand=' + Math.random();
  }
 </script>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值