HttpServletResponse

HttpServletResponse

web服务器接收到客户端的http请求,针对这个请求,分别创建一个代表请求的HttpServletRequest对象,代表响应的一个HttpServletResponse;

如果要获取客户端请求过来的参数:找HttpServletRequest
如果要给客户端响应一些信息:找HttpServletResponse

1.下载文件
向浏览器输出消息
2.下载文件
要获取下载文件的路径

String rp="F:\\lianxi\\maven\\response\\target\\classes\\IMG_3735.PNG";

​ 下载的文件名是啥?

 String fileName = rp.substring(rp.lastIndexOf("\\") + 1);

​ 设置想办法让浏览器能够支持下载我们需要的东西

  resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));

​ 获取下载文件的输入流

 FileInputStream input = new FileInputStream(rp);

​ 创建缓冲区

int length=0;
        byte[] buff = new byte[1024];

​ 获取OutputStream对象

 ServletOutputStream out = resp.getOutputStream();

​ 将FileOutputStream流写入到buffer缓冲区使用OutputStream将缓冲区中的数据输出到客户端!

      while ((length=input.read(buff))>0){
            out.write(buff,0,len);
        }
        input.close();
        out.close();

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <servlet>
        <servlet-name>down</servlet-name>
        <servlet-class>com.fan1.servlet.response</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>down</servlet-name>
        <url-pattern>/down</url-pattern>
    </servlet-mapping>

</web-app>




最终实现
![在这里插入图片描述]( https://img-blog.csdnimg.cn/20210411141945182.png?x-oss-process=image/watermark ,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NjU4MDYxNA==,size_16,color_FFFFFF,t_70#pic_center)

posted @ 2021-07-16 23:23  FanWd-sec  阅读(51)  评论(0)    收藏  举报