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

Couchbase - Yet Another Introduction
Couchbase - Yet Another IntroductionCouchbase - Yet Another Introduction
Couchbase - Yet Another IntroductionKelum Senanayake
 
Memcached Code Camp 2009
Memcached Code Camp 2009Memcached Code Camp 2009
Memcached Code Camp 2009NorthScale
 
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 SystemsLongtail Video
 
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 ComparisonIgor Anishchenko
 
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 MemcacheBen Ramsey
 

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 Generating Dynamic Excel Spreadsheets and JPEG Images with Servlets

06 response-headers
06 response-headers06 response-headers
06 response-headerssnopteck
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing Techglyphs
 
BITM3730Week12.pptx
BITM3730Week12.pptxBITM3730Week12.pptx
BITM3730Week12.pptxMattMarino13
 
05 status-codes
05 status-codes05 status-codes
05 status-codessnopteck
 
Introducing asp
Introducing aspIntroducing asp
Introducing aspaspnet123
 
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' technocratJonathan Linowes
 
Servlets Java Slides & Presentation
Servlets Java Slides & Presentation Servlets Java Slides & Presentation
Servlets Java Slides & Presentation Anas Sa
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.pptkstalin2
 
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' technocratlinoj
 
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 CodesDeeptiJava
 

Semelhante a Generating Dynamic Excel Spreadsheets and JPEG Images with Servlets (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

WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
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...apidays
 
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...Miguel Araújo
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
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 MenDelhi Call girls
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
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 WorkerThousandEyes
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
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 productivityPrincipled Technologies
 
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 2024The Digital Insurer
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 

Último (20)

WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
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...
 
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...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
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
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
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
 
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
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 

Generating Dynamic Excel Spreadsheets and JPEG Images with Servlets

  • 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