Response&&ServletContext

版权声明:本文为博主原创文章,遵循 CC 4.0 BY 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_37482956/article/details/101453897

reaponse (响应)

功能:设置响应消息

  • 设置响应行
    格式:HTTP/1.1 200 ok
    设置状态码:setStatus(int sc)

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

  • 设置响应体:

    • 使用步骤:
      1. 获取输出流

        • 字符输出流:PrintWriter getWriter()

        • 字节输出流:ServletOutputStream getOutputStream()

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

案例:

重定向
  • 重定向:资源跳转的方式
    在这里插入图片描述

  • 代码实现:

    //1.设置响应状态码 302
    response.setStatus(302);
    //2.设置响应头
    response.setHeader("location","/day04/respdemo2");
    
    
    // 简单写法
    response.sendRedirect("/day04/respdemo2");
    
  • 重定向的特点:redirect

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

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

  • 路径写法:

  1. 相对路径:通过相对路径不可以确定唯一资源
    • 如:./index.html

    • 不以/开头,以.开头路径

    • 规则:找到当前资源和目标资源之间的相对位置关系

      • ./:当前目录
      • …/:后退一级目录
  2. 绝对路径:通过绝对路径可以确定唯一资源
    • 如:http://localhost/day15/responseDemo2 /day15/responseDemo2

    • 以/开头的路径

    • 规则:判断定义的路径是给谁用的?判断请求将来从哪儿发出

      • 给客户端浏览器使用:需要加虚拟目录(项目的访问路径)
        • 建议虚拟目录动态获取:request.getContextPath()
        • <a> ,<form> ,重定向…
      • 给服务器使用:不需要加虚拟目录
        • 转发路径
服务器输出字符数据到浏览器
  • 步骤:
    1. 获取字符输出流
    2. 输出数据

在这里插入图片描述

  • 注意:
    • 乱码问题:

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

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

  • 代码
/*      //获取流之前,设置流的默认编码(tomcat 的编码)
        response.setCharacterEncoding("utf-8");
        // 告诉浏览器,服务器发送消息体数据的编码
        response.setHeader("content-type","text/html;Charset=utf-8");*/

        // 简写格式:
        response.setContentType("text/html;Charset=utf-8");

        //1.获取字符输出流
        PrintWriter pw = response.getWriter();
        //2.输出数据
        pw.write("<h1>hahaha!</h1>");
        pw.write("<h5>你好啊,hahaha</h5>");
服务器输出字节数据到浏览器
  • 步骤:
    1. 获取字节输出流 ServletOutputStream getOutputStream()
    2. 输出数据
  • 代码
     // 告诉浏览器要使用的编码格式
     response.setContentType("text/html;charset=utf-8");
     //1。获取字符输出流
     ServletOutputStream sos = response.getOutputStream();

     //2. 输出数据到浏览器
     sos.write("hello".getBytes());
     sos.write("你好".getBytes("utf-8"));
验证码
  1. 本质:图片
  2. 目的:防止恶意表单注册
  • 代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>

        /*
        * 点击图片换一张
        * */

        window.onload = function () {
            //1.获取图片对象
            var img = document.getElementById("checkCode");
            //2. 绑定点击事件
            img.onclick = function () {
                var date = new Date().getTime();
                img.src="/day04/respdemo5?"+date
            }
        }
    </script>
</head>
<body>
    <img id="checkCode" src="/day04/respdemo5">
</body>
</html>

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("/respdemo5")
public class RespsonseDemo5 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        int width = 100;
        int height = 40;
        // 1. 创建一图片对象,
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);

        // 2. 美化图片
        // 2.1 填充背景色
        Graphics g = image.getGraphics();// 画笔对象
        g.setColor(Color.CYAN); // 设置画笔颜色
        g.fillRect(0,0,width,height);

        // 2.2 画边框
        g.setColor(Color.lightGray);
        g.drawRect(0,0,width-1,height-1);

        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789";
        // 生成随机角标
        Random random = new Random();

        g.setColor(Color.red);
        for (int i = 0; i < 4 ; i++) {
            int index = random.nextInt(str.length());
            // 获取字符
            char ch = str.charAt(index);
            // 2.3 写验证码
            g.drawString(ch+"",width/5*(i+1),height/2);
        }

        g.setColor(Color.pink);
        // 2.4 画干扰线
        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. 将图片输出到页面展示
        ImageIO.write(image,"png",response.getOutputStream());
    }

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

