IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> Servlet之response -> 正文阅读

[网络协议]Servlet之response

1.响应消息的格式

?? ???? 响应行:HTTP/1.1 200 OK
?? ??? ??? ?响应码:
?? ??? ??? ??? ??? ??? ?1. 1xx:服务器就收客户端消息,但没有接受完成,等待一段时间后,发送1xx多状态码
?? ??? ??? ??? ??? ??? ?2. 2xx:成功。代表:200
?? ??? ??? ??? ??? ??? ?3. 3xx:重定向。代表:302(重定向),304(访问缓存)
?? ??? ??? ??? ??? ??? ?4. 4xx:客户端错误。
?? ??? ??? ??? ??? ??? ??? ?* 代表:
?? ??? ??? ??? ??? ??? ??? ??? ?* 404(请求路径没有对应的资源)
?? ??? ??? ??? ??? ??? ??? ??? ?* 405:请求方式没有对应的doXxx方法
?? ??? ??? ??? ??? ??? ?5. 5xx:服务器端错误。代表:500(服务器内部出现异常)
?? ??? ?响应头:
?? ??? ??? ??? ?1. 格式:头名称: 值
?? ??? ??? ??? ?2. 常见的响应头:
?? ??? ??? ??? ??? ?1. Content-Type:服务器告诉客户端本次响应体数据格式以及编码格式
?? ??? ??? ??? ??? ?2. Content-disposition:服务器告诉客户端以什么格式打开响应体数据
?? ??? ??? ??? ??? ??? ?* 值:
?? ??? ??? ??? ??? ??? ??? ?* in-line:默认值,在当前页面内打开
?? ??? ?响应空行:
?? ??? ?响应体:

2.response对象

?? ???? 1.设置响应行
?? ??? ??? ?设置状态码:setStatus(int sc)
?? ??? ?2.设置响应头
?? ??? ??? ?setHeader(String name, String value)
?? ??? ?3.设置响应体
?? ??? ??? ?* 使用步骤:
?? ??? ??? ??? ?1. 获取输出流
?? ??? ??? ??? ??? ?* 字符输出流:PrintWriter getWriter()

?? ??? ??? ??? ??? ?* 字节输出流:ServletOutputStream getOutputStream()

?? ??? ??? ??? ?2. 使用输出流,将数据输出到客户端浏览器

??????? 方法的几个应用:

???????

?? ???? 1.重定向
?? ??? ??? ??? ?//简单的重定向方法
?? ??? ???????? response.sendRedirect("/day15/responseDemo2");
?? ??? ??? ??? ?
?? ??? ??? ?* 转发的特点:forward
?? ??? ??? ??? ?1. 转发地址栏路径不变
?? ??? ??? ??? ?2. 转发只能访问当前服务器下的资源
?? ??? ??? ??? ?3. 转发是一次请求,可以使用request对象来共享数据
?? ??? ??? ?* 重定向的特点:redirect
?? ??? ??? ??? ?1. 地址栏发生变化
?? ??? ??? ??? ?2. 重定向可以访问其他站点(服务器)的资源
?? ??? ??? ??? ?3. 重定向是两次请求。不能使用request对象来共享数据
?? ??? ??? ??? ?
?? ??? ??? ?* 路径写法:
?? ??? ??? ??? ?1. 路径分类
?? ??? ??? ??? ??? ?1. 相对路径:通过相对路径不可以确定唯一资源
?? ??? ??? ??? ??? ??? ?* 如:./index.html
?? ??? ??? ??? ??? ??? ?* 不以/开头,以.开头路径

?? ??? ??? ??? ??? ??? ?* 规则:找到当前资源和目标资源之间的相对位置关系
?? ??? ??? ??? ??? ??? ??? ?* ./:当前目录
?? ??? ??? ??? ??? ??? ??? ?* ../:后退一级目录
?? ??? ??? ??? ??? ?2. 绝对路径:通过绝对路径可以确定唯一资源
?? ??? ??? ??? ??? ??? ?* 如:http://localhost/day15/responseDemo2?? ??? ?/day15/responseDemo2
?? ??? ??? ??? ??? ??? ?* 以/开头的路径

