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>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)