Presentation is loading. Please wait.

Presentation is loading. Please wait.

Web Application Development

Similar presentations

Presentation on theme: "Web Application Development"— Presentation transcript:

1 Web Application Development

2 Web Architecture Web Server HTML docs browser
Request: Web Server Response: HTML Code HTML docs

3 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

4 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

5 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?

6 Client/Server Architecture
Requests Disk Responses

7 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

8 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

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

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

11 3-tier Architecture Data Store Web Server Run-time Env. 2nd Tier
Request: Run-time Env. Browser 2nd Tier Script or Program Response: HTML Code Data Store 3rd Tier 1st Tier

12 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

13 Collecting Data Involves collecting some kind of data from the user using HTML form. Other methods: Java Applets ActiveX controls Windows Forms

14 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

15 GET Method All of the form data that has been entered is appended to the request string using key=value pairs. For example: – 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.

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

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

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

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

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

21 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?

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

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

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

25 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 request 1 CGI Based Web Server Process for CGI 1 CGI request 2 Process for CGI 2 CGI request 1 Process for CGI 1

26 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?

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

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

29 Servlet-based Web Server
CGI vs. Servlet CGI request 1 CGI Based Web Server Process for CGI 1 CGI request 2 Process for CGI 2 CGI request 1 Process for CGI 1 Servlet request 1 Servlet-based Web Server Servlet request 2 JVM Servlet 1 Servlet request 1 Servlet 2

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

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

32 HelloServlet public class HelloServlet extends HttpServlet {
public void doGet( HttpServletRequest request, HttpServletResponse response) { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println( "<title>HelloWorld!</title>"); } ...


34 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

35 Request & Responses What is a request? What is a response?
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

36 Servlet Classes & Interfaces

37 Servlet Life cycle

38 Life Cycle Methods

39 Life cycle Methods Invoked by container Defined in
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

40 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){ }

41 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){ } public void destroy() { bookDB = null;

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

43 Service() method

44 doGet() and doPost()

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

46 Example: doGet() import javax.servlet.*; import javax.servlet.http.*;
import*; 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>"); }

47 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

48 Example: Simple Response
public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Fill response headers response.setContentType("text/html"); // Set buffer size response.setBufferSize(8192); // Retrieve an output stream from the response PrintWriter out = response.getWriter(); // Write body content to output stream out.println("<title>First Servlet</title>"); out.println("<big>Hello Servlet Programmers! </big>"); }

49 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

50 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

51 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

52 Web Context (ServletContext)

53 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

54 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

55 ServletContext: Web Application Scope

56 How to Access ServletContext 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

57 Getting and Using RequestDispatcher Objects
public 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 Writer response.setContentType("text/html"); response.setBufferSize(8192); PrintWriter out = response.getWriter(); // then write the response out.println("<html>" + "<head><title>" + messages.getString("TitleBookDescription") + "</title></head>");

58 //Get the dispatcher; it gets the banner to the user
ServletContext ctx = getServletContext(); RequestDispatcher dispatcher = ctx.getRequestDispatcher("/banner"); if (dispatcher != null){ dispatcher.include(request, response); ...

59 Example: Logging public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException { ... getServletContext().log(“Life is good!”); getServletContext().log(“Life is bad!”, someException);

60 Session (HttpSession)

61 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

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

63 Example: HttpSession public class CashierServlet extends HttpServlet {
public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the user's session and shopping cart HttpSession session = request.getSession(); ShoppingCart cart = (ShoppingCart)session.getAttribute("cart"); ... // Determine the total price of the user's books double total = cart.getTotal();

64 Servlet Request (HttpServletRequest)

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

66 Requests

67 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

68 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>

69 A Sample FORM

70 A FORM Based Servlet import 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>"); }

71 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

72 Getting Server Information
Servlet can get server's information: String request.getServerName() e.g. "" int request.getServerPort() e.g. Port number "8080"

73 HTTP Request URL Contains the following parts
path]?[query string]

74 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

75 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 String userName = request.getParameter(“username”)

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

77 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: Referer: User-Agent: Mozilla/ 4.7 [en] (Win98; U)

78 HTTP Request Headers Accept Accept-Encoding Authorization
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

79 HTTP Request Headers Connection Cookie Host
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.

80 HTTP Request Headers If-Modified-Since Referer User-Agent
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.

81 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

82 Showing Request Headers
public 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)); }


84 Thank You!

Download ppt "Web Application Development"

Similar presentations

Ads by Google