Session 3 - Servlet

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 108

Session 3 - Servlet

1
Agenda
• What servlets are all about
• Advantages of servlets
• What JSP is all about
• Free servlet and JSP engines
• Compiling and invoking servlets
• Servlet structure
• A few basic servlets
• Servlet lifecycle
• Initializing servlets
• Debugging servlets
2 Servlet Web Programming – IU – IT – 2010
A Servlet’s Job
• Read explicit data sent by client (form data)
• Read implicit data sent by client
(request headers)
• Generate the results
• Send the explicit data back to client (HTML)
• Send the implicit data to client
(status codes and response headers)

3 Servlet Web Programming – IU – IT – 2010


Why Build Web Pages
Dynamically?
• The Web page is based on data submitted
by the user
– E.g., results page from search engines and order-
confirmation pages at on-line stores
• The Web page is derived from data that
changes frequently
– E.g., a weather report or news headlines page
• The Web page uses information from
databases or other server-side sources
– E.g., an e-commerce site could use a servlet to build a
Web page that lists the current price and availability of
each item that is for sale.

4 Servlet Web Programming – IU – IT – 2010


The Advantages of Servlets
Over “Traditional” CGI
• Efficient
– Threads instead of OS processes, one servlet copy, persistence
• Convenient
– Lots of high-level utilities
• Powerful
– Sharing data, pooling, persistence
• Portable
– Run on virtually all operating systems and servers
• Secure
– No shell escapes, no buffer overflows
• Inexpensive
– There are plenty of free and low-cost servers.

5 Servlet Web Programming – IU – IT – 2010


Extending the Power of Servlets:
JavaServer Pages (JSP)
• Idea:
– Use regular HTML for most of page
– Mark dynamic content with special tags
– Details in second half of course
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD><TITLE>Welcome to Our Store</TITLE></HEAD>
<BODY>
<H1>Welcome to Our Store</H1>
<SMALL>Welcome,
<!-- User name is "New User" for first-time visitors -->
<%= coreservlets.Utils.getUserNameFromCookie(request) %>
To access your account settings, click
<A HREF="Account-Settings.html">here.</A></SMALL>
<P>
Regular HTML for rest of on-line store’s Web page
</BODY></HTML>
6 Servlet Web Programming – IU – IT – 2010
Server-Side Java is
Driving the Web

Get
on
board
or
get
out
of
the
way

7 Servlet Web Programming – IU – IT – 2010


Free Servlet and JSP Engines
• Apache Tomcat
– http://jakarta.apache.org/tomcat/
– See http://www.moreservlets.com/Using-Tomcat-4.html
• Allaire/Macromedia JRun
– http://www.macromedia.com/software/jrun/
• New Atlanta ServletExec
– http://www.servletexec.com/
• Gefion Software LiteWebServer
– http://www.gefionsoftware.com/LiteWebServer/
• Caucho's Resin
– http://www.caucho.com/
8 Servlet Web Programming – IU – IT – 2010
Compiling and Invoking
Servlets
• Set your CLASSPATH
– Servlet JAR file (e.g., install_dir/common/lib/servlet.jar).
– Top of your package hierarchy
• Put your servlet classes in proper location
– Locations vary from server to server. E.g.,
• tomcat_install_dir/webapps/ROOT/WEB-INF/classes
See http://www.moreservlets.com/Using-Tomcat-4.html
• jrun_install_dir/servers/default/default-app/WEB-INF/classes
• Invoke your servlets
– http://host/servlet/ServletName
– Custom URL-to-servlet mapping (via web.xml)

9 Servlet Web Programming – IU – IT – 2010


Simple Servlet Template
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ServletTemplate extends HttpServlet {


public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

// Use "request" to read incoming HTTP headers


// (e.g. cookies) and HTML form data (query data)

// Use "response" to specify the HTTP response status


// code and headers (e.g. the content type, cookies).

PrintWriter out = response.getWriter();


// Use "out" to send content to browser
}
}
10 Servlet Web Programming – IU – IT – 2010
A Simple Servlet That
Generates Plain Text
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet {


public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello World");
}
}

11 Servlet Web Programming – IU – IT – 2010


Compiling and Invoking Servlet
(Tomcat 4; Class Setup)
• Place code in C:\Servlets+JSP.
– R-click on source code at http://archive.coreservlets.com
• CLASSPATH already set
• Start DOS; type "javac HelloWorld.java"
• Place HelloWorld.class in servlet directory
– C:\jakarta-tomcat-4.0\webapps\ROOT\WEB-INF\classes
– Drag files onto shortcut in Servlets+JSP directory
• Start server
– Double click startup.bat
• Invoke servlet
– http://localhost/servlet/HelloWorld
12 Servlet Web Programming – IU – IT – 2010
Generating HTML
• Set the Content-Type header
– Use response.setContentType
• Output HTML
– Be sure to include the DOCTYPE
• Use an HTML validation service
– http://validator.w3.org/
– http://www.htmlhelp.com/tools/validator/
– If your servlets are behind a firewall, you can run them,
save the HTML output, and use a file upload form to
validate.

