4020 Week 4

Download as pdf or txt
Download as pdf or txt
You are on page 1of 51

The Framework of WWW

HTML
Web Designer External Applications
Authoring Non-HTTP objects
& Publisher
Tools/Editors
• JAVA Servlet
• CGI (Perl)
• ASP & ASP.NET
• Java Server Pages
• Java Applet
• JavaScript

Web Programmer
Web
Browser
Internet
Global Reach
Broad Range Web
Server
Client
End User Web Master
Why Build 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
Alternatives for Generating
Dynamic Pages
In addition to CGI, can we dynamically generate
page in other ways?
◆ Java Servlets

◆ Java Server Pages

◆ Active Server Pages (ASP)


Servlets
Two-Tier Architecture
A 2-Tier architecture contains a presentation tier and an application+data tier.

Presentation tier interacts


directly with the user.

Application+data tier
expresses data into a
HTML/XML document for
the user

Presentation tier: Application+Data tier:


HTML/XML clients Web server
Three-Tier Architecture
• In a three-tier architecture, application may be viewed as three logical modules
•Top-tier:Presentation tier on client side:
- interacts with the user directly by accepting and displaying data using a
browser (Netscape, IE etc.)
•Middle-tier: Application tier contains so called business logic
- handles requests from clients, interacts with database and services
requests
- technologies: Java servlets, ASP, JSP, CGI
•Bottom-tier: Data tier
- application data (e.g. XML, Oracle, Access)
• slow due to an additional level; resources are used efficiently, highly scalable

Application
HTML
on a Web
interface
server

Presentation tier Application tier Data tier


• 2-Tier architecture are faster but are not very scalable.

• 3-Tier architecture can be slow due to an additional level


of functionality.
- resources are used efficiently used,
- scalable and the design choice now a days.
GET and POST methods (Revisit)
• During client-server interaction, data is sent to the server primarily in two
ways: GET or POST method
* GET: data is sent as a query string
client query is completely embedded in the URL sent to the server.
The amount of query information is usually limited to 1KB. This
information is stored in the request line.
* POST: data is sent as part of the message body
data is not visible in the URL. Large amounts of data can be sent
to the server.

Server side application should handle both the methods appropriately.


Server-Side processing (Revisit)
Server interprets query and
Query (Get or Post) invokes relevant application
Web
browser Web server Application
HTML output to Output is sent to server
client

Database access
(Optional)

Applications can be interfaced with


other server programs (e.g. e-mail
server, database server)
Java Servlets

Java Servlets are server side components (Java classes) that


provides a powerful mechanism for developing server-side
applications. Servlets are responsible for generating dynamic
response as a result of any request from client.
Why User Servlets?
◆ Servlets are loaded into memory once and stay
around to handle future requests (in contrast to CGI).
◆ Provide dynamic content to HTML documents.
◆ Server-side programming is well established on the
web (HTTP protocol provides a framework for
communicating with a server).
◆ Servlets make it easier to separate the business logic
used to generate results from the HTML that
displays those results.
◆ Add-on software exists to support Servlets (for
Apache, IIS etc). Servlets now provide functionality
for multiple platforms.
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
Two Examples for Multithreading

Chrome
http://csp.ipm.edu.mo
Suppose this web page has an
embedded flash movie and a
background music. We want a
responsive browser user interface
while the flash movie and
background music are playing.
Flash movie playing …
We need three threads within the
browser process.
Background music playing

Two Examples for Multithreading

Client and Server with Threads


What Are Threads?
◆ A thread (or lightweight process) is a basic unit of computation.
➢ It uses less state and less resources than heavyweight process.
➢ Thread creation can be 10-100 times faster than process
creation
◆ In a system that supports threads, each (heavyweight) process
consist of one or more threads.
➢ A traditional process is a process with one thread.
◆ Each thread has its own
➢ thread ID, program counter, stack space and some of its own
data.
◆ O/S gives us the impression of running several processes
simultaneously.
◆ Threads extends this concept from process level to function level,
running multiple tasks within a process.
Apache Tomcat

Representation and Management


of Data on the Web

http://jakarta.apache.org/tomcat/
Tomcat

◆ Tomcat is an open source project – meaning you


can view the code behind it and modify it, at your
own risk.

◆ Tomcat is “the servlet container that is used in the


official Reference Implementation for the Java
Servlet and JavaServer Pages technologies”
What is Tomcat?

◆ Tomcat is a Web Server created by


Apache
◆ A Web server is a program that
receives HTTP requests and returns
HTTP responses
◆ Tomcat supports Servlets and JSP!
What is JSP?

◆ A Java Server Page (JSP) is a combination of


HTML or XML and java code.

◆ JSPs are a compliment to servlets, rather than a


replacement. They make it easy to separate two
kinds of Web content: static content and dynamic
content.
Installing Tomcat
◆ Create a directory for installation
(tomcat_home) /usr/local/jakarta-tomcat-4.0.6

◆ Inside the directory, type "tomcat setup"


