Response & ServletContext对象

1. 功能:设置响应消息

  • 设置响应行
    1. 格式:HTTP/1.1 200 ok
    2. 设置状态码:setStatus(int sc)
  • 设置响应头:setHeader(String name, String value)
  • 设置响应体:
    使用步骤:
     1) 获取输出流
       * 字符输出流:PrintWriter getWriter()
       * 字节输出流:ServletOutputStream getOutputStream()
     2)使用输出流,将数据输出到客户端浏览器

2案例

2.1 完成重定向

  • 重定向:资源跳转的方式
  • 代码实现:
//1. 设置状态码为302
response.setStatus(302);
//2.设置响应头location
 response.setHeader("location","/day15/responseDemo2");

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

2.2路径写法

  • 路径分类
1. 相对路径:通过相对路径不可以确定唯一资源
	* 如:./index.html
	* 不以/开头,以.开头路径

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

	* 规则:判断定义的路径是给谁用的?判断请求将来从哪儿发出
		* 给客户端浏览器使用:需要加虚拟目录(项目的访问路径)
			* 建议虚拟目录动态获取:request.getContextPath()
			* <a> , <form> ,重定向...
	    * 给服务器使用:不需要加虚拟目录
			* 转发路径
相对路径的示例:
//当前路径
http://localhost/day15/location.html
//目标资源
http://localhost/day15/responseDemo2

可以看到:location.html和responseDemo2在同一级目录

当想通过location.html中的<a>标签访问responseDemo2时可以通过相对路径来写:
<a href='./responseDemo2'>responseDemo2</a>


绝对路径的示例:
当部署项目时把虚拟目录的值改变值,也不需要改变代码
本来是:http://localhost/day15/responseDemo2   response.sendRedirect("/day15/responseDemo2");
虚拟目录改变为:/day155        http://localhost/day155/responseDemo2

//动态获取虚拟目录
String contextPath = request.getContextPath();
//设置重定向
response.sendRedirect(contextPath+"responseDemo2");

2.3 服务器输出字符数据到浏览器

  • 步骤:(字符输出流)
	1)获取字符输出流
	PrintWriter pw = response.getWriter();
	2)输出数据
	pw.write("<h1> 你好 response<h1/>");//会产生中文乱码问题
  • 注意:乱码问题
    1)PrintWriter pw = response.getWriter();获取的流的默认编码是ISO-8859-1(服务器端)
    2)浏览器默认的编码是GBK,所以浏览器会使用GBK进行解码,与服务器用于编码的码不一样而导致中文乱码;
    3)解决方法
       a)设置该流的默认编码
        response.setCharacterEncoding("utf-8");
      b) 告诉浏览器,服务器所使用的编码
        response.setHeader("content-type","text/html;charset=utf-8");
    //简单的形式,设置编码,是在获取流之前设置
    response.setContentType("text/html;charset=utf-8");//既设置了编码,又通知了浏览器服务器所使用的编码

2.4 服务器输出字节数据到浏览器

  • 步骤**(字节输出流)**
1)获取字符输出流
	ServletOutputStream sos = response.getOutputStream();
2)输出数据
	sos.write("<h1> 你好 response<h1/>".getBytes("utf-8"));//会产生中文乱码问题

2.5验证码

  • 生成验证码
@WebServlet("/checkCodeServlet")
public class Varification extends HttpServlet {
    @Override
    protected void doGet(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);

        //3.生成随机数字
        String str = "abcdefghijklmnopqrstuvwxyz1234567890";

        Random ran = new Random();
        int index = 0;
        for(int i = 1;i<= 4;i++){
            index = ran.nextInt(str.length());
            char c = str.charAt(index);
            g.drawString(c+"",width/5*i,25);//写验证码
        }
        //4. 生成干扰线
        g.setColor(Color.green);
        for(int i = 0;i<10;i++){
            int x1 = ran.nextInt(100);
            int x2 = ran.nextInt(100);
            int y1 = ran.nextInt(100);
            int y2 = ran.nextInt(100);
            g.drawLine(x1,y1,x2,y2);
        }
        //将图片输出到页面显示
        ImageIO.write(image,"jpg",resp.getOutputStream());
    }

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

3 ServletContext对象

  • 概念:代表整个web应用,可以和程序的容器(服务器)来通信
  • 获取:
    1)通过request对象获取
    request.getServletContext();
    2)通过HttpServlet获取
    this.getServletContext();
    上述两种方式获取的对象的是相同的,即相同的对象地址值。因为每个项目代表唯一的一个web应用

3.1 功能

3.1.1 获取MIME类型

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

3.1.2 域对象:共享数据

  1. setAttribute(String name,Object value)
  2. getAttribute(String name)
  3. removeAttribute(String name)
  • ServletContext对象范围:所有用户所有请求的数据
  • 服务器关闭该域对象才会被清除,它保留的数据也被清除;

3.1.3 获取文件的真实(服务器)路径

  • 方法:String getRealPath(String path)
String b = context.getRealPath("/b.txt");//web目录下资源访问("/"代表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目录下的资源访问(src资源最终会被放到WEB-INF/classes目录下)
System.out.println(a);

4 综合案例

  • 文件下载需求:
    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>文件下载</title>
</head>
<body>
    <a href="/Test/filedownload?filename=九尾狐.jpg">图片1</a>
    <a href="/Test/filedownload?filename=1.avi">视频1</a>
</body>
</html>
@WebServlet("/filedownload")
public class FileDownload extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取文件名称
        req.setCharacterEncoding("utf-8");//对获取的客户端请求重新编码
        String filename = req.getParameter("filename");
        //2.使用字节输入流加载文件进内存
        //2.1获取文件绝对路径
        ServletContext sc = this.getServletContext();
        String filePath = sc.getRealPath("/img/"+filename);//第一个/表示web目录
        System.out.println(filePath);
        //2.2用字节流关联
        FileInputStream fis = new FileInputStream(filePath);

        //3设置response响应头
        //3.1 获取文件类型
        String fileType = sc.getMimeType(filename);
        //3.2 设置响应头文件类型
        resp.setHeader("content-type",fileType+";charset=utf-8");
        //解决中文文件名问题
        //1.获取user-agent请求头、
        String agent = req.getHeader("user-agent");
        //2.使用工具类方法编码文件名即可
        filename = DownLoadUtils.getFileName(agent, filename);
        //设置响应头打开方式
        resp.setHeader("content-disposition","attachment;filename="+filename);
        //4.将输入流的数据写出到输出流中
        byte[] buf=new byte[1024];
        ServletOutputStream sos = resp.getOutputStream();
        int len=0;
        while ((len = fis.read(buf))!=-1){
            sos.write(buf,0,len);
        }
        fis.close();
    }
}

解决中文文件名乱码工具包
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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值