ServletContext对象:

  1. 概念:
  • 代表整个web应用,可以和程序的容器(服务器)来通信
  1. 获取:
  • 通过request对象获取
    request.getServletContext();
  • 通过HttpServlet获取
    this.getServletContext();
  1. 功能:
  • 获取MIME类型:
    • MIME类型:在互联网通信过程中定义的一种文件数据类型

      • 格式: 大类型/小类型 text/html image/jpeg
    • 获取:String getMimeType(String file)

    • 代码:

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取ServletContext对象
        ServletContext context = this.getServletContext();
        // 通过文件名获取 MIME 类型
        String mimeType = context.getMimeType("a.jpg");
        System.out.println(mimeType);  //image/jpeg
    }
  • 域对象:共享数据

    1. setAttribute(String name,Object value)
    2. getAttribute(String name)
    3. removeAttribute(String name)
    • ServletContext对象范围:所有用户所有请求的数据
  • 获取文件的真实(服务器)路径

    • 方法:String getRealPath(String path)
    • 代码:
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取ServletContext对象
        ServletContext context = this.getServletContext();

        // 获取web 目录下的资源真实路径
        String a_path = context.getRealPath("/a.txt");
        System.out.println(a_path);  // E:\javaweb\day03_login\out\artifacts\day04_response_war_exploded\a.txt

        // 获取 WEB-INF 目录下资源的真实路径
        String b_path = context.getRealPath("/WEB-INF/b.txt");
        System.out.println(b_path);  // E:\javaweb\day03_login\out\artifacts\day04_response_war_exploded\WEB-INF\b.txt

        // 获取src 目录下资源的真实路径
        String c_path = context.getRealPath("/WEB-INF/classes/c.txt");
        System.out.println(c_path);  // E:\javaweb\day03_login\out\artifacts\day04_response_war_exploded\WEB-INF\classes\c.txt

    }

案例:

  • 文件下载需求:
    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输出流
    • 问题:

      • 中文文件问题
        • 解决思路:
          1. 获取客户端使用的浏览器版本信息
          2. 根据不同的版本信息,设置filename的编码方式不同
    • 代码:

	<!DOCTYPE html>
	<html lang="en">
	<head>
	    <meta charset="UTF-8">
	    <title>download</title>
	</head>
	<body>
	    <a href="/day04/downloadServlet?filename=图片.png">图片 </a>
	    <a href="/day04/downloadServlet?filename=1.avi">视频 </a>
	</body>
	</html>
	package com.long123.servlet.download;
	
	import com.long123.utils.DownLoadUtils;
	
	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("/downloadServlet")
	public class DownloadServlet extends HttpServlet {
	    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
	        // 1. 获取文件名参数
	        String filename = request.getParameter("filename");
	        // 2. 使用字节输入流加载文件进内存
	        // 2.1 找到文件服务器路径
	        ServletContext servletContext = this.getServletContext();
	        String realPath = servletContext.getRealPath("/img/" + filename);
	        // 2.2 用字节流关联
	        FileInputStream fis = new FileInputStream(realPath);
	
	        // 3. 设置response 的响应头
	        // 3.1 设置 响应头类型 content-type
	        String mimeType = servletContext.getMimeType(filename);// 获取文件的mime类型
	        response.setHeader("content-type",mimeType);
	
	        // 解决中文名文件问题
	        //1.获取user-agent请求头
	        String agent = request.getHeader("user-agent");
	        //2.使用工具类方法编码文件
	        filename = DownLoadUtils.getFileName(agent, filename);
	
	        // 3.2 设置响应的打开方式
	        response.setHeader("content-disposition","attachment;filename="+filename);
	
	        // 4.将输入流数据写入到输出流数据中
	        ServletOutputStream sos = response.getOutputStream();
	        byte[] buff = new byte[1024 * 10];
	        int len = 0;
	
	        while ((len = fis.read(buff))!=-1){
	            sos.write(buff,0,len);
	        }
	
	        fis.close();
	    }
	
	    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	        this.doPost(request,response);
	    }
	}

DownLoadUtils

	package com.long123.utils;
	
	import sun.misc.BASE64Encoder;
	import java.io.UnsupportedEncodingException;
	import java.net.URLEncoder;
	
	
	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")) {
	            // 火狐浏览器
	            BASE64Encoder base64Encoder = new BASE64Encoder();
	            filename = "=?utf-8?B?" + base64Encoder.encode(filename.getBytes("utf-8")) + "?=";
	        } else {
	            // 其它浏览器
	            filename = URLEncoder.encode(filename, "utf-8");
	        }
	        return filename;
	    }
	}

猜你喜欢

转载自blog.csdn.net/qq_37482956/article/details/101453897