Core Servlets chapter 5 HTTP request headers Requesting

  • Slides: 25
Download presentation
Core Servlets chapter 5: HTTP request headers

Core Servlets chapter 5: HTTP request headers

Requesting header information • It is possible that information the servlet needs is not

Requesting header information • It is possible that information the servlet needs is not in the form data but is in the request headers, which contain Accept, Accept-Encoding, Connection, Cookie, Host, Referer and User-Agent. • The servlet needs to explicitly read these. • To read, call (String) get. Header method of HTTPServlet. Request with the name of the specific header passed in. • Always check for null on return because the header may not have been sent. • The header names are not case sensitive.

Requesting header information Some headers are used so frequently thay have their own specifically

Requesting header information Some headers are used so frequently thay have their own specifically defined methods: • get. Cookies…. Will parse and store in an array of Cookie objects • get. Auth. Type, get. Remote. User • get. Content. Length – an int • get. Content. Type returns String • get. Date. Header and get. Int. Header return Date and int values • get. Header. Names returns an Enumeration of all headers • get. Headers returns an Enumeration of all occurences of a header

The request line itself Methods in HTTPServlet. Request return information from the first line

The request line itself Methods in HTTPServlet. Request return information from the first line of the request: • get. Method …returns GET, POST, or other method • get. Request. URI returns the part of the request after the host and port number but before the form data • get. Query. String returns form data • get. Protocol returns HTTP/1. 0 or HTTP/1. 1 and should generally be checked before specifying response headers specific to HTTP/1. 1

A servlet which returns all header information • Calling get. Header. Names returns an

A servlet which returns all header information • Calling get. Header. Names returns an Enumeration of all headers. Looping through this with calls to get. Header returns values. These are used to populate a table.

A table of all request header values

A table of all request header values

From wikipedia…MIME • Multipurpose Internet Mail Extensions (MIME) is an Internet standard that extends

From wikipedia…MIME • Multipurpose Internet Mail Extensions (MIME) is an Internet standard that extends the format of e-mail to support: • text in character sets other than US-ASCII; • non-text attachments; • message bodies with multiple parts; and • header information in non-ASCII character sets. • MIME's use, however, has grown beyond describing the content of e-mail to describing content type in general.

Understanding request headers • • • • Accept -all MIME types accepted by the

Understanding request headers • • • • Accept -all MIME types accepted by the browser. . For example not all browsers support png format. Accept-Charset – what char set the broswer can use Accept-Encoding –eg. , gzip and zip Accept-Language – en, en-us, and so on Authorization – used by client for identification when accessing pw/protected pages Connection Content-length - applicable only to post requests, it gives the size of the POST data in bytes Cookie- returns cookies to servers that sent them to the browser… Don’t read this directly… instead use request. get. Cookies() Host User-Agent – The browser or client making the request. It can be used to return different content to different browsers. For example, you might send wml to a phone or html to a conventional broswer. If-Modified-since If-unmodified since Referer – provides URL of referring webpage. Tells you where a request came from, for example, tracking advertisers referring customers to your site, modifying response if the request came from within or outside your site, etc. Many broswers filter out this header (Norton, Opera)

Sending compressed data: note from the table above the browser accepts gzip format

Sending compressed data: note from the table above the browser accepts gzip format

Using gzip utilities: three static functions package coreservlets; import java. io. *; import javax.

Using gzip utilities: three static functions package coreservlets; import java. io. *; import javax. servlet. http. *; import java. util. zip. *; public class Gzip. Utilities { /** Does the client support gzip? */ public static boolean is. Gzip. Supported (Http. Servlet. Request request) { String encodings = request. get. Header("Accept-Encoding"); return((encodings != null) && (encodings. index. Of("gzip") != -1)); } /** Has user disabled gzip (e. g. , for benchmarking)? */ public static boolean is. Gzip. Disabled (Http. Servlet. Request request) { String flag = request. get. Parameter("disable. Gzip"); return((flag != null) && (!flag. equals. Ignore. Case("false"))); } /** Return gzipping Print. Writer for response. */ public static Print. Writer get. Gzip. Writer (Http. Servlet. Response response) throws IOException { return(new Print. Writer (new GZIPOutput. Stream (response. get. Output. Stream()))); }}

