当前位置: 移动技术网 > IT编程>开发语言>Java > Servlet之Response对象

Servlet之Response对象

2020年05月01日  | 移动技术网IT编程  | 我要评论

周海媚拒绝求婚,qq水浒张清,神精榜天上人间

response对象

  • 功能:设置响应消息

    1. 设置响应行
      1. 格式:http/1.1 200 ok
      2. 设置状态码:setstatus(int sc)
    2. 设置响应头:setheader(string name,string value)
    3. 设置响应体
      • 使用步骤
        1. 获取输出流
          • 字符输出:printwrite getwriter()
          • 字节输出流:servletoutputstream getoutstream()
        2. 使用输出流,将数据输出到客户端浏览器
  • 案例

    1. 完成重定向

      1. 重定向:资源跳转的方式

      2. 代码实现

          //方式一
                //设置状态码
                resp.setstatus(302);
                //设置响应头location
                resp.setheader("location","/demo2");
                
                //方式二
                resp.sendredirect("/demo2");
        
      3. 重定向(redirect)的特点

        1. 地址栏发生变化
      4. 重定向可以访问其他站点(服务器)的资源

      5. 重定向是两次请求,不可以使用request对象来共享数据

      6. 转发(forward)的特点

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

        1. 路径分类
          1. 相对路径:通过相对路径不可以确定唯一资源
            • 如:./
            • 不以/开头,以.开头路径
            • 规则:找到当前资源和目标资源之间的相对位置关系
              • ./:当前目录
              • ../:后退一级目录
          2. 绝对路径:通过绝对路径可以确定唯一资源
            • 如:http://localhost/webservlet 可以省略为/webservlet
            • 以/开头
            • 规则:判断定义的路径是给谁用的?
              • 给客户端浏览器使用:需要加虚拟目录(项目的访问路径)

                • 建议虚拟目录动态获取:request.getcontextpath()

                • a标签和form标签 重定向。。。

              • 给服务器使用:不需要加虚拟目录

                • 转发
    2. 服务器输出字符数据到浏览器

      • 步骤

        1. 获取字符输出流

          printwriter pw = respond.getwriter();

        2. 输出数据

          pw.writer(string s);

      • 乱码问题

        1. printwriter pw = respond.getwriter();获取的流默认编码是iso-8895-1
        2. 设置流的默认编码
          • response.setcharacterenconding("utf-8");
        3. 告诉浏览器响应体使用的编码
          • response.setheader("content-type","text/html;charset=utf-8");
        • 简单形式设置编码:response.setcontenttype("text/html;charset=utf-8");
    3. 服务器输出字节数据到浏览器

      步骤

      1. 获取字节输出流

        servletoutputstream sos = response.getoutputstream();

      2. 输出数据

        sos.writer("你好".getbytes("utf-8"));

      • 乱码问题
      1. 设置流的默认编码
        • response.setcharacterenconding("utf-8");
      2. 告诉浏览器响应体使用的编码
        • response.setheader("content-type","text/html;charset=utf-8");
      • 简单形式设置编码:response.setcontenttype("text/html;charset=utf-8");
    4. 验证码

      1. 本质:图片
    5. 目的:防止恶意表单注册

      1. 代码

        @webservlet("/demo3")
        public class checkcodeservlet  extends httpservlet {
            @override
            protected void doget(httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception {
                this.dopost(req,resp);
            }
        
            @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_3byte_bgr);
        //        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);
        
                string str = "abcdefghijklnmopqrstuvwxyzabcdefghijklnmopqrst1234567890";
        //        生成随机角标
                random ran = new random();
                for (int i = 1; i <= 4; i++) {
                    int index = ran.nextint(str.length());
        //        获取字符
                    char ch = str.charat(index);
        //        2.3写验证码
                    g.drawstring(ch+"",width/5*i,height/2);
                }
        //        2.4画干扰线
                g.setcolor(color.green);
        //        随机生成干扰线
                for (int i = 1; i <= 10; i++) {
                    int x1 = ran.nextint(width);
                    int x2 = ran.nextint(width);
        
                    int y3 = ran.nextint(height);
                    int y4 = ran.nextint(height);
                    g.drawline(x1,y3,x2,y4);
                }
        
        
        //        将图片输出到页面展示
                imageio.write(image,"jpg",resp.getoutputstream());
            }
        }
        
        
  • servletcontext对象

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

    2. 获取

      1. 通过request对象获取

        request.getservletcontext();

      2. 通过httpservlet获取

        this.getservletcontext();

    3. 功能

      1. 获取mime类型

        • mime类型:在互联网通信过程中定义的一种文件数据类型
          • 格式:大类型/小类型 text/html image/jpeg
          • 获取:string getmimetype(string file)
      2. 域对象:共享数据

        1. void setattribute(string name,object obj);存储数据
        2. getattribute(string name):通过键获取值
        3. void renoveattribute(string name):通过键移除键值对
        • servletcontext对象范围:所有用户的所有请求数据
      3. 获取文件的真实(服务器)路径

        • string getrealpath("/b.txt")
    4. 代码

      public class servletcontextdemo1 extends httpservlet {
          @override
          protected void dopost(httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception {
      //        1.通过request对象获取
              servletcontext context1 = req.getservletcontext();
      //        2.通过httpservlet对象获取
              servletcontext context2 = this.getservletcontext();
      
              system.out.println(context1);
              system.out.println(context2);
              system.out.println(context1==context2);
              
              //获取mime类型
               string filename = "haha.jpg";
             string mine  =  context1.getmimetype(filename);
              system.out.println(mine);
              //获取文件真实路径
              string realpath1 = context1.getrealpath("/a.txt");//web目录下的
              system.out.println(realpath1);
              string realpath2 = context1.getrealpath("/web-inf/b.txt");//web-inf目录下的
              system.out.println(realpath2);
              string realpath3 = context1.getrealpath("/web-inf/classes/c.txt");//src目录下的
              system.out.println(realpath3);
          }
      
          @override
          protected void doget(httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception {
              this.dopost(req,resp);
          }
      }
      
      
    • 案例:文件下载

      • 文件下载需求

        1. 页面显示超链接
        2. 点击超链接后弹出下载提示框
        3. 完成图片文件下载
      • 分析

        1. 超链接指向的资源如果能被浏览器解析,则在浏览器中显示,如果不能解析,则弹出下载提示框。不满足需求
        2. 任何资源都必须弹出下载提示框
        3. 使用响应头设置资源的打开方式
      • 步骤

        1. 定义页面,编辑超链接href属性,指向servlet,传递资源名称filename
        2. 定义servlet
          1. 获取文件名称
          2. 使用字节输入流加载文件进内存
          3. 指定response的响应头:content-disposition:attachment;filename=xxx
          4. 将数据写出到response输出流
      • 问题

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

        package com.creat.test;
        
        import com.creat.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;
        import java.io.inputstream;
        import java.net.urldecoder;
        
        @webservlet("/downloadservlet")
        public class downloadservlet extends httpservlet {
            protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
                string filename = request.getparameter("filename");//获取请求下载的文件名
                string decodefilename = urldecoder.decode(filename, "utf-8");
                //java中相同编解码规则对应的类为urlencode和urldecode
                //这里使用urldecoder类静态方法decode对文件名解码(请求路径中中文已被编码)
        
                servletcontext servletcontext = getservletcontext();//获取服务器域对象
        
                string mimetype = servletcontext.getmimetype(decodefilename);//获取传输文件类型(一般文件在传输时有对应的类型,web.xml配置文件中列举了所有对应关系)
                response.setheader("content-type",mimetype);//设置传输文件类型
        
                string agent = request.getheader("user-agent");//获取请求的浏览器类型
                string encodefilename = downloadutils.getfilename(agent, decodefilename);//下载弹窗中文文件名会乱码,这里使用特殊方式编码
        
                response.setheader("content-disposition","attachment;filename="+encodefilename);//设置客户端浏览器对文件以附件处理
        
                string realpath = servletcontext.getrealpath("/"+decodefilename);//域对象获取文件真实路径
        
                fileinputstream inputstream=new fileinputstream(realpath);//创建输入流,加载要下载的文件进内存
                servletoutputstream outputstream = response.getoutputstream();//创建输出流,写文件给客户端浏览器
                byte[]bys=new byte[1024*4];
                int len;
                while ((len=inputstream.read(bys))!=-1){
                    outputstream.write(bys,0,len);
                }
                inputstream.close();
            }
        
            protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
                this.dopost(request,response);
            }
        }
        

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网