?? ??? ??? ??? ??? ??? ?* 规则:判断定义的路径是给谁用的?判断请求将来从哪儿发出
?? ??? ??? ??? ??? ??? ??? ?* 给客户端浏览器使用:需要加虚拟目录(项目的访问路径)
?? ??? ??? ??? ??? ??? ??? ??? ?* 建议虚拟目录动态获取:request.getContextPath()
?? ??? ??? ??? ??? ??? ??? ??? ?* <a> , <form> 重定向...
?? ??? ??? ??? ??? ??? ??? ?* 给服务器使用:不需要加虚拟目录
?? ??? ??? ??? ??? ??? ??? ??? ?* 转发路径
?? ??? ?2. 服务器输出字符数据到浏览器
?? ??? ??? ?* 步骤:
?? ??? ??? ??? ?1. 获取字符输出流
?? ??? ??? ??? ??? ?PrintWriter pw = resp.getWriter();
?? ??? ??? ??? ?2. 输出数据
?? ??? ??? ??? ?
?? ??? ??? ?//简单的形式,设置编码,是在获取流之前设置
?????? ??? ??? ??? ?response.setContentType("text/html;charset=utf-8");
?? ??? ?3. 服务器输出字节数据到浏览器
?? ??? ??? ?* 步骤:
?? ??? ??? ??? ?1. 获取字节输出流
?? ??? ??? ??? ?2. 输出数据
?? ??? ??? ??? ?
?? ??? ?4.验证码
?? ??? ??? ?本质:随机生成的图片
?? ??? ??? ?作用:防止恶意表单注册

package cn.itcast.web.response;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;


@WebServlet("/checkCode")
public class CheckCode extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        int width = 100;
        int height = 50;

        //1.在内存中创建一个对象,在内存中代表图片
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

        //2.美化图片
        //2.1加背景,创建一个画笔,选择颜色粉红色,然后画背景
        Graphics g = image.getGraphics();
        g.setColor(Color.PINK);
        g.fillRect(0,0,width,height);
        //2.2画边框
        g.setColor(Color.blue);
        g.drawRect(0,0,width-1,height-1);
        //2.3在图片上写字符串
        Random random = new Random();
        String str = "ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        for(int i = 1;i < 5;i ++){
            int num = random.nextInt(str.length());
            g.drawString(str.charAt(num)+"",width/5*i,height/2);
        }
        //2.4在图片上添加干扰线
        g.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);
            g.drawLine(x1,y1,x2,y2);
        }


        //3.图片显示在浏览器上
        ServletOutputStream sos = resp.getOutputStream();
        ImageIO.write(image,"jpg",sos);
    }

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



<!DOCTYPE html>
<html lang="ch">
<head>
    <meta charset="UTF-8">
    <title>验证码</title>
    <!--我需要动态的切换验证码,点击图片可以刷新,点击文字也可以刷新-->
    <script>
        //绑定单击事件
        window.onload=function () {
            //给图片绑定单击事件
            var img = document.getElementById("image");
            img.onclick=function () {
                var date = new Date().getTime();
                img.src="/day15/checkCode?"+date;
            }


            var word = document.getElementById("word");
            word.onclick=function () {
                var date = new Date().getTime();
                var img = document.getElementById("image");
                img.src="/day15/checkCode?"+date;
            }
        }
    </script>
</head>
<body>
<img src="/day15/checkCode" id = "image" />
<a href="/day15/CheckCode.html" id="word">看不清?换一张</a>

</body>
</html>

3.servletContext对象

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