A servlet that generates lots of content package coreservlets; import java. io. *; import

A servlet that generates lots of content package coreservlets; import java. io. *; import javax. servlet. http. *; public class Long. Servlet extends Http. Servlet { public void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { response. set. Content. Type("text/html"); // Change the definition of "out" depending on whether or not gzip is supported. Print. Writer out; if (Gzip. Utilities. is. Gzip. Supported(request) && !Gzip. Utilities. is. Gzip. Disabled(request)) { out = Gzip. Utilities. get. Gzip. Writer(response); response. set. Header("Content-Encoding", "gzip"); } else { out = response. get. Writer(); } // Once "out" has been assigned appropriately, the rest of the page has no dependencies on the type of writer being used. String doc. Type = "<!DOCTYPE HTML PUBLIC "-//W 3 C//DTD HTML 4. 0 " + "Transitional//EN">n"; String title = "Long Page"; out. println (doc. Type + "<HTML>n" + "<HEAD><TITLE>" + title + "</TITLE></HEAD>n" + "<BODY BGCOLOR="#FDF 5 E 6">n" + "<H 1 ALIGN="CENTER">" + title + "</H 1>n"); String line = "Blah, blah, blah. " + "Yadda, yadda, yadda. "; for(int i=0; i<10000; i++) { out. println(line); } out. println("</BODY></HTML>"); out. close(); // Needed for gzip; optional otherwise. }}

Previous example • In this example, the servlet checked to see if the browser

Previous example • In this example, the servlet checked to see if the browser accepted a zipped format for content, and, if it did, it sent the page using gzip.

Checking browser type • In this as in all examples, be sure to check

Checking browser type • In this as in all examples, be sure to check that request. get. Header() is not null. • Do not use this generally, as many browsers allow you to change the value sent by user-agent. • The next example sends browser-specific insults to the user.

The servlet package coreservlets; import java. io. *; import javax. servlet. http. *; public

The servlet package coreservlets; import java. io. *; import javax. servlet. http. *; public class Browser. Insult extends Http. Servlet { public void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { response. set. Content. Type("text/html"); Print. Writer out = response. get. Writer(); String title, message; // Assume for simplicity that Netscape and IE are the only two browsers String user. Agent = request. get. Header("User-Agent"); if ((user. Agent != null) && (user. Agent. index. Of("MSIE") != -1)) { title = "Microsoft Minion"; message = "Welcome, O spineless slave to the " + "mighty empire. "; } else { title = "Hopeless Netscape Rebel"; message = "Enjoy it while you can. " + "You <I>will</I> be assimilated!"; } String doc. Type = "<!DOCTYPE HTML PUBLIC "-//W 3 C//DTD HTML 4. 0 " + "Transitional//EN">n"; out. println(doc. Type + "<HTML>n" + "<HEAD><TITLE>" + title + "</TITLE></HEAD>n" + "<BODY BGCOLOR="#FDF 5 E 6">n" + "<H 1 ALIGN=CENTER>" + title + "</H 1>n" + message + "n" + "</BODY></HTML>"); }}

Visiting URL using two different browsers

Visiting URL using two different browsers

Webclient sends no header- I added code to catch null pointer exception

Webclient sends no header- I added code to catch null pointer exception

Customizing display based on Referer • The next example checks if the header “Referer”

Customizing display based on Referer • The next example checks if the header “Referer” contains one of three strings and displays different images accordingly. • I am not sure where the images are in terms of the text. I just found my own gif files. • This would be useful if you wanted to: – use a display type similar to the sender – Wanted different display for someone visiting from outside than for someone arriving here from an internal link

3 html files – identical except name – this is JRunreferer. html <!DOCTYPE HTML

3 html files – identical except name – this is JRunreferer. html <!DOCTYPE HTML PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN"> <HTML><HEAD><TITLE>Referer Test</TITLE></HEAD> <BODY BGCOLOR="#FDF 5 E 6"> <H 1 ALIGN="CENTER">Referer Test</H 1> Click <A HREF="http: //localhost/servlet/coreservlets. Customize. Image">here</A> to visit the servlet. </BODY></HTML>

Most of the servlet public class Customize. Image extends Http. Servlet { public void

Most of the servlet public class Customize. Image extends Http. Servlet { public void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { response. set. Content. Type("text/html"); Print. Writer out = response. get. Writer(); String referer = request. get. Header("Referer"); if (referer == null) { referer = "<I>none</I>"; } String title = "Referring page: " + referer; String image. Name; if (contains(referer, "JRun")) { image. Name = "jrun-powered. gif"; } else if (contains(referer, "Resin")) { image. Name = "resin-powered. gif"; } else { image. Name = "tomcat-powered. ico"; } String image. Path = ". . /request-headers/images/" + image. Name; String doc. Type = "<!DOCTYPE HTML PUBLIC "-//W 3 C//DTD HTML 4. 0 " + "Transitional//EN">n"; out. println(doc. Type + "<HTML>n" + "<HEAD><TITLE>" + title + "</TITLE></HEAD>n" + "<BODY BGCOLOR="#FDF 5 E 6">n" + "<CENTER><H 2>" + title + "</H 2>n" + "<IMG SRC="" + image. Path + "">n" + "</CENTER></BODY></HTML>"); } private boolean contains(String main. String, String sub. String) { return(main. String. index. Of(sub. String) != -1); }}

Checking refering page

Checking refering page

Obviously I found my own images

Obviously I found my own images

Accessing the standard CGI variables • These are variables based on header information, on

Accessing the standard CGI variables • These are variables based on header information, on the socket (name and IP of the requesting host), or from server installation parameters like mapping URLs to physical paths. • Common Gateway Interface programmers (Perl, eg. ) would be familiar with these.

More remarks on CGI vars • The text suggests unless you have a CGI

More remarks on CGI vars • The text suggests unless you have a CGI background, you can skim this section, • But note you can use – get. Servlet. Context(). get. Real. Path to map a URI (the part of the URL after the host/port info) to an actual path – Request. get. Remote. Host and request. get. Remote. Address to get the name and IP of the client.

A servlet to display CGI variables

A servlet to display CGI variables

(Most of) Show. CGIVariables public void do. Get(Http. Servlet. Request request, Http. Servlet. Response

(Most of) Show. CGIVariables public void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { response. set. Content. Type("text /html"); Print. Writer out = response. get. Writer(); String[][] variables = { { "AUTH_TYPE", request. get. Auth. Type() }, { "CONTENT_LENGTH", String. value. Of(request. get. Content. Length ()) }, { "CONTENT_TYPE", request. get. Content. Type() }, { "DOCUMENT_ROOT", get. Servlet. Context(). get. Real. Path("/") }, { "PATH_INFO", request. get. Path. Info() }, { "PATH_TRANSLATED", request. get. Path. Translated() }, { "QUERY_STRING", request. get. Query. String() }, { "REMOTE_ADDR", request. get. Remote. Addr() }, { "REMOTE_HOST", request. get. Remote. Host() }, //more like this { "SERVER_PROTOCOL", request. get. Protocol() }, { "SERVER_SOFTWARE", get. Servlet. Context(). get. Server. Info() } }; String title = "Servlet Example: Showing CGI Variables"; String doc. Type = "<!DOCTYPE HTML PUBLIC "-//W 3 C//DTD HTML 4. 0 " + "Transitional//EN">n"; out. println(doc. Type + "<HTML>n" + "<HEAD><TITLE>" + title + "</TITLE></HEAD>n" + "<BODY BGCOLOR="#FDF 5 E 6">n" + "<CENTER>n" + "<H 1>" + title + "</H 1>n" + "<TABLE BORDER=1>n" + " <TR BGCOLOR="#FFAD 00">n" + " <TH>CGI Variable Name<TH>Value"); for(int i=0; i<variables. length; i++) { String var. Name = variables[i][0]; String var. Value = variables[i][1]; if (var. Value == null) var. Value = "<I>Not specified</I>"; out. println(" <TR><TD>" + var. Name + "<TD>" + var. Value); } out. println("</TABLE></CENTER></BODY></HTML>"); } }