案例(黑马)—— 简单验证码

package com.qgl.web.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
    private int width = 100;
    private int height = 50;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 创建一个对象,用来在内存中画图
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

        // 美化图片
        // 填充矩形
        Graphics g = image.getGraphics();   // 获取画笔
        g.setColor(Color.PINK);             // 设置画笔颜色
        g.fillRect(0,0,width,height);
        // 画边宽
        g.setColor(Color.BLUE);
        g.drawRect(0,0,width-1,height-1);
        // 随机画字符
        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random rd = new Random();
        // 画干扰线
        for (int i = 1; i <8 ; i++) {
            int x1 = rd.nextInt(width);
            int x2 = rd.nextInt(width);
            int y1 = rd.nextInt(height);
            int y2 = rd.nextInt(height);
            g.drawLine(x1,x2,y1,y2);
        }
        // 画验证码
        g.setColor(Color.BLACK);
        for (int i = 1; i <=4; i++) {
            int index = rd.nextInt(str.length());
            char c = str.charAt(index);
            g.drawString(c+"",width/5*i,height/2);
        }

        // 输出图片到页面展示
        ImageIO.write(image,"jpg",resp.getOutputStream());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
<html>
  <head>
    <title>checkcodetitle>
    <script>
      // 加载完后
      window.onload = function () {
          // 获取图片与超链接元素
          var change1 = document.getElementById("clickimg");
          var change2 = document.getElementById("clickchar");
          // 电机图片与超链接切换图片
          change1.onclick = function () {
              // 使用时间戳
              var time = new Date().getTime();
              change1.src = "/case/checkCodeServlet?"+time;
          }
          change2.onclick = function () {
              var time = new Date().getTime();
              change1.src = "/case/checkCodeServlet?"+time;
          }
      }
    script>
  head>
  <body>
    <img id="clickimg" src="/case/checkCodeServlet">
    <a id="clickchar" href="">看不清,换一张a>
  body>
html>

你可能感兴趣的:(案例项目学习,javascript,java)