?? ??? ???? 2. 获取:
?? ??? ??? ??? ?1. 通过request对象获取
?? ??? ??? ??? ??? ?request.getServletContext();
?? ??? ??? ??? ?2. 通过HttpServlet获取
?? ??? ??? ??? ??? ?this.getServletContext();
?? ??? ??? ??? ?3.功能:
?? ??? ??? ??? ??? ?1.获取MIME文件:String getMimeType(String file) ?
?? ??? ??? ??? ??? ?2.共享数据
?? ??? ??? ??? ??? ?3.获取web文件的真实路径
?? ??? ??? ??? ??? ??? ?1. 方法:String getRealPath(String path) ?
?? ??? ??? ??? ??? ??? ? String b = context.getRealPath("/b.txt");//web目录下资源访问
?? ??? ??? ??? ??? ??? ? System.out.println(b);
?? ??? ??? ??? ?
?? ??? ??? ??? ??? ??? ?String c = context.getRealPath("/WEB-INF/c.txt");//WEB-INF目录下的资源访问
?? ??? ??? ??? ??? ??? ?System.out.println(c);
?? ??? ??? ??? ?
?? ??? ??? ??? ??? ??? ?String a = context.getRealPath("/WEB-INF/classes/a.txt");//src目录下的资源访问
?? ??? ??? ??? ??? ??? ?System.out.println(a);

?? ??? ???? 案例
?? ??? ??? ??? ?文件下载需求:
?? ??? ??? ??? ?1. 页面显示超链接
?? ??? ??? ??? ?2. 点击超链接后弹出下载提示框
?? ??? ??? ??? ?3. 完成图片文件下载
?? ??? ??? ??? ?
?? ??? ??? ??? ?分析:
?? ??? ??? ??? ??? ?1.图片的话,如果是超链接直接指过去就是直接解析,我们要的是下载
?? ??? ??? ??? ??? ?2.如果是超链接指向一个servlet的话,然后servlet里面改变响应头,应该可以出现下载按钮
?? ??? ??? ??? ??? ?3.* content-disposition:attachment;filename=xxx
?? ??? ??? ??? ??? ?
?? ??? ??? ??? ?步骤:
?? ??? ??? ??? ??? ?1.创建一个html,里面的超链接指向servlet
?? ??? ??? ??? ??? ?2.获取文件名称
?? ??? ??? ??? ??? ?2.将图片资源复制过去,然后就是获取一个输入流,把文件读到内存中
?? ??? ??? ??? ??? ?3.根据响应的输出流,把文件输出到浏览器上
?? ??? ??? ??? ??? ?4.不要忘记设置响应头
?? ??? ??? ??? ??? ?
?? ??? ??? ??? ?中文乱码问题存在:
?? ??? ??? ??? ??? ?根据不同的浏览器,设置不同的解析方式
?? ??? ??? ??? ??? ?
?? ??? ??? ??? ??? ?1.获取浏览器的版本信息
?? ??? ??? ??? ??? ?2.根据不同的版本信息,设置filename的编码方式不同

package cn.itcast.web.response;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/downloadImg")
public class download extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       //2.获取文件名称
        String filename = request.getParameter("filename");

        //3.将图片资源复制过去,然后就是获取一个输入流,把文件读到内存中
        //3.1找到文件的真实路径
        ServletContext servletContext = this.getServletContext();
        String realPath = servletContext.getRealPath("/img/"+filename);
        //3.2加载进内存
        FileInputStream fis = new FileInputStream(realPath);



        //解决中文乱码问题
        String agent = request.getHeader("user-agent");
        filename = DownLoadUtils.getFileName(agent,filename);
        //4.不要忘记设置响应头
        //4.1设置响应头类型
        String mimeType = servletContext.getMimeType(filename);
        response.setHeader("content-type",mimeType);
        //4.2设置成附件方式:content-disposition:attachment;filename=xxx
        response.setHeader("content-disposition","attachment;filename="+filename);


        //5.将字符输入流输出
        ServletOutputStream sos = response.getOutputStream();
        int len = 0;
        byte[] b = new byte[1024 * 8];
        while((len = fis.read(b)) != -1){
            sos.write(b,0,len);
        }


        fis.close();

    }

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


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>download</title>
</head>
<body>

<a href="/day15/downloadImg?filename=1.jpg">九尾</a>
<a href="/day15/downloadImg?filename=2.jpg">鼬</a>
</body>
</html>

  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2021-09-12 13:30:30  更:2021-09-12 13:30:36 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年6日历 -2024/6/27 1:42:37-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码