JavaWeb基础—HttpServletResponse

HttpServletResponse对象代表服务器的响应。

这个对象中封装了向客户端发送数据、发送响应头,发送响应状态码的方法。

 几个方法:

  向客户端发送数据:

    getOutputStream()

    getWriter()

  

  两个流(getWriter()与getOutputStream())不能同时使用。
      字符流      字节流

  一个原则:在使用getWrite()之前,先调用setContentType("text/html;charset=utf-8")

  发送状态码

    setStatus()  发送成功状态等,也可以302

    当然,接口里定义了相关的相应的常量,无需直接写数字

常见的应用:

  1.生成图片验证码:

    主要用到的是封装好的生成类:VerifyCode 以及 BufferedImage (详细代码另一篇博客附上)

public class VerifyCodeServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /**
         * 生成图片
         * 保存图片上验证码文本到session域中
         * 将图片响应给客户端
         */
        VerifyCode vc = new VerifyCode();
        BufferedImage image = vc.getImage();
        request.getSession().setAttribute("vcode", vc.getText());
        VerifyCode.output(image, response.getOutputStream());
        
    }

}

   2.设置相应头控制浏览器的行为:

      例如:

          response.setHeader("Cache-Control", "no-cache");//禁止缓存
       response.setHeader("refresh", "5");//设置refresh响应头控制浏览器每隔5秒钟刷新一次

         完成重定向,必须要带Location响应头!快捷重定向:sendRedirect(Location)
        完成定时刷新,使用Refresh(有点类似于过会儿再重定向),注意格式5;URL
        禁用浏览器缓存:(从index.jsp借着看)
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">

/**
    *  是每个请求进来的话就发送给每个请求的客户端
    **/
    response.geWriter().print(msg);

   与write()方法的区别:

  • response.getWriter()返回的是PrintWriter,这是一个打印输出流。
  • response.getWriter().print(),不仅可以打印输出文本格式的(包括html标签),还可以将一个对象以默认的编码方式转换为二进制字节输出
  • response.getWriter().writer(),只能打印输出文本格式的(包括html标签),不可以打印对象。

  可参见:http://blog.csdn.net/sjl6666666666/article/details/53239820

   【更新】:实现文件下载:

     String path = this.getServletContext().getRealPath("/Download/定南中学.jpg");//获取文件的相对路径  
        String filename = path.substring(path.lastIndexOf("\")+1);//获取文件名称,在转化为子串  
        //response.setHeader告诉浏览器以什么方式打开  
        //假如文件名称是中文则要使用 URLEncoder.encode()编码  
        //否则直接使用response.setHeader("content-disposition", "attachment;filename=" + filename);即可  
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8")); 

    使用 输入流下载:

     InputStream in = null ;  
        OutputStream out = null ;  
        try  
        {  
           in = new FileInputStream(path); //获取文件的流  
           int len = 0;  
           byte buf[] = new byte[1024];//缓存作用  
           out = response.getOutputStream();//输出流  
           while( (len = in.read(buf)) > 0 ) //切忌这后面不能加 分号 ”;“  
           {  
               out.write(buf, 0, len);//向客户端输出,实际是把数据存放在response中,然后web服务器再去response中读取  
           }  

    excel下载实例:

     response.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("utf-8"),"iso8859-1"));
        response.setContentType("application/ynd.ms-excel;charset=UTF-8");
        OutputStream out=response.getOutputStream();
        wb.write(out);
        out.flush();
        out.close();

     下载实例:(基于jxls1.0)

    @RequestMapping("/export")  
    public String testExport(HttpServletResponse response) throws Exception{
      
        String tplPath = "F:/tamp.xlsx";  
        String destPath = "F:/export.xlsx";  
        List<receiver> reclist = reSe.findall();
        
        Map<String, List<receiver>> beanParams = new HashMap<String, List<receiver>>();  
        beanParams.put("reclist", reclist);  
        XLSTransformer former = new XLSTransformer();  
        former.transformXLS(tplPath, beanParams, destPath);  
        
            InputStream in = null ;  
            OutputStream out = null ;  
        
           in = new FileInputStream(destPath); //获取文件的流  
           int len = 0;  
           byte buf[] = new byte[1024];//缓存作用 
           response.setContentType("application/vnd..ms-excel");
           response.setHeader("content-Disposition","attachment;filename="+URLEncoder.encode("export.xlsx","utf-8"));
           out = response.getOutputStream();//输出流  
           while( (len = in.read(buf)) > 0 ) //切忌这后面不能加 分号 ”;“  
           {  
               out.write(buf, 0, len);//向客户端输出,实际是把数据存放在response中,然后web服务器再去response中读取  
           }  
        return null;
    } 
 

      

  

原文地址:https://www.cnblogs.com/jiangbei/p/6682266.html