generating the server response: http response headers
TRANSCRIPT
Generating the Server Response: HTTP Response Headers
HTTP response headers
• Response headers can be used to specify cookies, to supply the page modification date , to instruct the browser to reload the page after a designated interval, to give the file size so that persistent HTTP connections can be used, to designate the type of document being generated, and to perform many other tasks.
Setting Response Headers from Servlets
• The following methods can be used to set HTTP response header in your servlet program. These methods are available with HttpServletResponse object.
• public void setHeader(String headerName, String headerValue) – Sets a response header with the given name and value.
• public void setDateHeader(String name, long millisecs)– Sets a response header with the given name and date-value.– 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.
Setting Common Response Headers• setContentType (String mimeType)– Sets the Content-Type header.
Servlets almost always use this.
• setContentLength (int length)– Sets the Content-Length header.
Used for persistent HTTP connections.
• addCookie(Cookie c)– Adds a value to the Set-Cookie header.
• sendRedirect (String address)– Sets the Location header as well as setting the status
code to 302.
Common MIME TypesType Meaning
application/msword Microsoft Word documentapplication/octet-stream Unrecognized or binary dataapplication/pdf Acrobat (.pdf) fileapplication/postscript PostScript fileapplication/vnd.ms-excel Excel spreadsheetapplication/vnd.ms-powerpoint Powerpoint presentationapplication/x-gzip Gzip archiveapplication/x-java-archive JAR fileapplication/x-java-vm Java bytecode (.class) fileapplication/zip Zip archiveaudio/basic Sound file in .au or .snd formataudio/x-aiff AIFF sound fileaudio/x-wav Microsoft Windows sound fileaudio/midi MIDI sound filetext/css HTML cascading style sheettext/html HTML documenttext/plain Plain texttext/xml XML documentimage/gif GIF imageimage/jpeg JPEG imageimage/png PNG imageimage/tiff TIFF imagevideo/mpeg MPEG video clipvideo/quicktime QuickTime video clip
HTTP 1.1 Response HeadersFollowing is a summary of the most useful HTTP 1.1 response
headers which go back to the browser from web server :• Allow Specifies the request methods(GET,POST,etc.) that the server
supports.• Cache-Control
This header specifies the circumstances in which the response document can safely be cached. It can have values public, private or no-cache etc. Public means document is cacheable, Private means document is for a single user and can only be stored in private (non shared) caches and no-cache means document should never be cached.
• Connection
This header instructs the browser whether to use persistent in HTTP connections or not. A value of close instructs the browser not to use persistent HTTP connections and keep-alive means using persistent connections.
Common HTTP 1.1 Response Headers (Continued)
• Content-Disposition– Lets you request that the browser ask the user to save the
response to disk in a file of the given nameContent-Disposition: attachment; filename=file-name
• Content-Language
This header signifies the language in which the document is written. For example en, en-us, etc.
• Content-Encoding – This header specifies the way in which the page was
encoded during transmission.• Content-Length– This header indicates the number of bytes in the response.
This information is needed only if the browser is using a persistent (keep-alive) HTTP connection.
Common HTTP 1.1 Response Headers (Continued)
• Content-Type– The MIME type of the document being returned.– Use setContentType to set this header.
• 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– This header indicates when the document was last changed. – Provide a getLastModified method to set this header.
Common HTTP 1.1 Response Headers (Continued)
• Location– The URL to which browser should reconnect. – Use sendRedirect instead of setting this directly.
• Refresh This header specifies how soon the browser should ask for an
updated page. You can specify time in number of seconds after which a page would be refreshed.
• Set-Cookie– This header specifies a cookie associated with the page. Use
addCookie method to set this header.
• WWW-Authenticate– This header tells the browser what authorization type is
needed in Authorization header.
Building Excel Spreadsheets• It is sometimes useful to generate Microsoft Excel content so
that users can save the results in a report and so that you can make use of the built-in formula support in Excel.
• Excel accepts input in at least three distinct formats: tab-separated data, HTML tables, and a native binary format.
• In this section, we illustrate the use of tab-separated data to generate spreadsheets.
• You use the shorthand setContentType method to set the Content-Type header, and the MIME type for Excel spreadsheets is application/vnd.ms-excel. So, to generate Excel spreadsheets, just do:
response.setContentType("application/vnd.ms-excel");PrintWriter out = response.getWriter();Then, simply print some entries with tabs (\t in Java strings) in
between.
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("\tQ1\tQ2\tQ3\tQ4\tTotal");
out.println("Apples\t78\t87\t92\t29\t=SUM(B2:E2)");
out.println ("Oranges\t77\t86\t93\t30\t=SUM(B3:E3)");
}
}
Building Excel Spreadsheets
Requirements for Handling Long-Running Servlets
• A way to 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 • A way to keep computations running after the response is sent
to the user.
- This task is simple: just start a Thread. The thread started by the system to answer requests automatically finishes when the response is finished, but other threads can keep running. 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 ready. – Use Refresh header to tell browser to ask for updates
Using Servlets to Generate JPEG Images1. Create a BufferedImage
BufferedImage image = new BufferedImage(width,height, BufferedImage.TYPE_INT_RBG);
2. Draw into the BufferedImage
Graphics2D g2d = (Grahics2D)image.getGrapics();
g2d.fill(someshape);
g2d.draw(someshape);
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);
}
Using Servlets to Generate JPEG Images
Using Servlets to Generate JPEG Images