Notes
Outline
Programming Web Applications
CGI
Servlets
JSP
What do these have in common?
They are all server-side technologies!
CGI
What is CGI
How does it work?
Environment variables
Processing Forms
GET vs. POST
Examples
What is CGI?
Stands for “Common Gateway Interface”
Server-side technology
Can be used:
Process fill-out forms
To generate dynamic contents
By a web server to run external programs
By a web server to get/send data from databases and other apps
How does it work?
CGI
CGI scripts can be written in any language, including Java
Perl is the most popular for CGI scripting
To experiment, you need a web server:
Xitami (www.xitami.com)
Jakarta-Tomcat (jakarta.apache.org/tomcat)
Tomcat is nice for Servlets/JSP
Content headers
If your script generates HTML then use:
Content-type: text/html\n\n
This tells the browser what content it is about to receive
Other content headers include:
text/plain
image/gif
image/jpg
Sample Script
#!/usr/bin/perl
print "Content-type:text/html\n\n";
print "<html><head><title>Test Page</title></head>\n";
print "<body>\n"; print "<h2>Hello, world!</h2>\n";
print "</body></html>\n";
Environment Variables
Some of the environment variables:
DOCUMENT_ROOT
HTTP_HOST
HTTP_USER_AGENT
REMOTE_HOST
REQUEST_METHOD
QUERY_STRING
CONTENT_LENGTH …etc
Script: environment variables
#!/usr/bin/perl
print "Content-type:text/html\n\n";
print <<EndOfHTML;
<html><head><title>Print Environment</title></head> <body>
EndOfHTML
foreach $key (sort(keys %ENV)) {
    print "$key = $ENV{$key}<br>\n";
}
print "</body></html>";
Forms
<form action="env.cgi" method="GET">
Enter some text here: <input type="text" name="sample_text" size=30><input type="submit"><p>
</form>
Forms
There are two ways to send data from an HTML form to a CGI script
GET
POST
These methods determine how the form data is sent to the server
GET
The input values from the form are sent as part of the URL
They are saved in the QUERY_STRING environment variable
If in the above example you type:
    “hello there John”
The QUERY_STRING will be:
Sample_text=hello+there+John
Spaces have been replaced with +
GET….
This is called URL Encoding!
Some commonly encoded characters
\t (tab) %09
\n (return) %0A
/ %2F
~ %7E
: %3A
; %3B
@ %40
& %26
GET….
<form action="env.cgi" method="GET">
First Name: <input type="text" name="fname“ size=30><p>
Last Name: <input type="text" name="lname" size=30><p>
<input type="submit"> </form>
If input is: Sarah Johnson
$ENV{‘QUERY_STRING’} would be: fname=Sarah&lname=Johnson
GET….
Parsing:
@values = split(/&/,$ENV{'QUERY_STRING'});
 foreach $i (@values) {
   ($varname, $mydata) = split(/=/,$i);
   print "$varname = $mydata\n";
}
GET….
It is possible to send values as part of a URL (more on this in class)
Source: www.javacourses.com/106/marks.html
POST
More sophisticated than GET
Data is not sent as URL-encoded (I.e. not part of the URL)
When POST is used, data is sent as a separate message (input stream)
POST….
Parsing:
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
 @pairs = split(/&/, $buffer);
foreach $pair (@pairs) {
    ($name, $value) = split(/=/, $pair);
   $value =~ tr/+/ /;
   $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
   $FORM{$name} = $value;
}
Servlets
What is a servlet?
Servlets vs. CGI scripts
How do they work?
Example
What is a Servlet?
A server-side technology
Designed to overcome some limitations of existing technologies (e.g. CGI is stateless)
Characteristics:
A light-weight task that can be executed as a thread
 A servlet can remain in memory (a CGI script terminates when it finished)
Advantages:
A servlet can service multiple client requests
Can handle multiple clients without reloading/reinitialization
Servlets….
Servlets are written in Java
Can be used to:
 Generate dynamic contents
Talk to databases
Work with cookies
Session management
How do they work?
Servlet Framework
The package: javax.servlet
At the top level there are three interfaces:
ServletConfig, Servlet, Serializable
The servlet interface:
   init()
   service()
   destroy()
   getServiceConfig()
   getServiceInfo()
