Upload
hayden-bradley
View
223
Download
0
Tags:
Embed Size (px)
Citation preview
Web Application DevelopmentWeb Application Development
Web Architecture
browser
WebServer HTM
Ldocs
HTML
docs
Request: http://host/hello.html
Response: HTML Code
Web Browser• Universal user interface presenting web content
– Internet Explorer– Netscape Communicator
• Scripting languages like VBScript or JavaScript can be used to perform client-side data validation.
• Provide some interactivity within the document.• DHTML is a combination of HTML, Cascading Style
Sheets, the document object model (DOM), and scripting languages.
• Other client-side technologies:– ActiveX – Java Applets
Web Server• The heart of any web interaction.• A program running on the server that listens for
incoming requests and service those requests.• Look for a web page or might execute a program
on the server side.• Leading web servers today are:
– Apache– Microsoft-IIS– Netscape-Enterprise– Rapidsite– Httpd– webStar
N-Tier Applications• Typical client/server systems have fallen into the
category of a two-tiered architecture.– A way of designing an application in which clients
contact well-known servers to access resources.
• The WWW as a client-server application– Client?– Server?– Contact?– Well-known?– Resources?– Access?
Client/Server Architecture
ClientClient ServerServer
DiskDisk
Requests
Responses
Two-Tiered Application• Processing load is given to the PC while the
more powerful server simply acts as a traffic controller between the application and the database.
• Disadvantages:– Application performance suffers due to:
• limited resources of the PC• Network traffic tends to increase as well
– Maintenance
• Solution?– Three-tiered Architecture
Three-tiered Architecture• Application is broken up into three separate
logical layers, each with a well-defined set of interfaces.– Presentation tier – typically consists of a graphical
user interface of some kind.– Middle tier – consists of the application logic and– Storage tier – contains the data that is needed for the
application
• Issues Addressed– Performance, network traffic, and maintenance
n-tier Architecture• Three-tier architecture lacks reusability and
scalability.• Extend the middle tier by allowing for multiple
application objects rather than just a single application.
• Each object must have an interface which allows them to work together.
• The interface can be thought of as a contract.
Web Application Architecture• Typically follow a three-tier architecture model.
– Presentation layer – includes not only web browser but web server.
• Responsible for assembling the data into presentable format.
– Application layer – Consists of some sort of script or program
– Third layer – provides the second tier with the data that it needs.
3-tier Architecture
Browser
WebServer
Request: http://host/hello.html
Response: HTML Code
Run-time Env.
Script or Program
Data Store
1st Tier
2nd Tier
3rd Tier
Web Application Roundtrip• Typical web application:
– collects data from the user (first tier), – sends the request to the web server, – run the requested server program (second and third
tiers), – package up the data to be presented in the web
browser, and – send it back to the browser for display
Collecting Data• Involves collecting some kind of data from the
user using HTML form.• Other methods:
– Java Applets– ActiveX controls– Windows Forms
Sending a Request• The web browser packages up user data and
issues an HTTP request to the web server to execute a server program.
• An HTTP request consists of URL for the page or script, form data, and any additional header information.
• Each request must specify which method the request is to use.
• Common methods are GET and POST
GET Method• All of the form data that has been entered is appended to the
request string using key=value pairs. For example:http://www.anyserver.com/cgi-bin/hello.cgi?name=iffee
http://www.anyserver.com – the web server to process the request
/cgi-bin/hello.cgi – name and location of the server resource
? – separates the location from data
Key=value – field names and associated values
& - separates key=value pairs
+ - replaces the space characters
• Get method is used as default method for all web requests.
GET Method• Problems?
– All of the form data packaged with request string, if some previous results for the exact same request URL exist in browser cache, then older results might be displayed.
– Amount of data that can be passed is limited.
POST Method• Package up the form data as request body.• The server program will be able to read the
contents of the input and parse out the variable names and values.
• Allows more data that can be passed and it will always send the request to the server.
Which Method Should Use?• GET request should be used to retrieve
information.• POST request should be used if the request will
actually modify the contents of a data store on the server.
• A simple database search that returns a set of results should use a GET request.
Executing the Server Script• A web server passes a request to a specific
script, or program, to be processed.• The web server first determines which type of
operating environment it needs to load.– This is done through mapping.
• Loads any required runtime environment.• Forward the request to the loaded environment.
Returning the results • Final step in a web application is to make some
kind of response to the operation and return that to browser.
• The server script specifies the content type and then writes the response to an output stream.
• The browser first look at the response header and determine the mime type to render the data.– Most common content type is “text/html”.
Why Programmability?• What’s the drawback to the simple document
model?– Static– Assumes documents created before they are
requested.
• What are examples of information that might be part of web documents that may not be known before they are requested?
Developing Server Application
• To make a program accessible to a web server, it must possess the following characteristics:– When a user issues a request from web browser, the
web server has to be able to execute the requested program.
– There must be a way in which the web server passes any form data to program.
– Once the program is invoked, there has to be a standard entry point.
– After the program has processed the input data, it has to package up the results and send them back to the web server which will, in turn, send them back to the web browser.
Server-Side Technologies• A few years back only solution was Common
Gateway Interface.• Propriety APIs by Microsoft and Netscape
(ISAPIs, NSAPIs)• Latest technologies being offered are Active
Server Pages, Java Servlets and Java Server Pages, PHP, ASP.NET, Cold Fusion, etc.
Common Gateway Interface CGI
• Simple way to create web application that accepts user inputs, queries a database, and returns some results back to the browser.
• URL (the request) determines the name of a program to run.
• CGI provides a way to specify a set of parameters to give the program.
• Every web server in extension provides support for CGI programs.
• A gateway between the user request and the data it requires.
• Can be written in just about any language. Most popular is Perl.
How CGI Works• Creates a new process in which the program will be run.• Load any required runtime environments as well as the
program itself.• Finally it will pass in a request object and invoke the
program.• When the program is finished, the server will read the
response from stdout.
CGI Based Web Server
CGI Based Web Server
Process for CGI 1Process for CGI 1
Process for CGI 2Process for CGI 2
Process for CGI 1Process for CGI 1
CGI request 1
CGI request 2
CGI request 1
Disadvantages Of CGI• Does not scale well.• Each time a request is received by the web
server, an entire new process is created.• Each process consists of its own set of
environment variables, a separate instance of runtime environment is required, a copy of the program, and an allocation of memory for the program to use.
• What might happen when a large number of requests are received immediately?
Java Servlets• A server side-program that services HTTP
requests and returns results as HTTP response.• A Java version of CGI.• Can take advantage of any/all other Java
packages and features.• Java objects which are based on servlet
framework and APIs and extend the functionality of the web server.
• Mapped to URLs and managed by container with a simple architecture.
CGI vs. Servlet
• Written in C/C++, Visual basic, and Perl.
• Difficult to maintain, non-manageable, and non-scalable.
• Prone to security problem of the programming language.
• Resource intensive and inefficient.
• Platform and application specific.
• Written in Java.• Powerful, reliable, and
efficient.• Improves scalability,
reusability (component based).
• Build-in security of java language.
• Platform independent and portable.
CGICGI ServletServlet
CGI vs. Servlet
CGI Based Web Server
CGI Based Web Server
Process for CGI 1Process for CGI 1
Process for CGI 2Process for CGI 2
Process for CGI 1Process for CGI 1
CGI request 1
CGI request 2
CGI request 1
Servlet-based Web ServerServlet-based Web Server
Servlet 1Servlet 1
Servlet 2Servlet 2
Servlet request 1
Servlet request 2
Servlet request 1JVMJVM
Java Servlets• A server side-program that services HTTP
requests and returns results as HTTP response.• A Java version of CGI.• Can take advantage of any/all other Java
packages and features.• Java objects which are based on servlet
framework and APIs and extend the functionality of the web server.
• Mapped to URLs and managed by container with a simple architecture.
A Servlet’s Job• Read explicit data sent by the client.• Read implicit data sent by the client (request
header).• Generate the results.• Send the explicit data back to the client (html).• Send implicit data to the client (status code and
response header).
HelloServletpublic class HelloServlet extends
HttpServlet {public void doGet( HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(
"<title>HelloWorld!</title>"); }...}
What does Servlet Do?• Receives client request (mostly in the form of
HTTP request)• Extract some information from the request• Do content generation or business logic process
(possibly by accessing database, invoking EJBs, etc)
• Create and send response to client (mostly in the form of HTTP response) or forward the request to another servlet
Request & Responses• What is a request?
– Information that is sent from client to a server• Who made the request• What user-entered data is sent• Which HTTP headers are sent
• What is a response?– Information that is sent to client from a server
• Text(html, plain) or binary(image) data• HTTP headers, cookies, etc
Servlet Classes & Interfaces
Servlet Life cycle
Life Cycle Methods
Life cycle Methods• Invoked by container
– Container controls life cycle of a servlet
• Defined in– javax.servlet.GenericServlet class or
• init(): Invoked once when the servlet is first instantiated• destroy(): Invoked before servlet instance is removed• service() - this is an abstract method
– javax.servlet.http.HttpServlet class• doGet(), doPost(), doXxx()• service() - implementation
Life cycle methods: init()public void init() throws ServletException {
String driver = getInitParameter("driver"); String fURL = getInitParameter("url");
try { openDBConnection(driver, fURL);
} catch (SQLException e) { e.printStackTrace();
} catch (ClassNotFoundException e){ e.printStackTrace();
}}
Life cycle methods: init()public void init(ServletConfig config) throws
ServletException {
super.init(config);String driver =
getInitParameter("driver");String fURL = getInitParameter("url");try {
openDBConnection(driver, fURL);} catch (SQLException e) {
e.printStackTrace();} catch (ClassNotFoundException e){
e.printStackTrace();}
public void destroy() {bookDB = null;
}}
service() & doGet()/doPost()• service() methods take generic requests and
responses:service(ServletRequest request,
ServletResponse response)
• doGet() and doPost() take HTTP requests and responses:
doGet(HttpServletRequest request, HttpServletResponse response)
doPost(HttpServletRequest request, HttpServletResponse response)
Service() method
doGet() and doPost()
doGet() & doPost()• Extract client-sent information (HTTP parameter)
from HTTP request• Set (save) and get (read) attributes to/from
scope objects.• Perform some business logic or access
database.• Optionally forward the request to other Web
components (Servlet or JSP).• Populate HTTP response message and send it
to client.
Example: doGet()import javax.servlet.*;import javax.servlet.http.*;import java.io.*;public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Just send back a simple HTTP response response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<title>First Servlet</title>"); out.println(
"<big>Hello J2EE Programmers! </big>");}
}
Steps of Populating HTTP Response• Fill Response headers• Set some properties of the response
– Buffer size
• Retrieve an output stream from the response• Write body content to the output stream
Example: Simple Responsepublic class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Fill response headersresponse.setContentType("text/html");
// Set buffer sizeresponse.setBufferSize(8192);
// Retrieve an output stream from the responsePrintWriter out = response.getWriter();
// Write body content to output streamout.println("<title>First Servlet</title>");out.println("<big>Hello Servlet Programmers! </big>");
}}
Scope Objects
• Enables sharing information among collaborating web components via attributes maintained in Scope objects
• Attributes of Scope objects are accessed with– getAttribute()– setAttribute()
• 4 Scope objects are defined– Web context, session, request, page
Four Scope Objects: Accessibility
• Web context (ServletConext)– Accessible from Web components within a Web
context
• Session– Accessible from Web components handling a request
that belongs to the session
• Request– Accessible from Web components handling the
request
• Page– Accessible from JSP page that creates the object
Four Scope Objects: Class
• Web context– javax.servlet.ServletContext
• Session– javax.servlet.http.HttpSession
• Request– subtype of javax.servlet.ServletRequest:
• javax.servlet.HttpServletRequest
• Page– javax.servlet.jsp.PageContext
Web Context(ServletContext)
What is ServletContext For?
• Used by servets to– Set and get context-wide object-valued attributes– Get request dispatcher
• To forward to or include web component
– Access Web context-wide initialization parameters set in the web.xml file
– Access Web resources associated with the Web– context– Log– Access other misc. information
Scope of ServletContext• Context-wide scope
– Shared by all servlets and JSP pages within a "web application"
• Why it is called “web application scope”– A "web application" is a collection of servlets and
content installed under a specific subset of the server's URL namespace and possibly installed via a *.war file
• All servlets in BookStore web application share same ServletContext object– There is one ServletContext object per "web
application" per JVM
ServletContext:Web Application Scope
How to AccessServletContext Object?• Within your servlet code, call getServletContext()• Example
public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException {
ServletContext ctx = getServletContext();String attr1 = ctx.getAttribute(“bookDB”);if (bookDB == null) throw new UnavailableException(
"Couldn't get database.");
}• The ServletContext is contained in ServletConfig object, which
the Web server provides to a servlet when the servlet is initialized– init (ServletConfig servletConfig) in Servlet interface
Getting and UsingRequestDispatcher Objectspublic void doGet (HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException {
HttpSession session = request.getSession(true);ResourceBundle messages =
(ResourceBundle) session.getAttribute("messages");
//set headers and buffer size before accessing the Writerresponse.setContentType("text/html");response.setBufferSize(8192);PrintWriter out = response.getWriter();
// then write the responseout.println("<html>" + "<head><title>" + messages.getString("TitleBookDescription") + "</title></head>");
//Get the dispatcher; it gets the banner to the userServletContext ctx = getServletContext();RequestDispatcher dispatcher =
ctx.getRequestDispatcher("/banner");if (dispatcher != null){
dispatcher.include(request, response);...
Example: Loggingpublic void doGet(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException {
...getServletContext().log(“Life is good!”);...getServletContext().log(“Life is bad!”,
someException);
Session
(HttpSession)
Why HttpSession?• Need a mechanism to maintain client state
across a series of requests from a same user (or originating from the same browser) over some period of time– Example: Online shopping cart
• Yet, HTTP is stateless• HttpSession maintains client state
– Used by Servlets to set and get the values of session scope attributes
How to Get HttpSession?• via getSession() method of a Request object
(HttpRequest)
Example: HttpSessionpublic class CashierServlet extends HttpServlet {
public void doGet (HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
// Get the user's session and shopping cartHttpSession session = request.getSession();ShoppingCart cart =(ShoppingCart)session.getAttribute("cart");...// Determine the total price of the user's booksdouble total = cart.getTotal();
Servlet Request(HttpServletRequest)
What is Servlet Request?• Contains data passed from client to servlet• All servlet requests implement ServletRequest
interface which defines methods for accessing– Client sent parameters– Object-valued attributes– Locales– Client and server– Input stream– Protocol information– Content type– If request is made over secure channel (HTTPS)
Requests
Getting Client Sent Parameters
• A request can come with any number of parameters
• Parameters are sent from HTML forms:– GET: as a query string, appended to a URL– POST: as encoded POST data, not appeared in the
URL
• getParameter("paraName")– Returns the value of paraName– Returns null if no such parameter is present– Works identically for GET and POST requests
A Sample FORM<HTML><HEAD><TITLE>Collecting Three Parameters</TITLE></HEAD><BODY BGCOLOR="#FDF5E6"><CENTER>
<FORM ACTION="/sample/servlet/ThreeParams“ METHOD=POST><TABLE>
<TR><TD COLSPAN=2>Please Enter Your Information</TR><TR><TD>First Name <TD><INPUT TYPE="TEXT" NAME="param1"></TR><TR><TD>Last Name <TD><INPUT TYPE="TEXT" NAME="param2"> </TR><TR><TD>Class Name <TD><INPUT TYPE="TEXT" NAME="param3"></TR><TR><TD COLSPAN=2 ALIGN=CENTER>
<INPUT TYPE="SUBMIT" VALUE="Save"></TR> </TABLE>
</FORM></CENTER></BODY></HTML>
A Sample FORM
A FORM Based Servletimport javax.servlet.*;Import javax.servlet.http.*;public class ThreeParams extends HttpServlet {
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException {
response.setContentType("text/html");PrintWriter out = response.getWriter();
String title = "Your Information";out.println("<HTML><BODY BGCOLOR=#CCCCCC><H1 ALIGN=CENTER>" +
title + "</H1><UL>\n" +" <LI><B>First Name in Response</B>: “ +request.getParameter("param1") + "\n" +" <LI><B>Last Name in Response</B>: “ +request.getParameter("param2") + "\n" +" <LI><B>Nick Name in Response</B>: “ + request.getParameter("param3") + "\n" +"</UL></BODY></HTML>");
}}
Getting Client Information
• Servlet can get client information from the request– String request.getRemoteAddr()
• Get client's IP address
– String request.getRemoteHost()• Get client's host name
Getting Server Information
• Servlet can get server's information:– String request.getServerName()
• e.g. "www.sun.com"
– int request.getServerPort()• e.g. Port number "8080"
HTTP Request URL• Contains the following parts
http://[host]:[port]/[request path]?[query string]
HTTP Request URL: [request path]
• [request path] is made of– Context: /<context of web app>– Servlet name: /<component alias>– Path information: the rest of it
• Examples– http://localhost/hello1/greeting– http://localhost/hello1/greeting.jsp
HTTP Request URL: [query string]• [query string] are composed of a set of
parameters and values that are user entered• Two ways query strings are generated
– It can explicitly appear in a web page• <a href="/bookstore1/catalog?Add=101">Add To Cart</a>
• String bookId =
request.getParameter("Add");– appended to a URL when a form with a GET HTTP
method is submitted• http://localhost/hello1/greeting?username=Monica+Clinton
• String userName =request.getParameter(“username”)
Context, Path, Query,Parameter Methods• String getContextPath()• String getQueryString()• String getPathInfo()• String getPathTranslated()
HTTP Request Headers• HTTP requests include headers which provide
extra information about the request• Example of 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.sun.com– Referer: http:/www.sun.com/codecamp.html– User-Agent: Mozilla/ 4.7 [en] (Win98; U)
HTTP Request Headers• Accept
– Indicates MIME types browser can handle.
• Accept-Encoding– Indicates encoding (e. g., gzip or compress) browser
can handle
• Authorization– User identification for password- protected pages– Instead of HTTP authorization, use HTML forms to
send username/password and store info in session object
HTTP Request Headers• Connection
– In HTTP 1.1, persistent connection is default– Servlets should set Content-Length with
setContentLength (use ByteArrayOutputStream to determine length of output) to support persistent connections.
• Cookie– Gives cookies sent to client by server sometime
earlier. Use getCookies, not getHeader
• Host– Indicates host given in original URL.– This is required in HTTP 1.1.
HTTP Request Headers• 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.
• Referer– URL of referring Web page.– Useful for tracking traffic; logged by many servers.
• User-Agent– String identifying the browser making the request.
HTTP Header Methods• String getHeader(String name)
– value of the specified request header as String
• Enumeration getHeaders(String name)– values of the specified request header
• Enumeration getHeaderNames()– names of request headers
• int getIntHeader(String name)– value of the specified request header as an int
Showing Request Headerspublic class ShowRequestHeaders extends HttpServlet { public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException {
response.setContentType("text/html");PrintWriter out = response.getWriter();String title = "Showing Request Headers";out.println("<HTML>” +“<B>Request Method:</B>” + request.getMethod() + "<BR>" +"<B>Request URI:</B>" + request.getRequestURI() + "<BR>\n" +"<B>Request Protocol: </B>" + request.getProtocol() + "<BR><BR>" +"<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));
} }}
Thank You!