13 Servlet Web Programming – IU – IT – 2010


A Servlet That Generates HTML
public class HelloWWW extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n";
out.println(docType +
"<HTML>\n" +
"<HEAD><TITLE>Hello WWW</TITLE></HEAD>\n" +
"<BODY>\n" +
"<H1>Hello WWW</H1>\n" +
"</BODY></HTML>");
}
}

14 Servlet Web Programming – IU – IT – 2010


Packaging Servlets
• Move the files to a subdirectory that
matches the intended package name
– For example, I’ll use the coreservlets package for most of
the rest of the servlets in this course. So, the class files
need to go in a subdirectory called coreservlets.
• Insert a package statement in the class file
– E.g., top of HelloWWW2.java:
package coreservlets;
• Set CLASSPATH to top-level directory
– E.g., C:\Servlets+JSP.
• Include package name in URL
– http://localhost/servlet/coreservlets.HelloWWW2
15 Servlet Web Programming – IU – IT – 2010
Some Simple HTML-Building
Utilities
public class ServletUtilities {
public static final String DOCTYPE =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">";

public static String headWithTitle(String title) {


return(DOCTYPE + "\n" +
"<HTML>\n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n");
}
...
}
• Don’t go overboard
– Complete HTML generation packages
usually work poorly
– The JSP framework is a better solution
16 Servlet Web Programming – IU – IT – 2010
HelloWWW with ServletUtilities
package coreservlets;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWWW3 extends HttpServlet {


public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(ServletUtilities.headWithTitle("Hello WWW") +
"<BODY>\n" +
"<H1>Hello WWW</H1>\n" +
"</BODY></HTML>");
}
}
17 Servlet Web Programming – IU – IT – 2010
HelloWWW Result

18 Servlet Web Programming – IU – IT – 2010


The Servlet Life Cycle
• init
– Executed once when the servlet is first loaded.
Not called for each request.
• service
– Called in a new thread by server for each request.
Dispatches to doGet, doPost, etc.
Do not override this method!
• doGet, doPost, doXxx
– Handles GET, POST, etc. requests.
– Override these to provide desired behavior.
• destroy
– Called when server deletes servlet instance.
Not called after each request.
19 Servlet Web Programming – IU – IT – 2010
Why You Should
Not Override service
• You can add support for other services later
by adding doPut, doTrace, etc.
• You can add support for modification dates
by adding a getLastModified method
• The service method gives you automatic
support for:
– HEAD requests
– OPTIONS requests
– TRACE requests
• Alternative: have doPost call doGet

20 Servlet Web Programming – IU – IT – 2010


Initializing Servlets
• Common in real-life servlets
– E.g., initializing database connection pools.
• Use ServletConfig.getInitParameter to read
initialization parameters
• Set init parameters in web.xml (ver 2.2/2.3)
– …/WEB-INF/web.xml
– Many servers have custom interfaces to create web.xml
• It is common to use init even when
you don’t read init parameters
– See modification date example in
Core Servlets and JavaServer Pages Chapter 2

21 Servlet Web Programming – IU – IT – 2010


