SlideShare uma empresa Scribd logo
1 de 15
Baixar para ler offline
Core Servlets and JavaServer Pages / 2e
        Volume 1: Core Technologies
          Marty Hall Larry Brown

     Generating the Server
       Response: HTTP
      Response Headers
1
Agenda
    • Format of the HTTP response
    • Setting response headers
    • Understanding what response
      headers are good for
    • Building Excel spread sheets
    • Generating JPEG images dynamically
    • Sending incremental updates
      to the browser



2
HTTP Request/Response
    • Request                        • Response

    GET /servlet/SomeName HTTP/1.1   HTTP/1.1 200 OK
    Host: ...                        Content-Type: text/html
    Header2: ...                     Header2: ...
    ...                              ...
    HeaderN:                         HeaderN: ...
      (Blank Line)                     (Blank Line)
                                     <!DOCTYPE ...>
                                     <HTML>
                                     <HEAD>...</HEAD>
                                     <BODY>
                                     ...
                                     </BODY></HTML>
3
Setting Arbitrary Response
     Headers
    • The most general way to specify headers is
      to use the setHeader method of the
      HttpServletResponse class
      – public void setHeader(String headerName, String
        headerValue)
    • Two specialized methods set headers with
      dates and integers
      – public void setDateHeader(String name, long millisecs)
         • Converts milliseconds since 1970 to a date string in GMT
           format
      – public void setIntHeader(String name, int headerValue)
         • Prevents need to convert int to String before calling
           setHeader
    • addHeader, addDateHeader, addIntHeader
      – Adds new occurrence of header instead of replacing
4
Setting Common Response
    Headers
    • setContentType (String mimeType)
      – Sets the Content-Type header (MIME types)
    • setContentLength (int length)
      – Sets the Content-Length header (number of bytes
        in the response), which is useful if the browser
        supports persistent HTTP connections.
    • addCookie (Cookie c)
      – Adds a value to the Set-Cookie header.
    • sendRedirect (String address)
      – Sets the Location header (plus changes status
        code).
5
Common HTTP 1.1 Response
    Headers
    • Cache-Control (1.1) and Pragma (1.0)
      – A no-cache value prevents browsers from caching page.
    • Content-Disposition
      – Lets you request that the browser ask the user to save the
        response to disk in a file of the given name
         Content-Disposition: attachment;
          filename=file-name
    • Content-Encoding
      – The way document is encoded
    • Content-Length
      – The number of bytes in the response.
      – Use ByteArrayOutputStream to buffer document before
6
        sending it, so that you can determine size.
Common HTTP 1.1 Response
    Headers (Continued)
    • Content-Type
      – The MIME type of the document being returned.
    • Expires
      – The time at which document should be considered out-of-
        date and thus should no longer be cached.
      – Use setDateHeader to set this header.
    • Last-Modified
      – The time document was last changed.
      – Use the getLastModified method instead



7
Common HTTP 1.1 Response
    Headers (Continued)
    • Location
      – The URL to which browser should reconnect.
      – Use sendRedirect instead of setting this directly.
    • Refresh
      – The number of seconds until browser should reload page.
        Can also include URL to connect to.
    • Set-Cookie
      – The cookies that browser should remember. Don’t set this
        header directly; use addCookie instead.




8
Common MIME Types
      Type                            Meaning
      application/msword              Microsoft Word document
      application/octet-stream        Unrecognized or binary data
      application/pdf                 Acrobat (.pdf) file
      application/postscript          PostScript file
      application/vnd.ms-excel        Excel spreadsheet
      application/vnd.ms-powerpoint   Powerpoint presentation
      application/x-gzip              Gzip archive
      application/x-java-archive      JAR file
      application/x-java-vm           Java bytecode (.class) file
      application/zip                 Zip archive
      audio/basic                     Sound file in .au or .snd format
      audio/x-aiff                    AIFF sound file
      audio/x-wav                     Microsoft Windows sound file
      audio/midi                      MIDI sound file
      text/css                        HTML cascading style sheet
      text/html                       HTML document
      text/plain                      Plain text
      text/xml                        XML document
      image/gif                       GIF image
      image/jpeg                      JPEG image
      image/png                       PNG image
      image/tiff                      TIFF image
      video/mpeg                      MPEG video clip
      video/quicktime                 QuickTime video clip
