84
Web Application Development

Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request: Response: HTML Code

Embed Size (px)

Citation preview

Page 1: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

Web Application DevelopmentWeb Application Development

Page 2: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

Web Architecture

browser

WebServer HTM

Ldocs

HTML

docs

Request: http://host/hello.html

Response: HTML Code

Page 3: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  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

Page 4: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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

Page 5: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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?

Page 6: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

Client/Server Architecture

ClientClient ServerServer

DiskDisk

Requests

Responses

Page 7: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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

Page 8: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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

Page 9: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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.

Page 10: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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.

Page 11: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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

Page 12: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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

Page 13: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

Collecting Data• Involves collecting some kind of data from the

user using HTML form.• Other methods:

– Java Applets– ActiveX controls– Windows Forms

Page 14: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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

Page 15: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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.

Page 16: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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.

Page 17: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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.

Page 18: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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.

Page 19: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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.

Page 20: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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”.

Page 21: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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?

Page 22: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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.

Page 23: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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.

Page 24: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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.

Page 25: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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

Page 26: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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?

Page 27: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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.

Page 28: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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

Page 29: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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

Page 30: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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.

Page 31: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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).

Page 32: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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>"); }...}

Page 33: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code
Page 34: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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

Page 35: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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

Page 36: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

Servlet Classes & Interfaces

Page 37: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

Servlet Life cycle

Page 38: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

Life Cycle Methods

Page 39: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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

Page 40: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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();

}}

Page 41: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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;

}}

Page 42: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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)

Page 43: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

Service() method

Page 44: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

doGet() and doPost()

Page 45: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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.

Page 46: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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>");}

}

Page 47: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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

Page 48: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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>");

}}

Page 49: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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

Page 50: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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

Page 51: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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

Page 52: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

Web Context(ServletContext)

Page 53: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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

Page 54: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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

Page 55: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

ServletContext:Web Application Scope

Page 56: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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

Page 57: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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>");

Page 58: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

//Get the dispatcher; it gets the banner to the userServletContext ctx = getServletContext();RequestDispatcher dispatcher =

ctx.getRequestDispatcher("/banner");if (dispatcher != null){

dispatcher.include(request, response);...

Page 59: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

Example: Loggingpublic void doGet(HttpServletRequest request,

HttpServletResponse response)throws ServletException, IOException {

...getServletContext().log(“Life is good!”);...getServletContext().log(“Life is bad!”,

someException);

Page 60: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

Session

(HttpSession)

Page 61: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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

Page 62: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

How to Get HttpSession?• via getSession() method of a Request object

(HttpRequest)

Page 63: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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();

Page 64: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

Servlet Request(HttpServletRequest)

Page 65: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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)

Page 66: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

Requests

Page 67: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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

Page 68: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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>

Page 69: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

A Sample FORM

Page 70: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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>");

}}

Page 71: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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

Page 72: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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"

Page 73: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

HTTP Request URL• Contains the following parts

http://[host]:[port]/[request path]?[query string]

Page 74: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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

Page 75: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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”)

Page 76: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

Context, Path, Query,Parameter Methods• String getContextPath()• String getQueryString()• String getPathInfo()• String getPathTranslated()

Page 77: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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)

Page 78: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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

Page 79: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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.

Page 80: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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.

Page 81: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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

Page 82: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

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));

} }}

Page 83: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code
Page 84: Web Application Development. Web Architecture browse r Web Server HTM L docs HTM L docs Request:  Response: HTML Code

Thank You!