Debugging Servlets
• Use print statements; run server on desktop
• Use Apache Log4J
• Integrated debugger in IDE
• Look at the HTML source
• Return error pages to the client
– Plan ahead for missing or malformed data
• Use the log file
– log("message") or log("message", Throwable)
• Separate the request and response data .
– Request: see EchoServer at www.coreservlets.com
– Response: see WebClient at www.coreservlets.com
• Stop and restart the server
22 Servlet Web Programming – IU – IT – 2010
Web Applications: A Preview
• Learning
– Use default Web application (ROOT on Tomcat)
– Use default URLs (http://…/servlet/ServletName)
– Advantages
• Simpler
• Can test without restarting server or editing web.xml
• Deployment
– Use a custom Web application (on Tomcat, a directory in
install_dir/webapps with structure similar to ROOT)
– Register custom URLs in WEB-INF/web.xml
– Advantages
• URLs look better
• Advanced features (init params, security, filters, etc.) depend on
your using custom URLS

23 Servlet Web Programming – IU – IT – 2010


Making Custom Web Apps
1. Make a directory whose structure mirrors
the structure of the default Web
application.
• HTML (and, eventually, JSP) documents go in the top-
level directory
• The web.xml file goes in the WEB-INF subdirectory
• Servlets and other classes go either in WEB-INF/classes
or a subdirectory of WEB-INF/classes that matches the
package name.
• On Tomcat, entire directory goes in install_dir/webapps
2. Update your CLASSPATH.
• Add webAppDir/WEB-INF/classes to it.

24 Servlet Web Programming – IU – IT – 2010


Making Custom Web Apps
3. Use the directory name in the URL
• All URLs should be of the form http://host/webAppDir/

4. Use web.xml to assign custom URLs
• Use the servlet and servlet-mapping elements
<servlet>
<servlet-name>Servlet2</servlet-name>
<servlet-class>
coreservlets.HelloServlet2
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
25 Servlet Web Programming – IU – IT – 2010
Making Custom Web Apps

26 Servlet Web Programming – IU – IT – 2010


Summary
• Servlets are efficient, portable, powerful,
and widely accepted in industry
• Regardless of deployment server, run a free
server on your desktop for development
• Getting started:
– Set your CLASSPATH
• Servlet JAR file
• Top of your package hierarchy
– Put class files in proper location
• .../WEB-INF/classes
– Use proper URL, usually http://host/servlet/ServletName
• Download existing servlet first time
– Start with HelloWWW from www.coreservlets.com
27 Servlet Web Programming – IU – IT – 2010
Summary (Continued)
• Main servlet code goes in doGet or doPost:
– The HttpServletRequest contains the incoming
information
– The HttpServletResponse lets you set outgoing
information
• Call setContentType to specify MIME type
• Call getWriter to obtain a Writer pointing to client
• One-time setup code goes in init
– Servlet gets initialized and loaded once
– Servlet gets invoked multiple times
– Initialization parameters set in web.xml (covered in detail
in More Servlets & JavaServer Pages Chapter 5)
28 Servlet Web Programming – IU – IT – 2010
Handling the Client
Request: Form Data

29
Agenda
• Why form data is important
• Processing form data in traditional CGI
• Processing form data in servlets
• Reading individual request parameters
• Reading all request parameters
• Real-life servlets: handling malformed data
• Filtering HTML-specific characters

30 Servlet Web Programming – IU – IT – 2010


The Role of Form Data
• Example URL at online travel agent
– http://host/path?user=Marty+Hall&origin=bwi&dest=lax
– Names come from HTML author;
values usually come from end user
• Parsing form (query) data in traditional CGI
– Read the data one way (QUERY_STRING) for GET
requests, another way (standard input) for POST requests
– Chop pairs at ampersands, then separate parameter names
(left of the equal signs) from parameter values (right of
the equal signs)
– URL decode values (e.g., "%7E" becomes "~")
– Need special cases for omitted values
(param1=val1&param2=&param3=val3) and repeated
parameters (param1=val1&param2=val2&param1=val3)
31 Servlet Web Programming – IU – IT – 2010
Creating Form Data:
HTML Forms
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD><TITLE>A Sample Form Using GET</TITLE></HEAD>
<BODY BGCOLOR="#FDF5E6">
<H2 ALIGN="CENTER">A Sample Form Using GET</H2>

<FORM ACTION="http://localhost:8088/SomeProgram">
<CENTER>
First name:
<INPUT TYPE="TEXT" NAME="firstName" VALUE="Joe"><BR>
Last name:
<INPUT TYPE="TEXT" NAME="lastName" VALUE="Hacker"><P>
<INPUT TYPE="SUBMIT"> <!-- Press this to submit form -->
</CENTER>
</FORM>
</BODY></HTML>
• See Chapter 16 for details on forms
32 Servlet Web Programming – IU – IT – 2010
Aside: Installing HTML Files
• Tomcat
– install_dir\webapps\ROOT\Form.html or
– install_dir\webapps\ROOT\SomeDir\Form.html
• JRun
– install_dir\servers\default\default-app\Form.html or
– install_dir\servers\default\default-app\SomeDir\Form.html
• URL
– http://localhost/Form.html or
– http://localhost/SomeDir/Form.html
• Custom Web applications
– Use a different directory with the same structure as the default Web
app
– Use directory name in URL (http://host/dirName/…)
– See Chapter 4 of More Servlets & JSP for details.
33 Servlet Web Programming – IU – IT – 2010
HTML Form: Initial Result

34 Servlet Web Programming – IU – IT – 2010


HTML Form: Submission Result
(Data Sent to EchoServer)

35 Servlet Web Programming – IU – IT – 2010


Sending POST Data
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD><TITLE>A Sample Form Using POST</TITLE></HEAD>
<BODY BGCOLOR="#FDF5E6">
<H2 ALIGN="CENTER">A Sample Form Using POST</H2>

<FORM ACTION="http://localhost:8088/SomeProgram"
METHOD="POST">
<CENTER>
First name:
<INPUT TYPE="TEXT" NAME="firstName" VALUE="Joe"><BR>
Last name:
<INPUT TYPE="TEXT" NAME="lastName" VALUE="Hacker"><P>
<INPUT TYPE="SUBMIT">
</CENTER>
</FORM>

</BODY></HTML>
36 Servlet Web Programming – IU – IT – 2010
Sending POST Data

37 Servlet Web Programming – IU – IT – 2010


Reading Form Data In Servlets
• request.getParameter("name")
– Returns URL-decoded value of first occurrence of name
in query string
– Works identically for GET and POST requests
– Returns null if no such parameter is in query
• request.getParameterValues("name")
– Returns an array of the URL-decoded values of all
occurrences of name in query string
– Returns a one-element array if param not repeated
– Returns null if no such parameter is in query
• request.getParameterNames()
– Returns Enumeration of request params
38 Servlet Web Programming – IU – IT – 2010
Handling Input in Multiple
Languages
• Use server's default character set
String firstName =
request.getParameter("firstName");

• Convert from English (Latin-1) to Japanese


String firstNameWrongEncoding =
request.getParameter("firstName");
String firstName =
new String(firstNameWrongEncoding.getBytes(),
"Shift_JIS");
• Accept either English or Japanese
request.setCharacterEncoding("JISAutoDetect");
String firstName =
request.getParameter("firstName");
39 Servlet Web Programming – IU – IT – 2010
An HTML Form With Three
Parameters
<FORM ACTION="/servlet/coreservlets.ThreeParams">
First Parameter: <INPUT TYPE="TEXT" NAME="param1"><BR>
Second Parameter: <INPUT TYPE="TEXT" NAME="param2"><BR>
Third Parameter: <INPUT TYPE="TEXT" NAME="param3"><BR>
<CENTER><INPUT TYPE="SUBMIT"></CENTER>
</FORM>

40 Servlet Web Programming – IU – IT – 2010


Reading the Three Parameters
public class ThreeParams extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading Three Request Parameters";
out.println(ServletUtilities.headWithTitle(title) +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=CENTER>" + title + "</H1>\n" +
"<UL>\n" +
" <LI><B>param1</B>: "
+ request.getParameter("param1") + "\n" +
" <LI><B>param2</B>: "
+ request.getParameter("param2") + "\n" +
" <LI><B>param3</B>: "
+ request.getParameter("param3") + "\n" +
"</UL>\n" +
"</BODY></HTML>"); }}
41 Servlet Web Programming – IU – IT – 2010
Reading Three Parameters:
Result