9
Building Excel Spreadsheets
     • Though servlets usually generate HTML
       output, other types of output are possible
     • Microsoft Excel content can be generated
       so that the features of Excel can be
       exploited
     • The key is to include the following code
          response.setContentType
                ("application/vnd.ms-excel");
          PrintWriter out = response.getWriter();
     • Example will generate output in tab-
       separated format (include t in the output
       strings)
10
Building Excel Spreadsheets
     public class ApplesAndOranges extends HttpServlet {
       public void doGet(HttpServletRequest request,
                         HttpServletResponse response)
           throws ServletException, IOException {
           response.setContentType
             ("application/vnd.ms-excel");
           PrintWriter out = response.getWriter();
           out.println("tQ1tQ2tQ3tQ4tTotal");
           out.println
             ("Applest78t87t92t29t=SUM(B2:E2)");
           out.println
             ("Orangest77t86t93t30t=SUM(B3:E3)");
       }
     }


11
Building Excel Spreadsheets




12
Requirements for Handling
     Long-Running Servlets
     • What to do if a calculation requires a long
       time to complete (20 seconds) or whose
       results change periodically
     • Store data between requests.
       – For data that is not specific to any one client, store it in a
         field (instance variable) of the servlet.
       – For data that is specific to a user, store it in the
         HttpSession object
       – For data that needs to be available to other servlets or JSP
         pages (regardless of user), store it in the ServletContext
     • Keep computations running after the
       response is sent to the user.
       – Start a Thread but set the thread priority to a low value so
         that it does not slow down the server.
