Sunday, January 3, 2016


  • getWriter() //characters only
  • getOutputStream() //bytes and characters.getByte()

We cannot use both method for one response, because an output will be auto closed, so the other output will not go through.
  • sendRedirect()
    response.sendRedirect("/webapp/anotherPage")// use at least "webapp" go back to client, client browser then send request to the new url
    //request.getContextPath() will return "/webapp"
    //the url can be anywhere in the world
    //the url from browser will change to the new url
    //after the sendRedirect, all code continues to run, so make sure to return and finish the service
    //To prevent user refreshing page, normally we use sendRedirect to direct to another url, so when user refresh, it keeps in the new url
  • flush()
    when response.flush() called, print writer committed all buffer to client, it can still push more content to client, but no forward contents will be affected.
    So if we call flush() first, request.getRequestDispatcher(url).forward(req,res) will not affect anything on the client side
    And before flush(), if we call request.getRequestDispatcher(url).forward(req,res) the printed buffer will not be affect, client will only see the forwarded contents.
  • Refresh: 1;url=     //redirect to url after 1 second
    //response.setHeader("Refresh", "5;url=");
  • cache: set http header, disable/enable cache
    response.setDateHeader("Expires",-1); //or value to System.currentTimeMillis()+1*1000;
  • download file
    response.setHeader("Content-Disposition", "attachment; filename=winter.jpg");
    String path = getServletContext().getRealPath("/images/Winter.jpg");
    FileInputStream fis = new FileInputStream(path);
    byte buff[] = new byte[1024];
    int length=0;
    response.getOutputStream().write(buff, 0, length);
                    • Image type
                      response.setHeader("Content-Type", "image/jped");
                    • Encode URL, with SESSIONID in url
                      url = response.encodeURL("/webapp/servlet1");
                      // return /webapp/servlet1?SESSIONID=ABCDEFGHIJKLMN
                    • Captcha

                    1. Control response header, so you can manage the actions from browser
                    2. Use HttpServletResponse provided functions
                    3. Output stream will be auto closed when service is finished

                    No comments:

                    Post a Comment