◆ The following directories will be created:
➢ conf
➢ lib
➢ logs
➢ webapps /usr/local/jakarta-tomcat-4.0.6/webapps
◆ Tomcat is installed in our labs.
◆ Install at your home computer.
Ports and Protocols
◆ When you send something to a computer, the IP address specifies
which computer it must go to. You also need to specify which
application should receive the data. This is done with a “port
number”. A port is a software service implemented by the
Operating System.
◆ Port Numbers and Their Standard Applications:
➢ Port 80: HTTP connections
➢ Port 8080: servlet requests in Tomcat
➢ Port 20 and 21: FTP connections
➢ Port 25: SMTP (Simple Mail Transfer Protocol)
◆ The way you read or write data to a port is with a socket. In Java,
you use input and output streams on sockets just as you were
processing a file (java.net package).
◆ Servlets can be used to service any request made via a socket (not
just web page requests).
◆ Servlets can be written to respond to any protocol (not just HTTP).
Running Tomcat
◆ Go to the installation directory
◆ Use the command "tomcat start" to start the server
◆ Use the command "tomcat stop" to stop the server
◆ You get to the server by requesting on a web
browser http://<host>:port/
➢ Host is the machine on which you started tomcat
➢ Port is the port number according to the configuration
(default = 8080)

http://sit.yorku.ca:8080/jhuang
The Directory Structure of a
Web Application
◆ Web applications are located in the webapps
directory
◆ Each web application has its own subdirectory.
◆ The web application subdirectory is built in a
standard fashion
◆ Note: After creating the subdirectory you must
restart Tomcat, for tomcat to recognize it!
The Directory Structure of a
Web Application
◆ ~/jhuang: The root directory of the “jhuang” web
application. Store here HTML, Servlet and JSP files

◆ ~/jhuang/WEB-INF: All resources for the web


application that are not in the root directory. Store
here web.xml, which is not allowed to use on SIT
server!!

◆ ~/jhuang/WEB-INF/classes: Servlet and utility classes

◆ ~/jhuang/WEB-INF/lib: Utility JAR files


Directory Structure of Your Group
Accounts on Linux SIT Server
◆ All Web files are put under the “website” directory.
◆ All their applications can read and write anywhere in
their group home directories, provided that they set
Unix/Linux permissions properly.
◆ Your applications are free to connect to the DB servers.
◆ All the groups are NOT allowed to change ANY of the
port number in the config files (e.g. (1) should not
modify files named server.xml and server-minimal.xml;
(2) should not create your own web.xml file).
◆ Use “source /javainit” to start Java 1.5.
Referring to your Files in the Browser
◆ To open a page called a.htm in the ROOT
directory of the “jhuang” web application:
➢ http://<host>:<port>/jhuang/login.html
➢ http://sit.yorku.ca:8080/jhuang/login.html
➢ http://sit.yorku.ca:8080/jhuang/DrJimmyHuang.jsp
➢ https://sit.yorku.ca:8443/jhuang/DrJimmyHuang.jsp
◆ To open a servlet called HelloWorld.class of
the dbi web application
➢ http://<host>:<port>/jhuang/servlet/HelloWorld
➢ http://unix.aml.yorku.ca:8080/jhuang/servlet
http://unix.aml.yorku.ca:8080/jhuang/servlet/
Java Servlets
• Server-side components

• written in Java language; Servlet is a Java application that can be


loaded dynamically to expand the functionality of a server.
• hosted on a Web server, run in a servlet container (also called servlet
engine)
• platform and server independent; Safe and Portable
• Unlike Java applets, do not require support for Java in the Web
browser

• used to
- perform all CGI related tasks
- dynamically create HTML pages
- access databases through JDBC
- email service using JavaMail
- access distributed objects using RMI, CORBA or EJB
- many others
<FORM ACTION="http://localhost:8080/examples/servlet/servFormIntro”
METHOD="POST">

Client sends Server invokes appropriate


FORM data using GET servlet specified in ACTION
or POST method specified attribute
in METHOD attribute

Results from the servlet Servlet processing FORM data


sent back to the client using doGet or doPost

client Web server

Sending Data Using FORMS


Java Servlets
• In this module, early example programs will use servlets for handling GET/POST
methods of FORM based requests

• Servlet classes and interfaces are not part of core Java standard.
They are defined in two packages:
- javax.servlet (generic servlet package)
- javax.servlet.http
* extends generic servlet classes/interfaces for Web server to
capture HTTP communication and servlet management

• servlet software: java.sun.com/products/servlets

• servlet development and testing (Sun’s J2EE)


java.sun.com/products/download.html

• hosting servlets (also JSP, XML):


• simt.unl.ac.uk (Unix Server); simt-dev.unl.ac.uk (SIMT server)
• www.mycgiserver.com (Free server accounts available)
First Servlet Example
import java.io.*; Import these packages
import javax.servlet.*;
import javax.servlet.http.*;

// print welcome message User defined class extends HttpServlet


