欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

javaweb之Servlet中response对象

程序员文章站 2022-05-13 19:05:41
...

一,概述

功能:设置响应消息
1,设置响应行
格式:HTTP/1.1 200 ok
设置状态码:setStatus(int sc)

2,设置响应头:
setHeader(String name, String value)

3,设置响应体:

使用步骤:
(1),获取输出流
字符输出流:PrintWriter getWriter()
字节输出流:ServletOutputStream getOutputStream()
(2),使用输出流,将数据输出到客户端浏览器

二,重定向案例

@WebServlet("/responseDemo1")
public class ResponseDemo1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("demo...");

        
        response.setStatus(302);
        /*
        response.setHeader("location","/day4/responseDemo2");
        */

        //动态获取虚拟目录
        String contextPath = request.getContextPath();
        response.sendRedirect(contextPath + "/responseDemo2");
    }

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

@WebServlet("/responseDemo2")
public class ResponseDemo2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("demo2....");
    }

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

forward和redirect区别

重定向的特点:redirect
1,地址栏发生变化
2,重定向可以访问其他站点(服务器)的资源
3,重定向是两次请求。不能使用request对象来共享数据

转发的特点:forward
1,转发地址栏路径不变
2,转发只能访问当前服务器下的资源
3,转发是一次请求,可以使用request对象来共享数据

路径写法:
1,路径分类

  1. 相对路径:通过相对路径不可以确定唯一资源,如:./index.html、不以/开头,以.开头路径
    规则:找到当前资源和目标资源之间的相对位置关系
    ./:当前目录
    …/:后退一级目录
  2. 绝对路径:通过绝对路径可以确定唯一资源,如:http://localhost/day15/responseDemo2 /day15/responseDemo2、以/开头的路径;
    规则:判断定义的路径是给谁用的?判断请求将来从哪儿发出
    给客户端浏览器使用:需要加虚拟目录(项目的访问路径),建议虚拟目录动态获取:request.getContextPath(),如<a> , <form>重定向…
    给服务器使用:不需要加虚拟目录,如转发路径。

三,服务器输出数据到浏览器

1,服务器输出字符数据到浏览器:
步骤:
(1),获取字符输出流
(2),输出数据

注意:乱码问题:
(1),PrintWriter pw = response.getWriter();获取的流的默认编码是ISO-8859-1
(2),设置该流的默认编码
(3),告诉浏览器响应体使用的编码

//简单的形式,设置编码,是在获取流之前设置
response.setContentType("text/html;charset=utf-8");

2,服务器输出字节数据到浏览器
步骤:
(1).获取字节输出流
(2).输出数据

@WebServlet("/responseDemo3")
public class ResponseDemo3 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置响应消息体的编码
        response.setContentType("text/html;charset=utf-8");
        //获取流
        PrintWriter pw = response.getWriter();

        pw.write("你好啊,response...");
    }

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

@WebServlet("/responseDemo4")
public class ResponseDemo4 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        ServletOutputStream sos = response.getOutputStream();
        sos.write("你好".getBytes("utf-8"));
    }

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

3,验证码案例:

  1. 本质:图片
  2. 目的:防止恶意表单注册
@WebServlet("/checkCodeDemo1")
public class CheckCodeDemo1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int width = 200;
        int height = 100;
        //创建图片对象
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

        //美化图片
        Graphics gh = image.getGraphics();
        gh.setColor(Color.PINK);
        gh.fillRect(0,0,width,height);//填充矩形

        gh.setColor(Color.BLUE);
        gh.drawRect(0,0,width-1,height-1);//画边框

        Random rd = new Random();
        String s = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
        for (int i = 1; i <= 4; i++) {
            int index = rd.nextInt(s.length());
            char ch = s.charAt(index);
            gh.drawString(ch+"",width/5*i,height/2);
        }

        gh.setColor(Color.GREEN);
        for (int i = 0; i < 10; i++) {
            int x1 = rd.nextInt(width);
            int x2 = rd.nextInt(width);
            int y1 = rd.nextInt(height);
            int y2 = rd.nextInt(height);
            gh.drawLine(x1,y1,x2,y2);

        }


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

    }

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

前端页面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        window.onload = function () {
            var checkImag = document.getElementById("checkImag");
            checkImag.onclick = function () {
                var time = new Date().getTime();
                checkImag.src = "/day4/checkCodeDemo1?"+time;
            };
        };

        function testClick() {
            var checkImag = document.getElementById("checkImag");
            var time = new Date().getTime();
            checkImag.src = "/day4/checkCodeDemo1?"+time;

        }
    </script>
</head>
<body>
    <img id="checkImag" src="/day4/checkCodeDemo1" alt="">

    <a id="nextImge" href="javascript:testClick()">看不清?点击下一张</a>
</body>
</html>

四,ServletContext对象

1,概念:代表整个web应用,可以和程序的容器(服务器)来通信

