欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

Servlet之Response对象,

来源: javaer 分享于  点击 28804 次 点评:186

Servlet之Response对象,


Response对象

  • 功能:设置响应消息

  • 设置响应头:setHeader(String name,String value)
  • 设置响应体
    • 使用步骤
  • 案例

  • 重定向可以访问其他站点(服务器)的资源

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

  • 转发(forward)的特点

  • 路径写法

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

    • 步骤

    • 乱码问题

      • 简单形式设置编码:response.setContentType("text/html;charset=utf-8");
  • 服务器输出字节数据到浏览器

    步骤

    • 乱码问题
    • 简单形式设置编码:response.setContentType("text/html;charset=utf-8");
  • 验证码

  • 目的:防止恶意表单注册

    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对象

  • 功能

    • ServletContext对象范围:所有用户的所有请求数据
  • 获取文件的真实(服务器)路径

    • String getRealPath("/b.txt")
  • 代码

    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);
        }
    }
    
    
    • 案例:文件下载

      • 文件下载需求

      • 分析

      • 步骤

      • 问题

        • 中文文件问题
          • 解决思路
      • 代码

        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);
            }
        }
        

相关文章

    暂无相关文章
相关栏目:

用户点评