public class ServWelcome extends HttpServlet {
Setting MIME type to HTML
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>First Servlet Program</TITLE></HEAD>");
out.println("<BODY>");
out.println("<H1>Welcome to Servlets</H1>");
out.println("</BODY>");
out.println("</HTML>");
} Writing HTML message body
} // public class ServWelcome
Servlet interface, GenericServlet
• javax.servlet package defines Servlet interface which must be implemented for
running servlets

• javax.servlet.GenericServlet abstract class defines a platform-independent servlet

- provides servlet configuration and a basic implementation of Servlet


interface consisting of following three methods:
init : initialising servlet, allocating resources, setting up any
databases
service: abstract method servicing zero or more requests from the
client
destroy: releasing resources, cleanup

• service() method accepts two parameters to communicate with the client


- javax.servlet.ServletRequest
encapsulates client’s request using input stream Servlet interface
- javax.servlet.ServletResponse
used to respond to client using an output stream GenericServlet class
Developing HTTPServlets
•javax.servlet.http. HTTPServlet further extends GenericServlet class for HTTP
communication.

• implements service() method

i.e. when called reads the HTTP method from the


request and dispatches the request to relevant Servlet interface
handling method

GET - doGet handling method and GenericServlet class


POST - doPost handling method

HTTPServlet class
• we need to implement doGet or doPost
• default implementation returns error
doGet() and doPost() methods
• Both the methods in HTTPServlet class define only default behaviour. The
default behaviour is to send an error message as a response.

• The class implementing servlets must extend HTTPServlet class to set non-
default response to client requests

• doGet has following signature:


public void doGet(HttpServletRequest request,
HttpServletResponse response);

•“HttpServletRequest request” represents the object containing request


information from the client.
•“HttpServletResponse response” is used to send response to the client.

• doPost has identical signature


public void doPost(HttpServletRequest request,
HttpServletResponse response);

• both the methods can generate IOException and ServletException which are
thrown to the servlet engine.
First Servlet Example
import java.io.*; Import these packages
import javax.servlet.*;
import javax.servlet.http.*;

// print welcome message User defined class extends HttpServlet


public class ServWelcome extends HttpServlet {
Setting MIME type to HTML
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>First Servlet Program</TITLE></HEAD>");
out.println("<BODY>");
out.println("<H1>Welcome to Servlets</H1>");
out.println("</BODY>");
out.println("</HTML>");
} Writing HTML message body
} // public class ServWelcome
GET and POST
◆ If the method attribute on the form is GET, the form data
is appended to the path component of the action URL,
and sent in an HTTP GET request.

◆ If the method is POST, the URL is not extended: the form


data is sent in an HTTP POST request.

◆ To handle a POST request with a servlet, define the


doPost() method instead of the doGet() method.
doGet() Handle HTTP GET request.
doPost() Handle HTTP POST request.

◆ Most commonly a servlet is responsible for handling


HTTP GET/POST requests, directed at a particular URL.
response.sendRedirect(“DentalPage”); doGet( )
HttpServlet class
Request
Web Server Request

service() method in
Response Response
Servlet

Get POST
Request Get Request POST
Response Response

doGet() in doPost() in subclass


subclass
The HTML to Invoke a Servlet

◆ The most common way for a browser to invoke a


Servlet is via an HTML form in a web page. An
HTML form start with the <FORM> tag and ends
with the </FORM> tag.
Compiling and Invoking Servlets
◆ Set your CLASSPATH
➢ Servlet JAR file (e.g., install_dir/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
➢ jrun_install_dir/servers/default/default-app/
WEB-INF/classes
◆ Invoke your servlets
➢ http://host:8080/username/servlet/ServletName
➢ http://unix.aml.yorku.ca:8080/jhuang/logIn.jsp
➢ Custom URL-to-servlet mapping (via web.xml), which
is not allowed to use on AML or SIT server.
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");
}
}
Generating HTML

◆ Set the Content-Type header


➢ Use response.setContentType

◆ Output HTML
➢ Be sure to include the DOCTYPE
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>");
}
}
Handling the Client Request: Form Data
◆ Example URL at online travel agent
➢ http://host/path?user=Marty+Hall&origin=iad&dest=nrt
➢ Names (user) come from HTML author;
values (Marty+Hall) usually come from end user

◆ Parsing form (query) data in traditional CGI


➢ Read the data one way for GET requests, another way for POST
requests
➢ Chop pairs at &, then separate parameter names (left of the "=")
from parameter values (right of the "=")
➢ URL decode values (e.g., "%7E" becomes "~")
➢ Need special cases for omitted values
(param1=val1&param2=&param3=val3) and repeated params
(param1=val1&param2=val2&param1=val3)
Reading Form Data (Query Data)
◆ getParameter("name")
➢ Returns value as user entered it. I.e., 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
◆ 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
◆ getParameterNames()
➢ Returns Enumeration of request params
An HTML Form With Three,Parameters
<FORM method=”get" ACTION="/servlet/cwp.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> See next slide
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>"); }
}
Reading Three Parameters:
Result

You might also like