2,获取:

  1. 通过request对象获取,request.getServletContext();
  2. 通过HttpServlet获取,this.getServletContext();
@WebServlet("/servletContextDemo1")
public class ServletContextDemo1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext context1 = this.getServletContext();
        ServletContext context2 = request.getServletContext();
        System.out.println(context1);
        //aaa@qq.com
        System.out.println(context2);
        //aaa@qq.com
        System.out.println(context1 == context2); //true
    }

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

3,功能:

(1),获取MIME类型:
MIME类型:在互联网通信过程中定义的一种文件数据类型
格式: 大类型/小类型 text/html image/jpeg
获取:String getMimeType(String file)

@WebServlet("/servletContextDemo2")
public class ServletContextDemo2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        String filename = "视频.mp4";
        //1,获取MIME类型(文件类型)
        String mimeType = context.getMimeType(filename);
        System.out.println(mimeType);
        // video/mp4
    }

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

(2),域对象:共享数据
setAttribute(String name,Object value)
getAttribute(String name)
removeAttribute(String name)
ServletContext对象范围:所有用户所有请求的数据

@WebServlet("/servletContextDemo3")
public class ServletContextDemo3 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext context1 = this.getServletContext();
        context1.setAttribute("msg","正确");

    }

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

@WebServlet("/servletContextDemo4")
public class ServletContextDemo4 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        Object msg = context.getAttribute("msg");
        System.out.println(msg);//正确
    }

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

3,获取文件的真实(服务器)路径
javaweb之Servlet中response对象
方法:

@WebServlet("/servletContextDemo5")
public class ServletContextDemo5 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        //获取资源真实路径
        String realPath1 = context.getRealPath("/b.txt");

        String realPath2 = context.getRealPath("/WEB-INF/c.txt");

        String realPath3 = context.getRealPath("/WEB-INF/class/a.txt");

        System.out.println(realPath1);
        System.out.println(realPath2);
        System.out.println(realPath3);
        /*
            E:\Java_Project\out\artifacts\day4_war_exploded\b.txt
            E:\Java_Project\out\artifacts\day4_war_exploded\WEB-INF\c.txt
            E:\Java_Project\out\artifacts\day4_war_exploded\WEB-INF\class\a.txt
         */
    }

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

五,servlet文件下载案例

文件下载需求:

  1. 页面显示超链接
  2. 点击超链接后弹出下载提示框
  3. 完成图片文件下载

分析:

  1. 超链接指向的资源如果能够被浏览器解析,则在浏览器中展示,如果不能解析,则弹出下载提示框。不满足需求
  2. 任何资源都必须弹出下载提示框
  3. 使用响应头设置资源的打开方式:content-disposition:attachment;filename=xxx

步骤:

  1. 定义页面,编辑超链接href属性,指向Servlet,传递资源名称filename
  2. 定义Servlet
    (1),获取文件名称
    (2),使用字节输入流加载文件进内存
    (3),指定response的响应头: content-disposition:attachment;filename=xxx
    (4),将数据写出到response输出流
@WebServlet("/downloadServlet")
public class DownloadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //将文件写入内存
        String filename = request.getParameter("filename");
        ServletContext context = request.getServletContext();
        String realPath = context.getRealPath("/source/" + filename);
        System.out.println(realPath);
        FileInputStream fis = new FileInputStream(realPath);

        //设置头信息,以附件形式
        String mimeType = context.getMimeType(filename);
        response.setHeader("content-type",mimeType);
        String agent = request.getHeader("user-agent");
        //使用工具包,适配各个浏览器中文乱码问题
        filename = DownLoadUtils.getFileName(agent,filename);
        response.setHeader("content-disposition","attachment;filename="+filename);

        //将资源写到页面上
        ServletOutputStream sos = response.getOutputStream();
        byte[] bytes = new byte[1024];
        int len = 0;


        while ((len = fis.read(bytes)) != -1){
            sos.write(bytes,0,len);
        }

        fis.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
DownLoadUtils工具包:

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.Base64.Encoder;


public class DownLoadUtils {

    public static String getFileName(String agent, String filename) throws UnsupportedEncodingException {
        if (agent.contains("MSIE")) {
            // IE浏览器
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+", " ");
        } else if (agent.contains("Firefox")) {
            // 火狐浏览器
            Encoder encoder = Base64.getEncoder();
            filename = "=?utf-8?B?" + encoder.encodeToString(filename.getBytes("utf-8")) + "?=";

        } else {
            // 其它浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        return filename;
    }

}
前端页面
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <a href="/day4/source/1.jpg">图片1</a>
    <a href="/day4/source/01.avi">视频1</a>
    <br>
    <a href="/day4/downloadServlet?filename=皮卡丘.jpg">图片2</a>
    <a href="/day4/downloadServlet?filename=java传智.avi">视频2</a>

</body>
</html>