42 Servlet Web Programming – IU – IT – 2010


Reading All Parameters
public class ShowParameters extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading All Request Parameters";
out.println(ServletUtilities.headWithTitle(title) +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=CENTER>" + title + "</H1>\n" +
"<TABLE BORDER=1 ALIGN=CENTER>\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" +
"<TH>Parameter Name<TH>Parameter Value(s)");

43 Servlet Web Programming – IU – IT – 2010


Reading All Parameters
(Continued)
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<TR><TD>" + paramName + "\n<TD>");
String[] paramValues =
request.getParameterValues(paramName);
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0)
out.println("<I>No Value</I>");
else
out.println(paramValue);

44 Servlet Web Programming – IU – IT – 2010


Reading All Parameters
(Continued)
} else {
out.println("<UL>");
for(int i=0; i<paramValues.length; i++) {
out.println("<LI>" + paramValues[i]);
}
out.println("</UL>");
}
}
out.println("</TABLE>\n</BODY></HTML>");
}

public void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

45 Servlet Web Programming – IU – IT – 2010


Result of ShowParameters
Servlet

– Note that order of parameters in Enumeration does not


match order they appeared in Web page
46 Servlet Web Programming – IU – IT – 2010
A Resumé Posting Service

Dilbert used with permission of United Syndicates Inc.

47 Servlet Web Programming – IU – IT – 2010


Posting Service: Front End
• Gathers resumé
formatting and
content
information

48 Servlet Web Programming – IU – IT – 2010


Posting Service: Back End
• Previews
result
or stores
resumé
in database

49 Servlet Web Programming – IU – IT – 2010


