SlideShare une entreprise Scribd logo
1  sur  15
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

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
 

Tendances (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
 

Similaire à 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
 

Similaire à 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
 

Dernier

What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 

Dernier (20)

What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 

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