码迷,mamicode.com
首页 > 其他好文 > 详细

Response的常见应用

时间:2020-04-04 22:18:53      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:NPU   ext   write   encoder   ima   set   code   lis   direct   

验证码

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int width = 50;
        int height = 20;
        //bufferedImage相当于画板
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //graphics相当于画笔
        Graphics2D graphics = (Graphics2D) bufferedImage.getGraphics();
        //消除线条锯齿
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        graphics.setColor(Color.white);
        //设置填充矩形
        graphics.fillRect(0, 0, width, height);
        graphics.setColor(Color.BLUE);
        //参数三为字体大小
        graphics.setFont(new Font("微软雅黑", Font.BOLD, height));
        //随机生成四位数字
        Random random = new Random();
        StringBuilder str = new StringBuilder();
        for (int i = 0; i <= 3; i++) {
            int num = random.nextInt(10);
            str.append(num);
        }
        //添加文字
        graphics.drawString(str.toString(), 0, height - 2);
        //添加干扰线
        graphics.setColor(Color.LIGHT_GRAY);
        for(int i=0;i<=15;i++){
            int x1=random.nextInt(width);
            int y1=random.nextInt(height);
            int x2=random.nextInt(width);
            int y2=random.nextInt(height);
            graphics.drawLine(x1,y1,x2,y2);
        }
        resp.setHeader("Content-Type", "jpg");
        ImageIO.write(bufferedImage, "jpg", resp.getOutputStream());
    }

文件下载

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String realPath = this.getServletContext().getRealPath("\\企鹅.jpg");
        //截取文件名
        String filename = realPath.substring(realPath.lastIndexOf("\\") + 1);
        FileInputStream fileInputStream = new FileInputStream(realPath);
        ServletOutputStream outputStream = resp.getOutputStream();
        //设置UTF-8编码,防止文件名是中文时产生乱码
        resp.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode(filename,"utf-8"));
        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len = fileInputStream.read(bytes)) > 0) {
            outputStream.write(bytes, 0, len);
        }
        fileInputStream.close();
        outputStream.close();
    }

自动刷新

案例1:

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //‘resp.setContentType("text/html;charset=utf-8");‘要在‘PrintWriter writer = resp.getWriter()‘之前
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.write("时间:"+System.currentTimeMillis());
        resp.setHeader("Refresh","2");
    }

案例2:

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("Refresh","3;url=‘http://www.baidu.com‘")
        ServletOutputStream outputStream = resp.getOutputStream();
        outputStream.write("三秒后跳转百度...".getBytes())
    }

数据压缩

        resp.setContentType("text/html;charset=utf-8");
        resp.setHeader("Content-Encoding","gzip");
        String str = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" +
                "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" +
                "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" +
                "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" +
                "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);
        gzipOutputStream.write(str.getBytes());
        gzipOutputStream.close();
        byte[] bytes = byteArrayOutputStream.toByteArray();
        ServletOutputStream outputStream = resp.getOutputStream();
        outputStream.write(bytes);

重定向

    //Redircet()就是对SetStatus()和SetHeader()的封装,resp.Redirect("/abc.jsp")和下面等效
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //HttpServletResponse.SC_MOVED_TEMPORARILY=302,为状态码
        resp.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
        resp.setHeader("Location", "/abc.jsp");
    }

不使用缓存

    //设置三个,为了兼容性
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setDateHeader("Expires", -1);
        resp.setHeader("Cache-Control","no-cache");
        resp.setHeader("Pragma", "no-cache");
    }

注意事项:
1. getWriter()和getOutputStream()两个方法不能同时调用。
2. Servlet的serice()方法结束后(也就是doPost()或者doGet()结束后),Servlet引擎将检查getWriter或getOutputStream方法返回的输出流对象是否已经调用过close方法,如果没有,Servlet引擎将调用close方法关闭该输出流对象.

Response的常见应用

标签:NPU   ext   write   encoder   ima   set   code   lis   direct   

原文地址:https://www.cnblogs.com/kwdlh/p/12634477.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!