The GenericServlet
It is an abstract class that implements Servlet
public abstract GenericServlet implements Servlet, ServletConfig, Serializable {
  void init()
  abstract void service()
  void destroy()
  ServletConfig getServletConfig()
  String getServiceInfo()
  void log()
}
The HttpServlet
It is an abstract class that extends the GenericServlet abstract class
It provides a convenient framework for handling the HTTP protocol
These two classes (GenericServlet and HttpServlet) ease the task of writing servlets
In the simplest case, you need to provide implementation for service()
Life cycle of a servlet
Servlet is loaded into memory by server: init()
Servlet processes client requests: service()
Servlet is remove by server: destroy()
service() is responsible for handling incoming client requests
public void service(ServiceRequest request, ServletResponse response) throws ServletException, IOException
Delegates HTTP requests: doGet() & doPost()
Retrieving Parameters
Use:
public String getParameter(String name)
public String[] getParameterValues(String name)
So if you have a parameter name “username” in a form then to retrieve the value use:
String name = request.getParameter(“username”);
Example:
Consider the following form:
<form action="RequestParamExample" method=POST>
First Name: <input type=text size=20 name=firstname>
<br>
Last Name: <input type=text size=20 name=lastname>
<br>
<input type=submit>
</form>
Example….
In a browser, this would look like:
When “Submit Query” is clicked we have the output:
First Name := Qusay
Last Name := Mahmoud
Example
The servlet:
public class RequestParams extends HttpServlet {
   public doPost(HttpServletRequest re, HttpServletResponse response) {
        PrintWriter out = response.getWriter();
        out.println("<html><body><head><title>test</title></head");
        out.println("<body>");
        String firstName = req.getParameter("firstname");
        String lastName = req.getParameter("lastname");
        out.println("First Name := " + firstName + "<br>");
        out.println("Last Name := " + lastName);
        out.println("</body></html>");
} }
Servlets for WAP
It is possible to use Servlets to generate WML
PrintWriter out = response.getWriter();
out.println("<?xml version=\"1.0\"?>");
out.println("<!DOCTYPE wml …etc");
out.println("<wml>");
out.println("<card title=\"MobileDate\">");
out.println(" <p align=\"center\">");
out.println("Date and Time Service<br/>");
out.println("Date is: "+ new java.util.Date());
…etc
What else?
Programming cookies and keeping track of sessions is easy with Servlets….APIs provided for this
Explore Cookies and Session Management on your own!
Something to think about: handheld devices do not support cookies, so how do you keep track of sessions??
JSP
Server-side technology
Enables you to embed Java code within an HTML document
JSP documents have the extension .jsp
When an HTTP request is received, the compilation engine converts the JSP document into a Java Servlet then the servlet will be loaded
Java code is embedded between <% and %>
Example
// file: hello.jsp
<html><head><title>example</title></head>
<body>
<% String visitor = request.getParameter(“user”);
    if (visitor == null) visitor = “there”;
%>
Hello, <%= visitor %>!
</body>
</html>
Example
Request parameters are passed into JSP pages using normal HTTP parameter mechanisms (using GET and POST)
Therefore, for the hello.jsp:
If invoked with: http://host…/hello.jsp it will print “Hello, World!”
If invoked with: http://host…/hello.jsp?user=Mary, it will print: “Hello, Mary!”
JSP for WAP
<?xml version…>
<!DOCTYPE…etc>
<% response.setContentTyp("text/vnd.wap.wml")
%>
<wml> <card title="MobileDate"
Date and Time Service<br/>
Date is: <%= new java.util.Date() %>
</card>
</wml>
Or you can use the PAGE directive…
What else?
Additional characters may appear after the initial <%, such as !, =, or @ to further prescribe the meaning of the tag
<%! Double radius = 3.5; %>
<%= 2 * Math.PI * radius %>
<%@ include file=“notice.html” %>
It is possible to create re-usable components with JSP using Java Beans
Explore on your own!
HTTP Servers
If you don’t have access to an HTTP server, I’d recommend that you install Jakarta-Tomcat for your personal use ….so you explore Servlets and JSP further….
http://jakarta.apache.org/tomcat