黑马程序员技术交流社区

标题: 学习心得 [打印本页]

作者: 星空下第一高手    时间: 2019-9-12 15:35
标题: 学习心得
package itvast.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("/ckeckCodeDemo01")
public class CheckCodeDemo extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       //设置编码格式
        //response.setContentType("charset=utf-8");
        int wight = 100;
        int height = 50;
       //创建一个对象,在内存中图片
        BufferedImage img = new BufferedImage(wight,height,BufferedImage.TYPE_3BYTE_BGR);

        //美化图片
        Graphics g = img.getGraphics();
        g.setColor(Color.PINK);
        g.fillRect(0,0,wight,height);
        g.setColor(Color.BLUE);
        g.drawRect(0,0,wight-1,height-1);
        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random ran = new Random();
        StringBuilder sb = new StringBuilder();
        for(int i = 1; i <= 4; i++) {
            int a = ran.nextInt(str.length());
            char chr = str.charAt(a);
            sb.append(chr);
            g.drawString(chr+"",wight/5*i,height/2);
        }
        String checkCode_session = sb.toString();
        request.getSession().setAttribute("checkCode_session",checkCode_session);
        for(int i = 0; i <= 6; i++) {
            int x1 = ran.nextInt(wight);
            int x2 = ran.nextInt(wight);
            int y1 = ran.nextInt(height);
            int y2 = ran.nextInt(height);
            g.drawLine(x1,y1,x2,y2);
        }


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

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2