通过response对象可以实现很多功能,下面的代码都是在myeclipse上实现过的,整理下路,以备后用。


response对象应用1

1向客户端发送简单消息

A利用已经声明的对象,调用其getOutputStream()方法,向客户端输出内容

response.getOutputStream().write("输出,以默认编码形式".getBytes());
System.out.println(response.getCharacterEncoding());

2向客户端发送中文消息,并指定编码

//下面语句设置了响应内容类型和编码方式
//response.setContentType("text/html;charset=GBK");
public void test3(HttpServletResponse response) throws IOException{

        OutputStream out = response.getOutputStream();
        out.write(1);//会乱码,服务器发送默认是以ISO编码,浏览器解析默认是gb2312
    }
    //不指定编码,发送数据,中文
    public void test2(HttpServletResponse response) throws IOException{

        OutputStream out = response.getOutputStream();
        out.write("中国".getBytes());//会乱码,iso编码中没有汉字
    }
    //以GBK编码发送数据
    public void test1(HttpServletResponse response) throws IOException{
        response.setContentType("text/html;charset=GBK");//设置响应内容和编码规则
        OutputStream out = response.getOutputStream();
        out.write("中国".getBytes());//可以正常现实出中文
    }

3使用response对象实现用户下载功能

步骤:

1、获取文件的真实路径

2、获取文件的文件名(用于告诉用户)

3、告知客户这是一次下载响应,通过设置response对象的相关内容

4、打开一 个输入流,将文件传进来。(这个流是针对文件的)

5、打开一个输出流,并将之前的文件流传进来,用response对象传出去。


response.setContentType("text/html;charset=UTF-8");
        1、获取文件的真实路径
        String path = getServletContext().getRealPath("/File/长大水塔.jpg");//获取文件的绝对路径
        2、获取文件的文件名(用于告诉用户)
        String filename = path.substring(path.lastIndexOf("\\")+1);//获取文件名字
        System.out.println(filename);
        System.out.println(path);
        3、告知客户这是一次下载响应,通过设置response对象的相关内容
        response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(filename, "UTF-8"));//少了个等于号,attachment附件
        4、打开一个输入流,将文件传进来。(这个流是针对文件的)
        InputStream in = new FileInputStream(path);//这个流是针对文件的输入的
        5、打开一个输出流,并将之前的文件流传进来,用response对象传出去。
        OutputStream out = response.getOutputStream();//这个流是针对response的输出的
        //传递这个流,固定套路
        byte[] buf = new byte[1024];
        int len = -1;
        while((len=in.read(buf)) != -1){
            out.write(buf);
        }
        in.close();

下面是一些关于response对象的细节

04-26 19:01
查看更多