http response headers vijayan sugumaran department of dis oakland university parts of this...
Post on 21-Dec-2015
217 views
TRANSCRIPT
![Page 1: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/1.jpg)
HTTP Response Headers
Vijayan Sugumaran
Department of DIS
Oakland University
Parts of this presentation was provided by www.coreservlets.com
![Page 2: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/2.jpg)
Important Topics Idea of HTTP status codes Setting status codes from servlets Common HTTP 1.1 status codes A common front end to various Web search
engines Idea of HTTP response headers Setting response headers from servlets Common HTTP 1.1 response headers Persistent servlet state and auto-reloading pages
![Page 3: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/3.jpg)
HTTP Request/Response
Request
GET /servlet/SomeName HTTP/1.1
Host: ...
Header2: ...
...
HeaderN:
(Blank Line)
Response
HTTP/1.1 200 OK
Content-Type: text/html
Header2: ...
...
HeaderN: ...
(Blank Line)
<!DOCTYPE ...>
<HTML>
<HEAD>...</HEAD>
<BODY>
...
</BODY></HTML>
![Page 4: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/4.jpg)
Generating the Server Response: HTTP Status Codes Example HTTP 1.1 Response
HTTP/1.1 200 OKContent-Type: text/html
<!DOCTYPE ...><HTML>...</HTML>
Changing the status code lets you perform a number of tasks not otherwise possible Forward client to another page Indicate a missing resource Instruct browser to use cached copy
Set status before sending document
![Page 5: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/5.jpg)
Setting Status Codes public void setStatus(int statusCode)
Use a constant for the code, not an explicit int.Constants are in HttpServletResponse
Names derived from standard message.E.g., SC_OK, SC_NOT_FOUND, etc.
public void sendError(int code, String message)
Wraps message inside small HTML document public void sendRedirect(String url)
Relative URLs permitted in 2.2 and later Sets Location header also
![Page 6: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/6.jpg)
Five Categories of Status Codes 100 – 199
Informational codes Client should respond with some other action
200 – 299 Signify that the request was successful
300 – 399 Used for files that have moved Includes a Location header indicating the new
address 400 – 499
Error by the client 500 – 599
Signify an error by the server
![Page 7: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/7.jpg)
Common HTTP 1.1 Status Codes 200 (OK)
Everything is fine; document follows. Default for servlets.
204 (No Content) Browser should keep displaying previous
document. 301 (Moved Permanently)
Requested document permanently moved elsewhere (indicated in Location header).
Browsers go to new location automatically.
![Page 8: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/8.jpg)
Common HTTP 1.1 Status Codes (contd.)
302 (Found) Requested document temporarily moved
elsewhere (indicated in Location header). Browsers go to new location automatically. Servlets should use sendRedirect, not setStatus,
when setting this header. 401 (Unauthorized)
Browser tried to access password-protected page without proper Authorization header.
404 (Not Found) No such page. Servlets should use sendError to
set this.
![Page 9: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/9.jpg)
Status Code Summary1. Informational 1xx
100 Continue101 Switching Protocols
2. Successful 2xx200 OK201 Created202 Accepted203 Non-Authoritative Information 204 No Content205 Reset Content206 Partial Content
![Page 10: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/10.jpg)
Status Code Summary3. Redirection 3xx
300 Multiple Choices301 Moved Permanently 302 Found303 See Other304 Not Modified305 Use Proxy306 (Unused)307 Temporary Redirect
![Page 11: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/11.jpg)
Status Code Summary
4. Client Error 4xx
400 Bad Request401 Unauthorized402 Payment Required403 Forbidden404 Not Found405 Method Not Allowed406 Not Acceptable407 Proxy Authentication Required408 Request Timeout
409 Conflict410 Gone411 Length Required412 Precondition Failed413 Request Entity Too Large414 Request-URI Too Long415 Unsupported Media Type416 Requested Range Not Satisfiable417 Expectation Failed
![Page 12: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/12.jpg)
Status Code Summary
5. Server Error 5xx500 Internal Server Error501 Not Implemented502 Bad Gateway503 Service Unavailable504 Gateway Timeout505 HTTP Version Not Supported
http://www.w3.org/Protocols/rfc2616/rfc2616.htmlURL for HTTP 1.1 Specification
![Page 13: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/13.jpg)
A Servlet That Redirects Users to Browser-Specific Pages
public class WrongDestination extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String userAgent = request.getHeader("User-Agent");
if ((userAgent != null) &&
(userAgent.indexOf("MSIE") != -1)) {
response.sendRedirect("http://home.netscape.com");
} else {
response.sendRedirect("http://www.microsoft.com");
}
}
}
![Page 14: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/14.jpg)
A Servlet That Redirects Users to Browser-Specific Pages
![Page 15: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/15.jpg)
A Front End to Various Search Enginespublic class SearchEngines extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String searchString =
request.getParameter("searchString");
if ((searchString == null) ||
(searchString.length() == 0)) {
reportProblem(response, "Missing search string");
return; }
searchString = URLEncoder.encode(searchString);
String searchEngineName =
request.getParameter("searchEngine");
if ((searchEngineName == null) ||
(searchEngineName.length() == 0)) {
reportProblem(response, "Missing search engine name");
return; }
![Page 16: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/16.jpg)
A Front End to Various Search Engines (Continued) String searchURL =
SearchUtilities.makeURL(searchEngineName, searchString);
if (searchURL != null) {
response.sendRedirect(searchURL);
} else {
reportProblem(response,
"Unrecognized search engine");
}
}
private void reportProblem(HttpServletResponse response,
String message) throws IOException {
response.sendError(response.SC_NOT_FOUND, message);
}
}
![Page 17: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/17.jpg)
A Front End to Various Search Engines (Continued)public class SearchSpec {
/** Builds a URL for the results page by
* simply concatenating the base URL
* (http://...?someVar=") with the
* URL-encoded search string (jsp+training).
*/
public String makeURL(String searchString) {
return(baseURL + searchString);
}
…
}
![Page 18: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/18.jpg)
Front End to Search Engines: HTML Form
![Page 19: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/19.jpg)
Front End to Search Engines: Result for Valid Data
![Page 20: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/20.jpg)
Front End to Search Engines: Result for Invalid Data
![Page 21: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/21.jpg)
Summary Many servlet tasks can only be accomplished through use of
HTTP status codes Setting status codes:
In general, set via response.setStatus In special cases (302 and 404), set with
response.sendRedirect and response.sendError
Most important status codes 200 (default) 302 (forwarding; set with sendRedirect) 401 (password needed) 404 (not found; set with sendError)
![Page 22: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/22.jpg)
Generating the Server Response: HTTP Response Headers
![Page 23: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/23.jpg)
AgendaFormat of the HTTP responseSetting response headersUnderstanding what response
headers are good forBuilding Excel spread sheetsGenerating JPEG images dynamicallySending incremental updates
to the browser
![Page 24: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/24.jpg)
HTTP Request/Response Request
GET /servlet/SomeName HTTP/1.1
Host: ...
Header2: ...
...
HeaderN:
(Blank Line)
Response
HTTP/1.1 200 OK
Content-Type: text/html
Header2: ...
...
HeaderN: ...
(Blank Line)
<!DOCTYPE ...>
<HTML>
<HEAD>...</HEAD>
<BODY>
...
</BODY></HTML>
![Page 25: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/25.jpg)
Setting Arbitrary Response Headers public void setHeader(String headerName,
String headerValue) Sets an arbitrary header.
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.
![Page 26: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/26.jpg)
Setting Common Response Headers setContentType
Sets the Content-Type header. Servlets almost always use this. See table of common MIME types.
setContentLength Sets the Content-Length header.
Used for persistent HTTP connections. See Connection request header.
addCookie Adds a value to the Set-Cookie header.
See separate section on cookies. sendRedirect
Sets the Location header (plus changes status code).
![Page 27: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/27.jpg)
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
![Page 28: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/28.jpg)
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. 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, so
that you can determine size. See discussion of the Connection request header
![Page 29: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/29.jpg)
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 The time document was last changed. Don’t set this header explicitly; provide a
getLastModified method instead. See lottery number example in book (Chapter 3).
![Page 30: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/30.jpg)
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. 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
The authorization type and realm needed in Authorization header. See security chapters in More Servlets & JSP.
![Page 31: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/31.jpg)
Building Excel Spreadsheetspublic 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)");
}
}
![Page 32: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/32.jpg)
Building Excel Spreadsheets
![Page 33: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/33.jpg)
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
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 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
![Page 34: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/34.jpg)
Persistent Servlet State and Auto-Reloading Pages: Example
Idea: generate list of large (e.g., 150-digit) prime numbers Show partial results until completed Let new clients make use of results from others
Demonstrates use of the Refresh header.Shows how easy it is for servlets to maintain state
between requests. Very difficult in traditional CGI.
Also illustrates that servlets can handle multiple simultaneous connections Each request is in a separate thread.
![Page 35: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/35.jpg)
Finding Prime Numbers for Use with Public Key Cryptography
public class PrimeNumberServlet extends HttpServlet {
private ArrayList primeListCollection = new ArrayList();
private int maxPrimeLists = 30;
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
int numPrimes =
ServletUtilities.getIntParameter(request, "numPrimes", 50);
int numDigits = ServletUtilities.getIntParameter(request, "numDigits",
120);
PrimeList primeList = findPrimeList(primeListCollection,
numPrimes, numDigits);
![Page 36: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/36.jpg)
Finding Prime Numbers for Use with Public Key Cryptography if (primeList == null) {
primeList = new PrimeList(numPrimes, numDigits, true);
// Multiple servlet request threads share the instance variables (fields) of //PrimeNumbers. So synchronize all access to servlet fields.
synchronized(primeListCollection) {
if (primeListCollection.size() >= maxPrimeLists)
primeListCollection.remove(0);
primeListCollection.add(primeList);
} }
ArrayList currentPrimes = primeList.getPrimes();
int numCurrentPrimes = currentPrimes.size();
int numPrimesRemaining = (numPrimes - numCurrentPrimes);
boolean isLastResult = (numPrimesRemaining == 0);
if (!isLastResult) {
response.setIntHeader("Refresh", 5);
}
…
![Page 37: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/37.jpg)
Finding Prime Numbers for Use with Public Key Cryptography
![Page 38: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/38.jpg)
Finding Prime Numbers for Use with Public Key Cryptography
![Page 39: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/39.jpg)
Using Servlets to Generate JPEG Images1. 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);
}
![Page 40: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/40.jpg)
Using Servlets to Generate JPEG Images
![Page 41: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/41.jpg)
Using Servlets to Generate JPEG Images
![Page 42: HTTP Response Headers Vijayan Sugumaran Department of DIS Oakland University Parts of this presentation was provided by](https://reader035.vdocuments.us/reader035/viewer/2022062516/56649d6a5503460f94a490fc/html5/thumbnails/42.jpg)
Summary Many servlet tasks can only be accomplished through 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 Most important response headers you set directly:
Cache-Control and Pragma Content-Disposition Content-Encoding Content-Length Expires Refresh WWW-Authenticate