13
Requirements for Handling
     Long-Running Servlets
     • Send updated results to the browser when
       they are ready.
       – Browser does not maintain and open connection to the
         server. Use Refresh header to tell browser to ask for
         updates
          if (!isLastResult) {
            response.setIntHeader("Refresh",5);




14
Using Servlets to
     Generate JPEG Images
     1. Create a BufferedImage
     2. Draw into the BufferedImage
     3. Set the Content-Type response header
         response.setContentType("image/jpeg");
     4. Get an output stream
         OutputStream out = response.getOutputStream
     5. Send the BufferedImage in JPEG format to
        the output stream
         try {
           ImageIO.write(image, "jpg", out);
         } catch(IOException ioe) {
           System.err.println("Error writing JPEG file: "
                              + ioe);
         }
15

Mais conteúdo relacionado

Mais procurados

Mais procurados (9)

HTTP
HTTPHTTP
HTTP
 
Couchbase - Yet Another Introduction
Couchbase - Yet Another IntroductionCouchbase - Yet Another Introduction
Couchbase - Yet Another Introduction
 
Node.js Introduction
Node.js IntroductionNode.js Introduction
Node.js Introduction
 
Memcached Code Camp 2009
Memcached Code Camp 2009Memcached Code Camp 2009
Memcached Code Camp 2009
 
Polylog: A Log-Based Architecture for Distributed Systems
Polylog: A Log-Based Architecture for Distributed SystemsPolylog: A Log-Based Architecture for Distributed Systems
Polylog: A Log-Based Architecture for Distributed Systems
 
Thrift vs Protocol Buffers vs Avro - Biased Comparison
Thrift vs Protocol Buffers vs Avro - Biased ComparisonThrift vs Protocol Buffers vs Avro - Biased Comparison
Thrift vs Protocol Buffers vs Avro - Biased Comparison
 
Jms using j boss
Jms using j bossJms using j boss
Jms using j boss
 
Raj apache
Raj apacheRaj apache
Raj apache
 
Give Your Site a Boost with Memcache
Give Your Site a Boost with MemcacheGive Your Site a Boost with Memcache
Give Your Site a Boost with Memcache
 

Semelhante a 07 response-headers

06 response-headers
06 response-headers06 response-headers
06 response-headers
snopteck
 
05 status-codes
05 status-codes05 status-codes
05 status-codes
snopteck
 
Introducing asp
Introducing aspIntroducing asp
Introducing asp
aspnet123
 
12 core technologies you should learn, love, and hate to be a 'real' technocrat
12 core technologies you should learn, love, and hate to be a 'real' technocrat12 core technologies you should learn, love, and hate to be a 'real' technocrat
12 core technologies you should learn, love, and hate to be a 'real' technocrat
Jonathan Linowes
 

Semelhante a 07 response-headers (20)

Play framework
Play frameworkPlay framework
Play framework
 
06 response-headers
06 response-headers06 response-headers
06 response-headers
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
 
BITM3730Week12.pptx
BITM3730Week12.pptxBITM3730Week12.pptx
BITM3730Week12.pptx
 
Php intro
Php introPhp intro
Php intro
 
Php intro
Php introPhp intro
Php intro
 
Php intro
Php introPhp intro
Php intro
 
05 status-codes
05 status-codes05 status-codes
05 status-codes
 
Lotus Domino 8.5
Lotus Domino 8.5Lotus Domino 8.5
Lotus Domino 8.5
 
Introducing asp
Introducing aspIntroducing asp
Introducing asp
 
12 core technologies you should learn, love, and hate to be a 'real' technocrat
12 core technologies you should learn, love, and hate to be a 'real' technocrat12 core technologies you should learn, love, and hate to be a 'real' technocrat
12 core technologies you should learn, love, and hate to be a 'real' technocrat
 
Servlets
ServletsServlets
Servlets
 
Servlets Java Slides & Presentation
Servlets Java Slides & Presentation Servlets Java Slides & Presentation
Servlets Java Slides & Presentation
 
19servlets
19servlets19servlets
19servlets
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Servlet1.ppt
Servlet1.pptServlet1.ppt
Servlet1.ppt
 
12 core technologies you should learn, love, and hate to be a 'real' technocrat
12 core technologies you should learn, love, and hate to be a 'real' technocrat12 core technologies you should learn, love, and hate to be a 'real' technocrat
12 core technologies you should learn, love, and hate to be a 'real' technocrat
 
Generating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status CodesGenerating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status Codes
 
Practical OData
Practical ODataPractical OData
Practical OData
 

Último

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Último (20)

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 

07 response-headers

  • 1. Core Servlets and JavaServer Pages / 2e Volume 1: Core Technologies Marty Hall Larry Brown Generating the Server Response: HTTP Response Headers 1
  • 2. Agenda • Format of the HTTP response • Setting response headers • Understanding what response headers are good for • Building Excel spread sheets • Generating JPEG images dynamically • Sending incremental updates to the browser 2
  • 3. HTTP Request/Response • Request • Response GET /servlet/SomeName HTTP/1.1 HTTP/1.1 200 OK Host: ... Content-Type: text/html Header2: ... Header2: ... ... ... HeaderN: HeaderN: ... (Blank Line) (Blank Line) <!DOCTYPE ...> <HTML> <HEAD>...</HEAD> <BODY> ... </BODY></HTML> 3
  • 4. Setting Arbitrary Response Headers • The most general way to specify headers is to use the setHeader method of the HttpServletResponse class – public void setHeader(String headerName, String headerValue) • Two specialized methods set headers with dates and integers – public void setDateHeader(String name, long millisecs) • Converts milliseconds since 1970 to a date string in GMT format – public void setIntHeader(String name, int headerValue) • Prevents need to convert int to String before calling setHeader • addHeader, addDateHeader, addIntHeader – Adds new occurrence of header instead of replacing 4
  • 5. Setting Common Response Headers • setContentType (String mimeType) – Sets the Content-Type header (MIME types) • setContentLength (int length) – Sets the Content-Length header (number of bytes in the response), which is useful if the browser supports persistent HTTP connections. • addCookie (Cookie c) – Adds a value to the Set-Cookie header. • sendRedirect (String address) – Sets the Location header (plus changes status code). 5
  • 6. Common HTTP 1.1 Response Headers • Cache-Control (1.1) and Pragma (1.0) – A no-cache value prevents browsers from caching page. • Content-Disposition – Lets you request that the browser ask the user to save the response to disk in a file of the given name Content-Disposition: attachment; filename=file-name • Content-Encoding – The way document is encoded • Content-Length – The number of bytes in the response. – Use ByteArrayOutputStream to buffer document before 6 sending it, so that you can determine size.
  • 7. Common HTTP 1.1 Response Headers (Continued) • Content-Type – The MIME type of the document being returned. • Expires – The time at which document should be considered out-of- date and thus should no longer be cached. – Use setDateHeader to set this header. • Last-Modified – The time document was last changed. – Use the getLastModified method instead 7
  • 8. Common HTTP 1.1 Response Headers (Continued) • Location – The URL to which browser should reconnect. – Use sendRedirect instead of setting this directly. • Refresh – The number of seconds until browser should reload page. Can also include URL to connect to. • Set-Cookie – The cookies that browser should remember. Don’t set this header directly; use addCookie instead. 8
  • 9. Common MIME Types Type Meaning application/msword Microsoft Word document application/octet-stream Unrecognized or binary data application/pdf Acrobat (.pdf) file application/postscript PostScript file application/vnd.ms-excel Excel spreadsheet application/vnd.ms-powerpoint Powerpoint presentation application/x-gzip Gzip archive application/x-java-archive JAR file application/x-java-vm Java bytecode (.class) file application/zip Zip archive audio/basic Sound file in .au or .snd format audio/x-aiff AIFF sound file audio/x-wav Microsoft Windows sound file audio/midi MIDI sound file text/css HTML cascading style sheet text/html HTML document text/plain Plain text text/xml XML document image/gif GIF image image/jpeg JPEG image image/png PNG image image/tiff TIFF image video/mpeg MPEG video clip video/quicktime QuickTime video clip 9
  • 10. Building Excel Spreadsheets • Though servlets usually generate HTML output, other types of output are possible • Microsoft Excel content can be generated so that the features of Excel can be exploited • The key is to include the following code response.setContentType ("application/vnd.ms-excel"); PrintWriter out = response.getWriter(); • Example will generate output in tab- separated format (include t in the output strings) 10
  • 11. Building Excel Spreadsheets public class ApplesAndOranges extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType ("application/vnd.ms-excel"); PrintWriter out = response.getWriter(); out.println("tQ1tQ2tQ3tQ4tTotal"); out.println ("Applest78t87t92t29t=SUM(B2:E2)"); out.println ("Orangest77t86t93t30t=SUM(B3:E3)"); } } 11
  • 13. Requirements for Handling Long-Running Servlets • What to do if a calculation requires a long time to complete (20 seconds) or whose results change periodically • Store data between requests. – For data that is not specific to any one client, store it in a field (instance variable) of the servlet. – For data that is specific to a user, store it in the HttpSession object – For data that needs to be available to other servlets or JSP pages (regardless of user), store it in the ServletContext • Keep computations running after the response is sent to the user. – Start a Thread but set the thread priority to a low value so that it does not slow down the server. 13
  • 14. Requirements for Handling Long-Running Servlets • Send updated results to the browser when they are ready. – Browser does not maintain and open connection to the server. Use Refresh header to tell browser to ask for updates if (!isLastResult) { response.setIntHeader("Refresh",5); 14
  • 15. Using Servlets to Generate JPEG Images 1. Create a BufferedImage 2. Draw into the BufferedImage 3. Set the Content-Type response header response.setContentType("image/jpeg"); 4. Get an output stream OutputStream out = response.getOutputStream 5. Send the BufferedImage in JPEG format to the output stream try { ImageIO.write(image, "jpg", out); } catch(IOException ioe) { System.err.println("Error writing JPEG file: " + ioe); } 15