posts - 397,comments - 0,views - 25332

Respons_案例_输出字节数据

服务器输出字节数据到浏览器

  步骤:

    获取字节输出流

    输出数据

resp.setCharacterEncoding("text/html;charset=utf-8");

        ServletOutputStream outputStream = resp.getOutputStream();
        outputStream.write("你好".getBytes("utf-8"));

 

 

 

 

 

 

 

 

 

 

 

 

 

 

验证码分析

创建一对象,在内存中图(验证码对象)

美化图片

将图片输出到页面

 

 

复制代码
@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int width = 100;
        int height = 50;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        Graphics graphics = image.getGraphics();
        graphics.setColor(Color.PINK);
        graphics.fillRect(0,0,width,height);

        graphics.setColor(Color.BLUE);
        graphics.drawRect(0,0,width-1,height-1);


        String str = "ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

        Random random = new Random();
        for (int i = 1; i <=4; i++) {
            int i1 = random.nextInt(str.length());
            char c = str.charAt(i1);
            graphics.drawString(c+"",width/5*i,height/2);
        }

//        graphics.drawString("A",20,25);
//        graphics.drawString("B",40,25);
//        graphics.drawString("C",60,25);
//        graphics.drawString("D",80,25);


        graphics.setColor(Color.green);

        for (int i = 0; i <10; i++) {
            int x1 = random.nextInt(width);
            int x2 = random.nextInt(width);

            int y1 = random.nextInt(height);
            int y2 = random.nextInt(height);
            graphics.drawLine(x1,y1,x2,y2);
        }

        ImageIO.write(image,"jpg",resp.getOutputStream());
    }
复制代码

 

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        window.onload = function () {
           var img =  document.getElementById("checkCode");
           img.onclick = function () {

               var date = new Date().getTime();

                img.src = "/checkCodeServlet?"+date;
           }
        }
    </script>
</head>
<body>
    <img id="checkCode" src="/checkCodeServlet"/>
    <a id="change" href="">看不清换一张</a>
</body>
</html>
复制代码

 

 

posted on   淤泥不染  阅读(27)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示