Point: Check for Missing Data
• Textfield was not in HTML form at all
– request.getParameter returns null
• Textfield was empty when form was
submitted
– Request.getParameter returns an empty String
• Example Check
String value = request.getParameter("someName");
if ((value != null) && (!value.equals("")) {

}

50 Servlet Web Programming – IU – IT – 2010


Posting Service: Servlet Code
private void showPreview(HttpServletRequest request,
PrintWriter out) {
String headingFont = request.getParameter("headingFont");
headingFont = replaceIfMissingOrDefault(headingFont, "");
...
String name = request.getParameter("name");
name = replaceIfMissing(name, "Lou Zer");
String title = request.getParameter("title");
title = replaceIfMissing(title, "Loser");
String languages = request.getParameter("languages");
languages = replaceIfMissing(languages, "<I>None</I>");
String languageList = makeList(languages);
String skills = request.getParameter("skills");
skills = replaceIfMissing(skills, "Not many, obviously.");
...
}
• Point: always explicitly handle
missing or malformed query data
51 Servlet Web Programming – IU – IT – 2010
Filtering Strings for HTML-
Specific Characters
• You cannot safely insert arbitrary strings
into servlet output
– < and > can cause problems anywhere
– & and " can cause problems inside of HTML attributes
• You sometimes cannot manually translate
– The string is derived from a program excerpt or another
source where it is already in some standard format
– The string is derived from HTML form data
• Failing to filter special characters from form
data makes you vulnerable to cross-site
scripting attack
– http://www.cert.org/advisories/CA-2000-02.html
– http://www.microsoft.com/technet/security/crssite.asp
52 Servlet Web Programming – IU – IT – 2010
Filtering Code
(ServletUtilities.java)
public static String filter(String input) {
StringBuffer filtered = new StringBuffer(input.length());
char c;
for(int i=0; i<input.length(); i++) {
c = input.charAt(i);
if (c == '<') {
filtered.append("&lt;");
} else if (c == '>') {
filtered.append("&gt;");
} else if (c == '"') {
filtered.append("&quot;");
} else if (c == '&') {
filtered.append("&amp;");
} else {
filtered.append(c);
}
}
return(filtered.toString());
}
53 Servlet Web Programming – IU – IT – 2010
Servlet That Fails to Filter
public class BadCodeServlet extends HttpServlet {
private String codeFragment =
"if (a<b) {\n" +
" doThis();\n" +
"} else {\n" +
" doThat();\n" +
"}\n";

public String getCodeFragment() {


return(codeFragment);
}

54 Servlet Web Programming – IU – IT – 2010


Servlet That Fails to Filter
(Continued)
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "The Java 'if' Statement";

out.println(ServletUtilities.headWithTitle(title) +
"<BODY>\n" +
"<H1>" + title + "</H1>\n" +
"<PRE>\n" +
getCodeFragment() +
"</PRE>\n" +
"Note that you <I>must</I> use curly braces\n" +
"when the 'if' or 'else' clauses contain\n" +
"more than one expression.\n" +
"</BODY></HTML>");
}
55 Servlet Web Programming – IU – IT – 2010
Servlet That Fails to Filter
(Result)

56 Servlet Web Programming – IU – IT – 2010


Servlet That Properly Filters
public class FilteredCodeServlet extends BadCodeServlet {
public String getCodeFragment() {
return(ServletUtilities.filter(super.getCodeFragment()));
}
}

57 Servlet Web Programming – IU – IT – 2010


Summary
• Query data comes from HTML forms as
URL-encoded name/value pairs
• Servlets read data by calling
request.getParameter("name")
– Results in value as entered into form, not as sent over
network. I.e. not URL-encoded.
• Always check for missing or
malformed data
– Missing: null or empty string
– Special case: query data that contains special HTML
characters
• Need to be filtered if query data will be placed into
resultant HTML page
58 Servlet Web Programming – IU – IT – 2010
Handling the Client Request:
HTTP Request Headers

59
Agenda
• Idea of HTTP request headers
• Reading request headers
from servlets
• Example: printing all headers
• Common HTTP 1.1 request headers
• Example: compressing Web pages
• Example: password-protecting Web pages

60 Servlet Web Programming – IU – IT – 2010


Handling the Client Request:
HTTP Request Headers
• Example HTTP 1.1 Request
GET /search?keywords=servlets+jsp HTTP/1.1
Accept: image/gif, image/jpg, */*
Accept-Encoding: gzip
Connection: Keep-Alive
Cookie: userID=id456578
Host: www.somebookstore.com
Referer: http://www.somebookstore.com/findbooks.html
User-Agent: Mozilla/4.7 [en] (Win98; U)

• It shouldn't take a rocket scientist to realize


that you need to understand HTTP to be
effective with servlets or JSP

61 Servlet Web Programming – IU – IT – 2010


Reading Request Headers
(Methods in HttpServletRequest)
• General
– getHeader
– getHeaders (2.2 only)
– getHeaderNames
• Specialized
– getCookies
– getAuthType and getRemoteUser
– getContentLength
– getContentType
– getDateHeader
– getIntHeader
• Related info
– getMethod, getRequestURI, getProtocol
62 Servlet Web Programming – IU – IT – 2010
Checking For Missing Headers
• HTTP 1.0
– All request headers are optional
• HTTP 1.1
– Only Host is required
• Conclusion
– Always check that request.getHeader is non-null before
trying to use it
String val = request.getHeader("some name");
if (val != null) {

}

63 Servlet Web Programming – IU – IT – 2010


Printing All Headers
public class ShowRequestHeaders extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Servlet Example: Showing Request Headers";
out.println(ServletUtilities.headWithTitle(title) +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=CENTER>" + title + "</H1>\n" +
"<B>Request Method: </B>" +
request.getMethod() + "<BR>\n" +
"<B>Request URI: </B>" +
request.getRequestURI() + "<BR>\n" +
"<B>Request Protocol: </B>" +
request.getProtocol() + "<BR><BR>\n" +

64 Servlet Web Programming – IU – IT – 2010


Printing All Headers
(Continued)
"<TABLE BORDER=1 ALIGN=CENTER>\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" +
"<TH>Header Name<TH>Header Value");
Enumeration headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String headerName = (String)headerNames.nextElement();
out.println("<TR><TD>" + headerName);
out.println(" <TD>" + request.getHeader(headerName));
}
out.println("</TABLE>\n</BODY></HTML>");
}

public void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
65 Servlet Web Programming – IU – IT – 2010
Printing All Headers:
Typical Netscape Result

66 Servlet Web Programming – IU – IT – 2010


Printing All Headers:
Typical Internet Explorer Result

67 Servlet Web Programming – IU – IT – 2010


Common HTTP 1.1 Request
Headers
• Accept
– Indicates MIME types browser can handle
– Can send different content to different clients. For
example, PNG files have good compression
characteristics but are not widely supported in browsers.
A servlet could check to see if PNG is supported, sending
<IMG SRC="picture.png" ...> if it is supported, and
<IMG SRC="picture.gif" ...> if not.
– Warning: IE incorrectly sets this header when you hit the
Refresh button. It sets it correctly on original request.
• Accept-Encoding
– Indicates encodings (e.g., gzip or compress) browser can
handle.
– See following example
68 Servlet Web Programming – IU – IT – 2010
Common HTTP 1.1 Request
Headers (Continued)
• Authorization
– User identification for password-protected pages.
– See upcoming example.
– Instead of HTTP authorization, use HTML forms to send
username/password and store info in session object. This
approach is usually preferable because standard HTTP
authorization results in a small, terse dialog box that is
unfamiliar to many users.
– Servers have high-level way to set up password-protected
pages without explicit programming in the servlets.
• For details, see Chapter 7 (Declarative Security) and
Chapter 8 (Programmatic Security) of More Servlets
and JavaServer Pages, www.moreservlets.com.
69 Servlet Web Programming – IU – IT – 2010
Common HTTP 1.1 Request
Headers (Continued)
• Connection
– In HTTP 1.0, keep-alive means browser can handle
persistent connection. In HTTP 1.1, persistent connection is
default. Persistent connections mean that the server can
reuse the same socket over again for requests very close
together from the same client (e.g., the images associated
with a page, or cells within a framed page).
– Servlets can't do this unilaterally; the best they can do is to
give the server enough info to permit persistent connections.
So, they should set Content-Length with setContentLength
(using ByteArrayOutputStream to determine length of
output). See example in book.
• Cookie
– Gives cookies previously sent to client. Use getCookies, not
getHeader. See chapter & later class session.
70 Servlet Web Programming – IU – IT – 2010
Common HTTP 1.1 Request
Headers (Continued)
• Host
– Indicates host given in original URL
– This is a required header in HTTP 1.1. This fact is
important to know if you write a custom HTTP client
(e.g., WebClient used in CSAJSP Chapter 2) or telnet to a
server and use the HTTP/1.1 version.
• If-Modified-Since
– Indicates client wants page only if it has been changed
after specified date
– Don’t handle this situation directly; implement
getLastModified instead. See example in CSAJSP
Chapter 2.

71 Servlet Web Programming – IU – IT – 2010


Common HTTP 1.1 Request
Headers (Continued)
• Referer
– URL of referring Web page
– Useful for tracking traffic; logged by many servers
– Can also be used to let users set preferences and then return to the
page they came from
– Can be easily spoofed, so don't let this header be your sole means of
deciding (for example) how much to pay sites that show your banner
ads.
– Some personal firewalls, Norton in particular, screen this out and
replace it with Weferer (and random chars as values)
• User-Agent
– String identifying the browser making the request
– Best used for identifying category of client
• Web browser vs. I-mode cell phone, etc.
– For Web applications, use other headers if possible
72

Servlet Again, can be easily spoofed. Web Programming – IU – IT – 2010
Sending Compressed
Web Pages

Dilbert used with permission of United Syndicates Inc.

73 Servlet Web Programming – IU – IT – 2010


Sending Compressed Pages:
EncodedPage.java
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
String encodings = request.getHeader("Accept-Encoding");
String encodeFlag = request.getParameter("encoding");
PrintWriter out;
String title;
if ((encodings != null) &&
(encodings.indexOf("gzip") != -1) &&
!"none".equals(encodeFlag)) {
title = "Page Encoded with GZip";
OutputStream out1 = response.getOutputStream();
out = new PrintWriter(new GZIPOutputStream(out1), false);
response.setHeader("Content-Encoding", "gzip");
} else {
title = "Unencoded Page";
out = response.getWriter();
}
74 Servlet Web Programming – IU – IT – 2010
Sending Compressed Pages:
EncodedPage.java (Continued)
out.println(ServletUtilities.headWithTitle(title) +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=CENTER>" + title + "</H1>\n");
String line = "Blah, blah, blah, blah, blah. " +
"Yadda, yadda, yadda, yadda.";
for(int i=0; i<10000; i++) {
out.println(line);
}
out.println("</BODY></HTML>");
out.close();
}

75 Servlet Web Programming – IU – IT – 2010


Sending Compressed Pages:
Results
• Uncompressed (28.8K modem),
Netscape 4.7 and Internet Explorer 5.0:
> 50 seconds
• Compressed (28.8K modem),
Netscape 4.7 and Internet Explorer 5.0:
< 5 seconds
• Caution:
be careful
about
generalizing
benchmarks

76 Servlet Web Programming – IU – IT – 2010


Restricting Access to Web
Pages
• Main approach: "declarative" security via web.xml
settings
– See More Servlets and JSP for lots of detail
• Alternative: programmatic HTTP
1 Check whether there is Authorization header. If not, go to Step 2. If so,
skip over word “basic” and reverse the base64 encoding of the remaining
part. This results in a string of the form username:password. Check the
username and password against some stored set. If it matches, return the
page. If not, go to Step 2.
2 Return a 401 (Unauthorized) response code and a header of the following
form:
WWW-Authenticate: BASIC realm="some-name"
This instructs browser to pop up a dialog box telling the user to enter a
name and password for some-name, then to reconnect with that username
and password embedded in a single base64 string inside the Authorization
header.

77 Servlet Web Programming – IU – IT – 2010


SecretServlet (Registered Name
of ProtectedPage Servlet)
public class ProtectedPage extends HttpServlet {
private Properties passwords;
private String passwordFile;

public void init(ServletConfig config)


throws ServletException {
super.init(config);
try {
passwordFile =
config.getInitParameter("passwordFile");
passwords = new Properties();
passwords.load(new FileInputStream(passwordFile));
} catch(IOException ioe) {}
}

78 Servlet Web Programming – IU – IT – 2010


SecretServlet (Continued)
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String authorization =
request.getHeader("Authorization");
if (authorization == null) {
askForPassword(response);
} else {
String userInfo =
authorization.substring(6).trim();
BASE64Decoder decoder = new BASE64Decoder();
String nameAndPassword =
new String(decoder.decodeBuffer(userInfo));
// Check name and password
79 Servlet Web Programming – IU – IT – 2010
SecretServlet (Continued)
private void askForPassword
(HttpServletResponse response) {
// SC_UNAUTHORIZED is 401
response.setStatus(response.SC_UNAUTHORIZED);
response.setHeader("WWW-Authenticate",
"BASIC realm=\"privileged-few\"");
}

80 Servlet Web Programming – IU – IT – 2010


SecretServlet In Action

81 Servlet Web Programming – IU – IT – 2010


Summary
• Many servlet tasks can only be accomplished by
making use of HTTP headers coming from the
browser
• Use request.getHeader for arbitrary header
– Remember to check for null
• Cookies, authorization info, content length, and
content type have shortcut methods
• Most important headers you read directly
– Accept
– Accept-Encoding
– Connection
– Referer
– User-Agent
82 Servlet Web Programming – IU – IT – 2010
Generating the
HTTP Response
Core Servlets & JSP book: www.coreservlets.com
More Servlets & JSP book: www.moreservlets.com
Servlet and JSP Training Courses: courses.coreservlets.com

83
Agenda
• 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

84 Servlet Web Programming – IU – IT – 2010


Generating the Server
Response: HTTP Status Codes
• Example HTTP 1.1 Response
HTTP/1.1 200 OK
Content-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
85 Servlet Web Programming – IU – IT – 2010
Setting Status Codes
• response.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.
• response.sendError(int code,
String message)
– Wraps message inside small HTML document
• response.sendRedirect(String url)
– Relative URLs permitted in 2.2 and later
– Sets Location header also

86 Servlet Web Programming – IU – IT – 2010


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.

87 Servlet Web Programming – IU – IT – 2010


Common HTTP 1.1 Status
Codes (Continued)
• 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. See example.
• 401 (Unauthorized)
– Browser tried to access password-protected page without
proper Authorization header. See example in book.
• 404 (Not Found)
– No such page. Servlets should use sendError to set this.
– Problem: Internet Explorer 5.0.
– Fun and games: http://www.plinko.net/404/
88 Servlet Web Programming – IU – IT – 2010
A Front End to Various Search
Engines: Code
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 numResults =
request.getParameter("numResults");
...
String searchEngine =
request.getParameter("searchEngine");
89 Servlet Web Programming – IU – IT – 2010
A Front End to Various Search
Engines: Code (Continued)
SearchSpec[] commonSpecs =
SearchSpec.getCommonSpecs();
for(int i=0; i<commonSpecs.length; i++) {
SearchSpec searchSpec = commonSpecs[i];
if (searchSpec.getName().equals(searchEngine)) {
String url =
searchSpec.makeURL(searchString, numResults);
response.sendRedirect(url);
return;
}
}
reportProblem(response,
"Unrecognized search engine.");

90 Servlet Web Programming – IU – IT – 2010


A Front End to Various Search
Engines: Code (Continued)

private void reportProblem(HttpServletResponse response,


String message)
throws IOException {
response.sendError(response.SC_NOT_FOUND,
message);
}

91 Servlet Web Programming – IU – IT – 2010


Front End to Search Engines:
Result of Legal Request

92 Servlet Web Programming – IU – IT – 2010


Front End to Search Engines:
Result of Illegal Request

• Fix:
Tools, Internet Options,
deselect "Show 'friendly' HTTP error messages"
Not a real fix -- doesn't help unsuspecting users of your pages
93 Servlet Web Programming – IU – IT – 2010
Generating the Server Response:
HTTP Response Headers
• Purposes
– Give forwarding location
– Specify cookies
– Supply the page modification date
– Instruct the browser to reload the page after a designated
interval
– Give the document size so that persistent HTTP
connections can be used
– Designate the type of document being generated
– Etc.

94 Servlet Web Programming – IU – IT – 2010


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.
Servlets 2.2/2.3 only.
95 Servlet Web Programming – IU – IT – 2010
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).
96 Servlet Web Programming – IU – IT – 2010
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
97 Servlet Web Programming – IU – IT – 2010
Common HTTP 1.1 Response
Headers
• Cache-Control (1.1) and Pragma (1.0)
– A no-cache value prevents browsers from caching page. Send both
headers or check HTTP version.
• Content-Encoding
– The way document is encoded. Browser reverses this encoding
before handling document. See compression example earlier.
• 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 and detailed example in book.

98 Servlet Web Programming – IU – IT – 2010


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 example in CSAJSP Chapter 2.
99 Servlet Web Programming – IU – IT – 2010
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 example in CSAJSP Section 4.5.
100 Servlet Web Programming – IU – IT – 2010
Persistent Servlet State and
Auto-Reloading Pages
• 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.

101 Servlet Web Programming – IU – IT – 2010


Generating Prime Numbers:
Source Code
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
int numPrimes =
ServletUtilities.getIntParameter(request,
"numPrimes", 50);
int numDigits =
ServletUtilities.getIntParameter(request,
"numDigits", 120);
// findPrimeList is synchronized
PrimeList primeList =
findPrimeList(primeListVector, numPrimes, numDigits);
if (primeList == null) {
primeList = new PrimeList(numPrimes, numDigits, true);

102 Servlet Web Programming – IU – IT – 2010


Generating Prime Numbers:
Source Code (Continued)
synchronized(primeListVector) {
if (primeListVector.size() >= maxPrimeLists)
primeListVector.removeElementAt(0);
primeListVector.addElement(primeList);
}
}
Vector currentPrimes = primeList.getPrimes();
int numCurrentPrimes = currentPrimes.size();
int numPrimesRemaining = (numPrimes - numCurrentPrimes);
boolean isLastResult = (numPrimesRemaining == 0);
if (!isLastResult) {
response.setHeader("Refresh", "5");
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Show List of Primes found ...

103 Servlet Web Programming – IU – IT – 2010


Prime Number Servlet:
Front End

104 Servlet Web Programming – IU – IT – 2010


Prime Number Servlet:
Initial Result

105 Servlet Web Programming – IU – IT – 2010


Prime Number Servlet:
Final Result

106 Servlet Web Programming – IU – IT – 2010


Summary
• Many servlet tasks can only be
accomplished through use of HTTP status
codes and headers sent to the browser
• Two parts of the response
– Status line
• In general, set via response.setStatus
• In special cases, set via
response.sendRedirect and response.sendError
– Response headers
• In general, set via response.setHeader
• In special cases, set via response.setContentType,
response.setContentLength, response.addCookie,
and response.sendRedirect
107 Servlet Web Programming – IU – IT – 2010
Summary (Continued)
• Most important status codes
– 200 (default)
– 302 (forwarding; set via sendRedirect)
– 401 (password needed)
– 404 (not found; set via sendError)
• Most important headers you set directly
– Cache-Control and Pragma
– Content-Encoding
– Content-Length
– Expires
– Refresh
– WWW-Authenticate
108 Servlet Web Programming – IU – IT – 2010

You might also like