SlideShare ist ein Scribd-Unternehmen logo
1 von 12
Downloaden Sie, um offline zu lesen
© 2010 Marty Hall
Generating the Serverg
Response: HTTP
Response HeadersResponse HeadersOriginals of Slides and Source Code for Examples:
http://courses.coreservlets.com/Course-Materials/csajsp2.html
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.2
p j p
© 2010 Marty Hall
For live Java EE training, please see training courses
at http://courses.coreservlets.com/.at http://courses.coreservlets.com/.
Servlets, JSP, Struts, JSF 1.x, JSF 2.0, Ajax (with jQuery, Dojo,
Prototype, Ext-JS, Google Closure, etc.), GWT 2.0 (with GXT),
Java 5, Java 6, SOAP-based and RESTful Web Services, Spring,g
Hibernate/JPA, and customized combinations of topics.
Taught by the author of Core Servlets and JSP, More
Servlets and JSP and this tutorial Available at public
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Servlets and JSP, and this tutorial. Available at public
venues, or customized versions can be held on-site at your
organization. Contact hall@coreservlets.com for details.
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
4
HTTP Request/Responseq p
• Request • Response
GET /servlet/SomeName HTTP/1.1
Host: ...
HTTP/1.1 200 OK
Content-Type: text/html
Header2: ...
...
HeaderN:
Content Type: text/html
Header2: ...
...
HeaderN:HeaderN:
(Blank Line)
HeaderN: ...
(Blank Line)
<!DOCTYPE ...>
<HTML>
<HEAD>...</HEAD>
<BODY>
...
</BODY></HTML>
5
Setting Arbitrary Response
HeadersHeaders
• response.setHeader(String headerName,
S i h d V l )String headerValue)
– Sets an arbitrary header
• response setDateHeader(String name• response.setDateHeader(String name,
long millisecs)
– Converts milliseconds since 1970 to a date stringg
in GMT format
• response.setIntHeader(String name,
i t h d V l )int headerValue)
– Prevents need to convert int to String before calling
setHeadersetHeader
• addHeader, addDateHeader, addIntHeader
– Adds new occurrence of header instead of replacing6
Setting Common Response
HeadersHeaders
• setContentType
S t th C t t T h d– Sets the Content-Type header.
– Servlets almost always use this.
– See table of common MIME types.yp
• setContentLength
– Sets the Content-Length header.
Used for persistent HTTP connections– Used for persistent HTTP connections.
– See Connection request header.
• addCookie
– Adds a value to the Set-Cookie header.
– See separate section on cookies.
• sendRedirect• sendRedirect
– Sets the Location header (plus changes status code).
7
Common MIME Types
Type Meaning
application/msword Microsoft Word document
application/octet stream Unrecognized or binary dataapplication/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
li i / i i hiapplication/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 documenttext/html HTML document
text/plain Plain text
text/xml XML document
image/gif GIF image
image/jpeg JPEG image
image/png PNG image
8
image/png PNG image
image/tiff TIFF image
video/mpeg MPEG video clip
video/quicktime QuickTime video clip
Building Excel Spreadsheets
public class ApplesAndOranges extends HttpServlet {
public void doGet(HttpServletRequest requestpublic void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response setContentTyperesponse.setContentType
("application/vnd.ms-excel");
PrintWriter out = response.getWriter();
t i tl ("tQ1tQ2tQ3tQ4tT t l")out.println("tQ1tQ2tQ3tQ4tTotal");
out.println
("Applest78t87t92t29t=SUM(B2:E2)");
out.println
("Orangest77t86t93t30t=SUM(B3:E3)");
}
}
9
Building Excel Spreadsheets
10
Common HTTP 1.1 Response
HeadersHeaders
• Cache-Control (1.1) and Pragma (1.0)
A h l b f hi– A no-cache value prevents browsers from caching page.
• Content-Disposition
– Lets you request that the browser ask the user to save the responsey q p
to disk in a file of the given name
Content-Disposition: attachment; filename=file-name
• Content-Encoding• Content-Encoding
– The way document is encoded. See earlier compression example
• Content-Length
– The number of bytes in the response.
– See setContentLength on previous slide.
– Use ByteArrayOutputStream to buffer document before sending it,y y p g ,
so that you can determine size. See discussion of the Connection
request header
11
Common HTTP 1.1 Response
Headers (Continued)Headers (Continued)
• Content-Type
– The MIME type of the document being returned.
– Use setContentType to set this header.
Expires• Expires
– The time at which document should be considered out-of-
date and thus should no longer be cached.g
– Use setDateHeader to set this header.
• Last-Modified
– The time document was last changed.
– Don’t set this header explicitly; provide a
getLastModified method instead See lottery numbergetLastModified method instead. See lottery number
example in book (Chapter 3).
12
Common HTTP 1.1 Response
Headers (Continued)Headers (Continued)
• Location
– The URL to which browser should reconnect.
– Use sendRedirect instead of setting this directly.
Refresh• Refresh
– The number of seconds until browser should reload page.
Can also include URL to connect to.C U
See following example.
• Set-Cookie
– The cookies that browser should remember. Don’t set this
header directly; use addCookie instead. See next section.
• WWW-Authenticate• WWW-Authenticate
– The authorization type and realm needed in Authorization
header. See security chapters in More Servlets & JSP.13
Requirements for Handling
Long-Running ServletsLong-Running Servlets
• A way to store data between requests.
F d h i ifi li i i fi ld– 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
S• See upcoming lecture on session tracking
– For data that needs to be available to other servlets or JSP pages
(regardless of user), store it in the ServletContext
• A way to keep computations running after the
response is sent to the user.
– This task is simple: start a Thread. The only subtlety: set the threadThis task is simple: start a Thread. The only subtlety: set the thread
priority to a low value so that you do not slow down the server.
• A way to get the updated results to the browser
when they are readywhen they are ready.
– Use Refresh header to tell browser to ask for updates
14
Persistent Servlet State and
Auto-Reloading Pages: ExampleAuto-Reloading Pages: Example
• Idea: generate list of large (e.g., 150-digit)
i bprime numbers
– Show partial results until completed
Let new clients make use of results from others– Let new clients make use of results from others
• Demonstrates use of the Refresh header.
• Shows how easy it is for servlets to• Shows how easy it is for servlets to
maintain state between requests.
– Very difficult in traditional CGI.y
• Also illustrates that servlets can handle
multiple simultaneous connections
– Each request is in a separate thread.
15
Finding Prime Numbers for Use
with Public Key Cryptographywith Public Key Cryptography
public class PrimeNumberServlet extends HttpServlet {
private List<PrimeList> primeListCollection =private List<PrimeList> primeListCollection
new ArrayList<PrimeList>();
private int maxPrimeLists = 30;
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
int numPrimes =int numPrimes =
ServletUtilities.getIntParameter(request,
"numPrimes", 50);
int numDigits =
ServletUtilities.getIntParameter(request,
"numDigits", 120);
PrimeList primeList =
fi dP i Li t( i Li tC ll tifindPrimeList(primeListCollection,
numPrimes, numDigits);
16
Finding Prime Numbers for Use
with Public Key Cryptographywith Public Key Cryptography
if (primeList == null) {
primeList = new PrimeList(numPrimes, numDigits, true);primeList new PrimeList(numPrimes, numDigits, true);
synchronized(primeListCollection) {
if (primeListCollection.size() >= maxPrimeLists)
primeListCollection.remove(0);p
primeListCollection.add(primeList);
}
}
List<BigInteger> currentPrimes =
primeList.getPrimes();
int numCurrentPrimes = currentPrimes.size();
i t P i R i i ( P i C tP i )int numPrimesRemaining = (numPrimes - numCurrentPrimes);
boolean isLastResult = (numPrimesRemaining == 0);
if (!isLastResult) {
response setIntHeader("Refresh" 5);response.setIntHeader( Refresh , 5);
}
…
17
Finding Prime Numbers for Use
with Public Key Cryptographywith Public Key Cryptography
18
Finding Prime Numbers for Use
with Public Key Cryptographywith Public Key Cryptography
19
Using Servlets to
Generate JPEG ImagesGenerate 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.getOutputStreamOutputStream out response.getOutputStream
5. Send the BufferedImage in JPEG format to
the output streamp
try {
ImageIO.write(image, "jpg", out);
} catch(IOException ioe) {
System.err.println("Error writing JPEG file: "
+ ioe);
}20
Using Servlets to
Generate JPEG ImagesGenerate JPEG Images
21
Using Servlets to
Generate JPEG ImagesGenerate JPEG Images
22
Summary
• Many servlet tasks can only be accomplished
th h f HTTP h dthrough use of HTTP response headers
• Setting response headers:
– In general, set with response.setHeader
– In special cases, set with response.setContentType,
response.setContentLength, response.addCookie, and
response.sendRedirect
M t i t t h d t di tl• Most important response headers you set directly:
– Cache-Control and Pragma
– Content-Disposition
C E di– Content-Encoding
– Content-Length
– Expires
R f h– Refresh
– WWW-Authenticate
23
© 2010 Marty Hall
Questions?
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.24

Weitere ähnliche Inhalte

Was ist angesagt?

APC & Memcache the High Performance Duo
APC & Memcache the High Performance DuoAPC & Memcache the High Performance Duo
APC & Memcache the High Performance Duo
Anis Berejeb
 

Was ist angesagt? (19)

Bring your infrastructure under control with Infrastructor
Bring your infrastructure under control with InfrastructorBring your infrastructure under control with Infrastructor
Bring your infrastructure under control with Infrastructor
 
Apache ZooKeeper
Apache ZooKeeperApache ZooKeeper
Apache ZooKeeper
 
Introduction to apache zoo keeper
Introduction to apache zoo keeper Introduction to apache zoo keeper
Introduction to apache zoo keeper
 
The Ring programming language version 1.7 book - Part 52 of 196
The Ring programming language version 1.7 book - Part 52 of 196The Ring programming language version 1.7 book - Part 52 of 196
The Ring programming language version 1.7 book - Part 52 of 196
 
Java и Linux — особенности эксплуатации / Алексей Рагозин (Дойче Банк)
Java и Linux — особенности эксплуатации / Алексей Рагозин (Дойче Банк)Java и Linux — особенности эксплуатации / Алексей Рагозин (Дойче Банк)
Java и Linux — особенности эксплуатации / Алексей Рагозин (Дойче Банк)
 
GopherFest 2017 - Adding Context to NATS
GopherFest 2017 -  Adding Context to NATSGopherFest 2017 -  Adding Context to NATS
GopherFest 2017 - Adding Context to NATS
 
How Prometheus Store the Data
How Prometheus Store the DataHow Prometheus Store the Data
How Prometheus Store the Data
 
Hadoop Puzzlers
Hadoop PuzzlersHadoop Puzzlers
Hadoop Puzzlers
 
Winter is coming? Not if ZooKeeper is there!
Winter is coming? Not if ZooKeeper is there!Winter is coming? Not if ZooKeeper is there!
Winter is coming? Not if ZooKeeper is there!
 
Distributed Lock Manager
Distributed Lock ManagerDistributed Lock Manager
Distributed Lock Manager
 
Java concurrency introduction
Java concurrency introductionJava concurrency introduction
Java concurrency introduction
 
Zookeeper Introduce
Zookeeper IntroduceZookeeper Introduce
Zookeeper Introduce
 
Python twisted
Python twistedPython twisted
Python twisted
 
Introduction to Apache ZooKeeper | Big Data Hadoop Spark Tutorial | CloudxLab
Introduction to Apache ZooKeeper | Big Data Hadoop Spark Tutorial | CloudxLabIntroduction to Apache ZooKeeper | Big Data Hadoop Spark Tutorial | CloudxLab
Introduction to Apache ZooKeeper | Big Data Hadoop Spark Tutorial | CloudxLab
 
Go Programming Patterns
Go Programming PatternsGo Programming Patterns
Go Programming Patterns
 
Introduction to Apache ZooKeeper
Introduction to Apache ZooKeeperIntroduction to Apache ZooKeeper
Introduction to Apache ZooKeeper
 
Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研
 
Php
PhpPhp
Php
 
APC & Memcache the High Performance Duo
APC & Memcache the High Performance DuoAPC & Memcache the High Performance Duo
APC & Memcache the High Performance Duo
 

Andere mochten auch (19)

The Change! Tool
The Change! ToolThe Change! Tool
The Change! Tool
 
05 status-codes
05 status-codes05 status-codes
05 status-codes
 
10 jdbc
10 jdbc10 jdbc
10 jdbc
 
01 overview-and-setup
01 overview-and-setup01 overview-and-setup
01 overview-and-setup
 
01 web-apps
01 web-apps01 web-apps
01 web-apps
 
13 java beans
13 java beans13 java beans
13 java beans
 
10 jdbc
10 jdbc10 jdbc
10 jdbc
 
14 mvc
14 mvc14 mvc
14 mvc
 
15 expression-language
15 expression-language15 expression-language
15 expression-language
 
03 form-data
03 form-data03 form-data
03 form-data
 
ICT observatories for better governance
ICT observatories for better governanceICT observatories for better governance
ICT observatories for better governance
 
08 session-tracking
08 session-tracking08 session-tracking
08 session-tracking
 
07 cookies
07 cookies07 cookies
07 cookies
 
02 servlet-basics
02 servlet-basics02 servlet-basics
02 servlet-basics
 
11 page-directive
11 page-directive11 page-directive
11 page-directive
 
Digital Engagement for CSPs
Digital Engagement for CSPsDigital Engagement for CSPs
Digital Engagement for CSPs
 
04 request-headers
04 request-headers04 request-headers
04 request-headers
 
Linea Viso-Corpo "Naturale" by Delta BkB
Linea Viso-Corpo "Naturale" by Delta BkBLinea Viso-Corpo "Naturale" by Delta BkB
Linea Viso-Corpo "Naturale" by Delta BkB
 
08 session-tracking
08 session-tracking08 session-tracking
08 session-tracking
 

Ähnlich wie 06 response-headers

Ähnlich wie 06 response-headers (20)

Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
 
SCWCD : Thread safe servlets : CHAP : 8
SCWCD : Thread safe servlets : CHAP : 8SCWCD : Thread safe servlets : CHAP : 8
SCWCD : Thread safe servlets : CHAP : 8
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
 
Servlets
ServletsServlets
Servlets
 
Servlet
Servlet Servlet
Servlet
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
07 response-headers
07 response-headers07 response-headers
07 response-headers
 
Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdf
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSP
 
19servlets
19servlets19servlets
19servlets
 
BITM3730Week12.pptx
BITM3730Week12.pptxBITM3730Week12.pptx
BITM3730Week12.pptx
 
Servlets
ServletsServlets
Servlets
 
Servlets Java Slides & Presentation
Servlets Java Slides & Presentation Servlets Java Slides & Presentation
Servlets Java Slides & Presentation
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 
Advance Java Programming (CM5I) 6.Servlet
Advance Java Programming (CM5I) 6.ServletAdvance Java Programming (CM5I) 6.Servlet
Advance Java Programming (CM5I) 6.Servlet
 
1 java servlets and jsp
1   java servlets and jsp1   java servlets and jsp
1 java servlets and jsp
 
ADP - Chapter 2 Exploring the java Servlet Technology
ADP - Chapter 2 Exploring the java Servlet TechnologyADP - Chapter 2 Exploring the java Servlet Technology
ADP - Chapter 2 Exploring the java Servlet Technology
 

Kürzlich hochgeladen

Kürzlich hochgeladen (20)

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 Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 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
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
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
 
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
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
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
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 

06 response-headers

  • 1. © 2010 Marty Hall Generating the Serverg Response: HTTP Response HeadersResponse HeadersOriginals of Slides and Source Code for Examples: http://courses.coreservlets.com/Course-Materials/csajsp2.html Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.2 p j p © 2010 Marty Hall For live Java EE training, please see training courses at http://courses.coreservlets.com/.at http://courses.coreservlets.com/. Servlets, JSP, Struts, JSF 1.x, JSF 2.0, Ajax (with jQuery, Dojo, Prototype, Ext-JS, Google Closure, etc.), GWT 2.0 (with GXT), Java 5, Java 6, SOAP-based and RESTful Web Services, Spring,g Hibernate/JPA, and customized combinations of topics. Taught by the author of Core Servlets and JSP, More Servlets and JSP and this tutorial Available at public Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. Servlets and JSP, and this tutorial. Available at public venues, or customized versions can be held on-site at your organization. Contact hall@coreservlets.com for details.
  • 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 4 HTTP Request/Responseq p • Request • Response GET /servlet/SomeName HTTP/1.1 Host: ... HTTP/1.1 200 OK Content-Type: text/html Header2: ... ... HeaderN: Content Type: text/html Header2: ... ... HeaderN:HeaderN: (Blank Line) HeaderN: ... (Blank Line) <!DOCTYPE ...> <HTML> <HEAD>...</HEAD> <BODY> ... </BODY></HTML> 5
  • 3. Setting Arbitrary Response HeadersHeaders • response.setHeader(String headerName, S i h d V l )String headerValue) – Sets an arbitrary header • response setDateHeader(String name• response.setDateHeader(String name, long millisecs) – Converts milliseconds since 1970 to a date stringg in GMT format • response.setIntHeader(String name, i t h d V l )int headerValue) – Prevents need to convert int to String before calling setHeadersetHeader • addHeader, addDateHeader, addIntHeader – Adds new occurrence of header instead of replacing6 Setting Common Response HeadersHeaders • setContentType S t th C t t T h d– Sets the Content-Type header. – Servlets almost always use this. – See table of common MIME types.yp • setContentLength – Sets the Content-Length header. Used for persistent HTTP connections– Used for persistent HTTP connections. – See Connection request header. • addCookie – Adds a value to the Set-Cookie header. – See separate section on cookies. • sendRedirect• sendRedirect – Sets the Location header (plus changes status code). 7
  • 4. Common MIME Types Type Meaning application/msword Microsoft Word document application/octet stream Unrecognized or binary dataapplication/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 li i / i i hiapplication/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 documenttext/html HTML document text/plain Plain text text/xml XML document image/gif GIF image image/jpeg JPEG image image/png PNG image 8 image/png PNG image image/tiff TIFF image video/mpeg MPEG video clip video/quicktime QuickTime video clip Building Excel Spreadsheets public class ApplesAndOranges extends HttpServlet { public void doGet(HttpServletRequest requestpublic void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response setContentTyperesponse.setContentType ("application/vnd.ms-excel"); PrintWriter out = response.getWriter(); t i tl ("tQ1tQ2tQ3tQ4tT t l")out.println("tQ1tQ2tQ3tQ4tTotal"); out.println ("Applest78t87t92t29t=SUM(B2:E2)"); out.println ("Orangest77t86t93t30t=SUM(B3:E3)"); } } 9
  • 5. Building Excel Spreadsheets 10 Common HTTP 1.1 Response HeadersHeaders • Cache-Control (1.1) and Pragma (1.0) A h l b f hi– A no-cache value prevents browsers from caching page. • Content-Disposition – Lets you request that the browser ask the user to save the responsey q p to disk in a file of the given name Content-Disposition: attachment; filename=file-name • Content-Encoding• Content-Encoding – The way document is encoded. See earlier compression example • Content-Length – The number of bytes in the response. – See setContentLength on previous slide. – Use ByteArrayOutputStream to buffer document before sending it,y y p g , so that you can determine size. See discussion of the Connection request header 11
  • 6. Common HTTP 1.1 Response Headers (Continued)Headers (Continued) • Content-Type – The MIME type of the document being returned. – Use setContentType to set this header. Expires• Expires – The time at which document should be considered out-of- date and thus should no longer be cached.g – Use setDateHeader to set this header. • Last-Modified – The time document was last changed. – Don’t set this header explicitly; provide a getLastModified method instead See lottery numbergetLastModified method instead. See lottery number example in book (Chapter 3). 12 Common HTTP 1.1 Response Headers (Continued)Headers (Continued) • Location – The URL to which browser should reconnect. – Use sendRedirect instead of setting this directly. Refresh• Refresh – The number of seconds until browser should reload page. Can also include URL to connect to.C U See following example. • Set-Cookie – The cookies that browser should remember. Don’t set this header directly; use addCookie instead. See next section. • WWW-Authenticate• WWW-Authenticate – The authorization type and realm needed in Authorization header. See security chapters in More Servlets & JSP.13
  • 7. Requirements for Handling Long-Running ServletsLong-Running Servlets • A way to store data between requests. F d h i ifi li i i fi ld– 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 S• See upcoming lecture on session tracking – For data that needs to be available to other servlets or JSP pages (regardless of user), store it in the ServletContext • A way to keep computations running after the response is sent to the user. – This task is simple: start a Thread. The only subtlety: set the threadThis task is simple: start a Thread. The only subtlety: set the thread priority to a low value so that you do not slow down the server. • A way to get the updated results to the browser when they are readywhen they are ready. – Use Refresh header to tell browser to ask for updates 14 Persistent Servlet State and Auto-Reloading Pages: ExampleAuto-Reloading Pages: Example • Idea: generate list of large (e.g., 150-digit) i bprime numbers – Show partial results until completed Let new clients make use of results from others– Let new clients make use of results from others • Demonstrates use of the Refresh header. • Shows how easy it is for servlets to• Shows how easy it is for servlets to maintain state between requests. – Very difficult in traditional CGI.y • Also illustrates that servlets can handle multiple simultaneous connections – Each request is in a separate thread. 15
  • 8. Finding Prime Numbers for Use with Public Key Cryptographywith Public Key Cryptography public class PrimeNumberServlet extends HttpServlet { private List<PrimeList> primeListCollection =private List<PrimeList> primeListCollection new ArrayList<PrimeList>(); private int maxPrimeLists = 30; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int numPrimes =int numPrimes = ServletUtilities.getIntParameter(request, "numPrimes", 50); int numDigits = ServletUtilities.getIntParameter(request, "numDigits", 120); PrimeList primeList = fi dP i Li t( i Li tC ll tifindPrimeList(primeListCollection, numPrimes, numDigits); 16 Finding Prime Numbers for Use with Public Key Cryptographywith Public Key Cryptography if (primeList == null) { primeList = new PrimeList(numPrimes, numDigits, true);primeList new PrimeList(numPrimes, numDigits, true); synchronized(primeListCollection) { if (primeListCollection.size() >= maxPrimeLists) primeListCollection.remove(0);p primeListCollection.add(primeList); } } List<BigInteger> currentPrimes = primeList.getPrimes(); int numCurrentPrimes = currentPrimes.size(); i t P i R i i ( P i C tP i )int numPrimesRemaining = (numPrimes - numCurrentPrimes); boolean isLastResult = (numPrimesRemaining == 0); if (!isLastResult) { response setIntHeader("Refresh" 5);response.setIntHeader( Refresh , 5); } … 17
  • 9. Finding Prime Numbers for Use with Public Key Cryptographywith Public Key Cryptography 18 Finding Prime Numbers for Use with Public Key Cryptographywith Public Key Cryptography 19
  • 10. Using Servlets to Generate JPEG ImagesGenerate 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.getOutputStreamOutputStream out response.getOutputStream 5. Send the BufferedImage in JPEG format to the output streamp try { ImageIO.write(image, "jpg", out); } catch(IOException ioe) { System.err.println("Error writing JPEG file: " + ioe); }20 Using Servlets to Generate JPEG ImagesGenerate JPEG Images 21
  • 11. Using Servlets to Generate JPEG ImagesGenerate JPEG Images 22 Summary • Many servlet tasks can only be accomplished th h f HTTP h dthrough use of HTTP response headers • Setting response headers: – In general, set with response.setHeader – In special cases, set with response.setContentType, response.setContentLength, response.addCookie, and response.sendRedirect M t i t t h d t di tl• Most important response headers you set directly: – Cache-Control and Pragma – Content-Disposition C E di– Content-Encoding – Content-Length – Expires R f h– Refresh – WWW-Authenticate 23
  • 12. © 2010 Marty Hall Questions? Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.24