Presentation is loading. Please wait.

Presentation is loading. Please wait.

WEB TECHNOLOGIES – Unit V

Similar presentations


Presentation on theme: "WEB TECHNOLOGIES – Unit V"— Presentation transcript:

1 WEB TECHNOLOGIES – Unit V
By B. Ravinder Reddy Assistant Professor Department of CSE UNIT-5 WT

2 Lecture No Topic Name Slide No
LECTURE PLAN UNIT-5 Lecture No Topic Name Slide No L1 Web Servers and Servlets a. Tomcat web server 2-23 L2 Introduction to Servlets 24-32 L3 Lifecycle of a Serverlet, JSDK 33-49 L4 The Servlet API 50-85 L5 The javax.servelet Package 86-96 L6 Reading Servelet parameters , Reading Initialization parameters 97-107 L7 The javax.servelet HTTP package L8 Handling Http Request & Response L9 Using Cookies-Session Tracking, Security Issues UNIT-5 WT

3 LECTURE-1 UNIT-5 WT

4 Web Servers: A web server is nothing but a computer which is
connected to the Internet, hosts the files belonging to a website, and is uniquely identifiable with a valid IP address. Then you can connect to it by typing a relevant domain name and getting it converted to it's IP address (by DNS server). This computer (server) will respond to your requests as URLs, by sending you the relevant resource (e.g. a web page). The picture below makes it more understandable (picture is from howstuffworks.com): UNIT-5 WT

5 UNIT-5 WT

6 Some of web-servers are listed below: • Microsoft's IIS • Apache
These computers that serve you the website are running a software called web-server. This software is not just used to deliver static resources you place on it (e.g. HTML files, CSS files, etc.). Just like the way browsers are responsible to handle HTML, CSS, or JavaScript files, web-servers are capable of executing scripts and programs on the server. Some of web-servers are listed below: • Microsoft's IIS • Apache • and Sun's Tomcat UNIT-5 WT

7 Dynamic web pages are benefiting from this service, server is able to execute scripts or
programs when a dynamic page is called. There are different scripting and programming languages used for creating dynamic web pages, a limited list is presented below: • PHP • Perl • Java (JSP) • ASP • ASP.NET • ... UNIT-5 WT

8 used for web-based applications are: • MySql • Microsoft SQL
Every server has its own characteristics, advantages, and disadvantages, however their detailed features are out of the purpose of this course. In addition to these, web-servers can provide database services to web sites. Some sample database technologies which are often used for web-based applications are: • MySql • Microsoft SQL UNIT-5 WT

9 How does it work? In this section you can see the steps taken in a simple server work-flow: 1 - Request; It all starts with a request sent by a client, when you type in your browser's address bar " you are actually sending a request which finds its way through the Internet by getting converted at the nearest DNS server and ends at the relevant web server. And that is when server receives a request to start it's work. UNIT-5 WT

10 one domain name, it determines the requested target.
Requests are mostly sent by users when they click on a link, enter an address, etc. in their browsers. Therefore it is the browser which actually prepares and send the request, that is the reason XmlHttpRequest is an object of the browser in AJAX development. 2 - Address Resolution; Once the request is received by the server, it takes the following actions before any process happens: 1. Virtual Hosting; This happens when servers virtually provide service for more than one domain name, it determines the requested target. UNIT-5 WT

11 access permission and performs the required authentication.
2. Address Mapping; This checks weather this request is for a dynamic or static resource and redirects it to the actual location of the server's file system. 3. Authentication; If the requested resource is protected, this step verifies user's access permission and performs the required authentication. UNIT-5 WT

12 3 - Request Processing; When resource is found, it is the time when server needs to process for being sent. This process can be divided into two main types, static resources, and dynamic ones. For static resources, there are not much of process required, headers are made ready and that is all. In case of dynamic resources, server needs to execute commands in order to prepare what UNIT-5 WT

13 1. Common Gateway Interface (CGI) scripts
is needed to be sent. Dynamic mechanisms can be divided into the following items: 1. Common Gateway Interface (CGI) scripts 2. Server Side Includes (SSI) 3. Template Approaches 4. Servlet APIs CGI and SSI are the two basic forms of using dynamic content and were available for a long period. Recent developments have resulted in new ways of creating dynamic content using template approaches, Servlets, Hybrid solutions (like PHP), etc. However the important UNIT-5 WT

14 complete what needs to be sent as a response.
issue here is to execute some compiled program or written script in order to generate or complete what needs to be sent as a response. In the process of this execution, web-server may connect to other resources such as data bases or other web-servers. An example is a website which presents weather information, and this information is grabbed from another web-server (e.g. when server is preparing the home page to send to a client, it needs to retrieve weather info from weather.com web-server. UNIT-5 WT

15 4 - Response Generation;
Once execution is over, server sends the content to client. All these steps happens every time you click on a link in your web-based client (such as hotmail)! What to do next? The same way like most of web sites are developed around the world, one needs a local server in order to build and test websites before publishing them on the main server. Therefore each student needs to simulate a web-server on her/his computer. In order to do UNIT-5 WT

16 download it for free from http://easyphp.org/index.php.
so, we will use a simple software called EasyPHP. This software package combines an Apache server, PHP server, and MySql database server all in a windows application. You can download it for free from Once you this software installed and running on your computer, your system can perform as a web-server (locally). This allows you to see the performance of dynamic pages the same way you are used to see for static pages you made before. UNIT-5 WT

17 installation folder (unless you change it during installation).
Note that is the address in which you can access your local web-server's root folder, this address is usually redirected to a folder named "www" in your EasyPHP installation folder (unless you change it during installation). For next parts of this course we will study PHP as a server side scripting language and MySQL as a database which integrates with PHP applications. UNIT-5 WT

18 Tomcat WebServer Setting up development environment
Setting up SSH tunneling. If you have not done so already, follow the instructions for "Advanced SSH setup" in the "Getting Started withcps116" document. Installing Tomcat. Log into cps116 and run the command "/home/dbcourse/bin/setup-tomcat.sh". Log out and log back in again. Copying example source code. Run the command "/home/dbcourse/examples/web-db-beers/setup.sh", which will create a directory named web-db-beers under your home directory on cps116. This directory contains the source code for a simple db-beers web application, which we will use throughout the rest of this document as an example of developing and deploying Java servlet/JSP applications. UNIT-5 WT

19 Setting up example database
Setting up example database. Run the command "/home/dbcourse/examples/db-beers/setup.sh", which will set up the database needed for running the db-beers web application. A note on configuring Tomcat: The script you ran to install Tomcat also carried out some configuration tasks. In particular, the <Resource> element found towards the end of the file ~/apache-tomcat/conf/context.xml configures a JNDI data source that can be used by your web applications. UNIT-5 WT

20 With such a data source, your web applications do not need to worry about any database- or connection-specific details; they simply request a connection from the data source. The application code for dealing with data sources can be found in ~/web-db-beers/src/my/db/BeerDB.java. Additional notes on Tomcat configuration can be found in ~/apache-tomcat/README-cps116.txt. UNIT-5 WT

21 Running Tomcat To start Tomcat, run the command "~/apache-tomcat/bin/startup.sh". To see access the Tomcat web server, point the browser on your work computer to  Assuming that you have followed the advanced SSH setup and Tomcat installation instructions correctly, you should see a welcome page from Tomcat. To shutdown Tomcat, run the command "~/apache-tomcat/bin/shutdown.sh". Note: You can only access the Tomcat web site while you remain logged into cps116 using SSH. Also, please remember to shutdown Tomcat before you log off. UNIT-5 WT

22 Developing and deploying WARs
After starting Tomcat, go into the directory ~/web-db-beers, which is an example of a development directory for a simple db-beers web application. Read the file build.properties in this directory to get a sense of the structure of the development directory. When you start a development directory for your own application, you will want to structure it in the same way. We will use the build tool named ant to build, deploy, and undeploy our application. Below is a list of the most essential commands (all of them should be issued from the base of the development directory, in our case ~/web-db-beers): UNIT-5 WT

23 "ant deploy": Deploy the web application on Tomcat
"ant deploy": Deploy the web application on Tomcat. If deployment succeeds, you can access your web application at the URLhttp://localhost:8080app.path, where app.path is specified in build.properties file (it should have a leading "/"). For our running example, the URL would be  "ant undeploy": Undeploy the web application on Tomcat. A web application must be undeployed first before it can be re-deployed. "ant compile": Compile the Java source files. It is automatically called by "ant dist". "ant dist": Package the web application into a WAR (Web Application Archive) file ready to be deployed. It is automatically called by "ant deploy". UNIT-5 WT

24 A variety of other ant commands (called "targets") are available; read build.xml and build.properties for details. A typical development cycle consists of coding/debugging -> ant deploy -> testing on browser -> ant undeploy, and then back to coding/debugging. To develop your own servlet/JSP application, you may start with a copy of the development directory for db-beers, and make appropriate changes tobuild.properties, src/, and web/. If you want to use external jar library files, put those under web/WEB-INF/lib/. UNIT-5 WT

25 LECTURE-2 UNIT-5 WT

26 INTRODUCTION TO SERVLETS
Java Servlets are part of the Sun’s J2EE Enterprise Architecture The web development part Java Servlet is a simple, consistent mechanism for extending the functionality of a web server Are precompiled Java programs that are executed on the server side. Require a Servlet container to run UNIT-5 WT

27 What Is A Servlet A Java object Plug-in for a web server
Replacement for CGI scripts Can also be used to extend server as a plug-in Full power of Java Platform-independent Database access Easy to write UNIT-5 WT

28 Server/Service/Servlet
server - a process running on a host machine Apache, Java Web Server service - a protocol running on a port HTTP, FTP servlet - a module running inside a service PhoneServlet UNIT-5 WT

29 Servlet/Service/Server Diagram
UNIT-5 WT

30 Why Use Servlets? Work well in a Heterogeneous Environments
OS and platform neutral Work with all major web servers (IIS, apache,etc..) Well defined Web Architecture framework Standard built in services such as: Standard Approach to Authentication using declarative security vice programmatic security Database connection pooling Complete support for sessions via cookies and/or URL re-writing. UNIT-5 WT

31 Servlet Container/Engine
Servlets require a Container Apache Tomcat is the reference implementation of the Servlet Specifications It is open source, small, install quickly, and is FREE Web Site: jakarta.apache.org/tomcat It include a simple HTTP 1.1 server, good enough for development and small applications. UNIT-5 WT

32 Why Java Servlets Instead of CGI?
Efficient, Convenient, Powerful, Portable, Secure, Inexpensive Lightweight threads instead of OS threads created Single copy of code brought into memory for all threads versus per thread Data (session state) can be stored across threads within servlet container Java is portable and secure Requires little expense once servlet container integrated with web server UNIT-5 WT

33 Advantages of Servlets over CGI
Performance : Performance is significantly better. Servlets execute within the address space of a Web server. Creating a separate process to handle each client request isn't necessary. Platform Independence: Servlets are platform-independent, because they are written in Java. Several Web servers, from vendors such as Sun, Netscape, and Microsoft, offer the Servlet API. Programs developed for this API can be moved to any of these environments without recompilation. Security: The Java Security Manager on the server enforces a set of restrictions to protect the resources on a server machine. You will see that some servlets are trusted and others are untrusted. Extensibility: The full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms. Portability: Java servlets uses philosophy of write once and run any where. UNIT-5 WT

34 LECTURE-3 UNIT-5 WT

35 Servlet Lifecycle When user enters a Uniform Resource Locator (URL) to a Web browser, then the browser generates an HTTP request for this URL and sends it to the appropriate server. This HTTP request is received by the Web server. The server maps this request to a particular servlet. The servlet is dynamically retrieved and loaded into the address space of the server. Then the three methods that are central to the life cycle of a servlet: init( ), service( ), and destroy( ) are called. They are implemented by every servlet and are invoked at specific times by the server. UNIT-5 WT

36 Servlet Lifecycle (Init Method)
Single instance created init() method called You can override init() in your subclass of HttpServlet to do some initial code.... init() is NOT called again on further requests UNIT-5 WT

37 Servlet Lifecycle (Service Method)
On each request, the server creates a new thread and calls service() service() checks HTTP request type and calls appropriate doXXXX (Get, Post, Put...) don't override service (unless you really know what you're doing) UNIT-5 WT

38 Servlet Lifecycle (destroy())
For some reason (servlet idle, etc) the server may want to remove the servlet from memory destroy() allows you to close DB connections, wrap up, etc... destroy() is called before the servlet is removed from the server. UNIT-5 WT

39 Life Cycle of Servlet servlet GenericServlet HttpServlet
init(ServletConfig); doGet(HttpServletRequest, HttpServletResponse); service(ServletRequest, ServletResponse); doPost(HttpServletRequest, HttpServletResponse); ……. destroy(); UNIT-5 WT

40 Request Processing Container Code GET or POST request Send Response
Yes Servlet exists req resp No resp resp Load servlet Initialize servlet Process Service Static Resources Web Container WEB SERVER UNIT-5 WT

41 The Java Servlet Development Kit
The Java Servlet Development Kit (JSDK) contains the class libraries that are needed to create servlets. A utility known as the servletrunner is also included, which enables you to test some of the servlets that you create. Download the JSDK without charge from the Sun Microsystems Web site at java.sun.com. Follow the instructions to install this toolkit on your machine. For a Windows machine, the default location of Version 2 of the JSDK is c:\\Jsdk2.0. The directory c:\\Jsdk2.0\\bin contains servletrunner.exe. Update your Path environment variable so that it includes this directory. The directory c:\\Jsdk2.0\\lib contains jsdk.jar This JAR file contains the classes and interfaces that are needed to build servlets. UNIT-5 WT

42 The basic steps are the following:
Update your Classpath environment variable so that it includes c:\\Jsdk2.0\\lib\\jsdk.jar. The basic steps are the following: 1. Create and compile the servlet source code. 2. Start the servletrunner utility. 3. Start a Web browser and request the servlet. Start a Web browser and enter the URL shown here: Alternatively, you may enter the URL shown here: This can be done because is defined as the IP address of the local machine UNIT-5 WT

43 Web server Architecture
Web Container Static Resources Servlets Req Servlet Engine Resp JSP’s Client Web Server UNIT-5 WT

44 Phases in servlet development
Servlet components go through the following phases during its life time Development Phase Deployment Phase Running Phase UNIT-5 WT

45 Development Phase This phase involves
Creation of a directory structure Creation of servlet classes Creation of Deployment Descriptor (web.xml) Creation of HTML files (If any exists) Creation of supporting Java classes If exists) Creation of any other supporting files UNIT-5 WT

46 Directory structure of a web application
A web application has a prescribed directory structure that all compliant servlet containers understand. Application Root (HTML, JSP, Images, . .etc) - Other context folders + - / WEB-INF classes + lib(contains third party jar files) src (put all .java files) <O> Web.xml UNIT-5 WT

47 The root directory contains a special directory named WEB-INF .
The top level or application root contains HTML documents, JSP pages, Images and any other resources. Any number of subdirectories, which also contains application context can be under the root, much like folders in the document tree of a web server. The root directory contains a special directory named WEB-INF . This directory and its sub directories are not visible to application users. They contains servlet classes, .jar files and configuration data UNIT-5 WT

48 classes: This directory contains servlets and other classes
classes: This directory contains servlets and other classes. These classes are automatically found by the servlet class loader, as if they were in application class path. lib: This directory contains .jar files. Classes in any .jar file in this directory are automatically made available to the class loader without having to be listed explicitly in some class path web.xml : This is an xml document referred to as the deployment descriptor. It is used to configure the servlets and other resources that make up the web application. UNIT-5 WT

49 Creating the servlet Every servlet should implement the javax.servlet.Servlet interface either directly or indirectly. A servlet can be created either by extending javax.servlet.GenericServlet class or by extending javax.servlet.http.HttpServlet class. javax.servlet.Servlet interface defines the life cycle methods init(), service(), and destroy() and two very useful methods getServletConfig() , getServletInfo(). UNIT-5 WT

50 Note: Every process that is running on certain host will be assigned a unique port number by the operating system, where the port number is the logical entity to assign to the processor. So that the processor communicate to the external world through this port number. Every host in the network will have nearly port numbers. The default port number assigned to the tomcat server is 8080 UNIT-5 WT

51 LECTURE-4 UNIT-5 WT

52 The Java Servlet API UNIT-5 WT

53 The Servlet API Java provides two packages contain the code that is required to build servlets: javax.servlet javax.servlet.http. They constitute the Servlet API. These packages are not part of the Java core packages. Therefore, they are not included in the Java Development Kit (JDK). You must download the Java Servlet Development Kit (JSDK) to obtain their functionality. The Servlet API is supported by most Web servers, such as those from Sun, Microsoft, and others. Check the Sun Microsystems Web pages at for additional information. UNIT-5 WT

54 HTTP HyperText Transfer Protocol
Stateless request/response client-server protocol Requests: Method: GET, POST, HEAD, TRACE, OPTIONS, PUT, DELETE UNIT-5 WT

55 HTTP Requests, continued URI (required in HTTP/1.1) Header Fields Body
E.g. how the response should be returned, under what conditions, identification and characterization of client, accounting data Body POST data Empty for GET UNIT-5 WT

56 HTTP Response: Status code (machine), reason (human) Header Body
Metadata, e.g. Content-Type (Media type), Content-Length, Last-Modified, Etag Body (X)HTML, other XML, text, binary data … UNIT-5 WT

57 URL Connections java.net also -- connections extend Socket
Encapsulates HTTP and FTP connections URI, URL, URLConnection, HttpURLConnection UNIT-5 WT

58 Servlets Definition Enhance/extend a “web” server
Reside in a servlet container Provide mechanisms for maintaining state Most often used in http servers UNIT-5 WT

59 Servlets Technical details: Event-based Request/response discipline
Lifetime beyond a single event For dynamic web applications: Can generate HTML, embody business logic, communicate with a database, select static HTML in response to a request More often interpretation of request, then delegation of responsibilities (Controller in MVC) UNIT-5 WT

60 Servlet Lifecycle Multithreaded access (usually default)
init called first 0 to many calls to service destroy called UNIT-5 WT

61 init (ServletConfig) call super.init (config), or just use init ()
Called once Prior to any call to service Don’t worry about multithreading issues here Sometimes used to get resources needed for the lifetime of the servlet UNIT-5 WT

62 service (req, resp) Not usually overridden
Default impl. determines what request handler to call (based on HTTP request type), calls it Will call doGet, doPost, doPut, etc. Default implementations provided for doHead, doTrace, doOptions UNIT-5 WT

63 doPost, doGet, etc. doPost (HttpServletRequest req, HttpServletResponse resp) Implement this to handle POSTs Read from req, build resp Multithreaded access by default (depending on server config) Beware instance variables, shared data config and context are shared, session is usually safe, req/resp are not Use locks and/or synchronized data structures if shared data is an issue UNIT-5 WT

64 destroy () called once Servlet timeout, servlet reload, container shutdown Other threads may still be processing service requests, no further requests will be processed Release resources, write data, etc. UNIT-5 WT

65 Generating output, handling form data, maintaining state
Using servlets Generating output, handling form data, maintaining state UNIT-5 WT

66 Review Typically used in HTTP servers
Server side of HTTP request/response Interpret request, generate response Servlets are container-managed Respond to events, doXXXX Need to consider lifecycle, threading policies, security, resource access and configuration UNIT-5 WT

67 Generating (X)HTML Set content type Access response output stream
As a PrintWriter, via response.getWriter () Use out.println, out.print Escape quotes You are responsible for all content, including doctype header (and xml declaration if using XHTML) UNIT-5 WT

68 HTML Forms Form data consists of name, value pairs
Values are retrieved on the server by name GET passes data in the query string Always URL-encoded POST passes data in content of request Either URL-encoded, or multipart/form-data UNIT-5 WT

69 HTTP URL structure query is URL-encoded: name1=Bob+Smith&name2=Sally+Jones Name1=Bob%20Smith&name2=Sally%20Jones UNIT-5 WT

70 space characters are replaced by `+', and
space characters are replaced by `+', and .. non-alphanumeric characters are replaced by `%HH’, HH 2 hex digits representing char in encoding. Line breaks.. are CR LF pairs, i.e. `%0D%0A'. fields are listed in the order they appear in the document with name,value separated by `=' and the pairs separated from each other by `&'. Fields with null values may be omitted (e.g. empty checkboxes). UNIT-5 WT

71 Structure of forms form element Attributes: action (REQUIRED)
method (GET) enctype, accept, accept-charset onsubmit, onreset UNIT-5 WT

72 Forms contain controls
input : many kinds of form data Text fields, checkboxes, radio buttons, passwords, buttons, hidden controls, file selectors, object controls button : type=submit|button|reset select : a menu, contains option child elements textarea : multi-line text input field Other html tags can be present (e.g. format forms in tables) UNIT-5 WT

73 Servlet support Does decoding for you, common interface Just use
request.getParameter (String name) for both GET and POST Returns null if parameter doesn’t exist Multipart not well supported in standard API Use request.getReader (), request.getInputStream () ..parse yourself Use 3rd party API, e.g. com.oreilly.servlet.multipart.MultipartParser, org.apache.commons.fileupload.servlet UNIT-5 WT

74 More Servlet Support Retrieve all values matching name:
request.getParameterValues (String name) Returns String array, or null Retrieve all parameter names: request.getParameterNames () Returns String Enumeration Retrieve an immutable Map<String,String> of name, value pairs request.getParameterMap () UNIT-5 WT

75 Filtering and Displaying Text Input
Filter input text data if it will be displayed in result Replace characters that are escaped in xml with their escape sequences & --> & < --> < “ --> " ‘ --> &apos; Decide how you will handle whitespace Convert spaces, tabs to   and newlines to <br/> Wrap in <pre> Generate corresponding html/css code ignore UNIT-5 WT

76 Maintaining State Cookies Name,value pairs with properties
Lifetime independent of request/response Passed between client and server during HTTP transactions Hidden fields, URL rewriting Form controls (input type=“hidden”) added dynamically to pages, containing name/value that should be associated with client. Hardcoded links (href) contain name/value data in query UNIT-5 WT

77 Maintaining State, continued
Sessions Pass a single cookie (or fallback to URL rewriting) containing a session ID Server maintains a mapping between session ID and associated data stored on the server UNIT-5 WT

78 Cookie Support Cookie class Name, value Domain, path maxAge
> 0 Persist cookie, in seconds -1 (default) in memory, until browser is closed 0 delete cookie on client UNIT-5 WT

79 Using Cookies Retrieving cookies
request.getCookies () returns array of Cookie or null Creating cookies Cookie (String name, String value) Updating client Existing Cookies can be modified, but must be added to response for change to take place response.addCookie (Cookie c) UNIT-5 WT

80 Hidden forms, URL rewriting support
DIY exception : URL rewriting a common fallback when cookies not supported for session ID, discussed next response.encodeURL (String url) Returns URL with encoded session ID if necessary UNIT-5 WT

81 Sessions Support in Java
HttpSession is an interface for a glorified (specialized) Map<String,Object> or similar One-to-one mapping between jsessionID and HttpSession Attached to HTTPServletRequest object in doXXXX methods request.getSession (boolean create=true) request.isRequestedSessionIdValid () UNIT-5 WT

82 Sessions support, continued
Associated with one client (usually) Id, creation time, last accessed time Can be invalidated manually or due to inactivity Lifetime: new-->active-->invalid Object getAttribute (String name) setAttribute (String name, Object o) Enumeration getAttributeNames () UNIT-5 WT

83 More Session details Interface maps String to Object, you must cast ref to derived type If your object uses generics (e.g. typed lists), you’ll get a compiler warning when casting Interface is pre 1.5, strips away type info Any other code can take e.g. a List<String> session object and treat it as an untyped list Solutions: be careful, store keys into external structures, use Checked wrappers on collections (runtime cost) UNIT-5 WT

84 Sharing, Storing Distributed sessions
E.g. load balancing servers need access to same user’s session if redirected Transaction management details are not in spec. May need to redundantly replace object refs in session Persistent sessions Tomcat default (try recompiling a servlet that uses sessions and refreshing a page without closing your browser) In both cases sessions are serialized (converted into streams) Contents that aren’t Serializable will be lost UNIT-5 WT

85 ServletConfig Provided to a servlet upon initialization by the web server (container) Simple read only interface to configuration details String getInitParameter (String name) Enumeration getInitParameterNames () String getServletName () Can also access ServletContext UNIT-5 WT

86 ServletContext Lets a servlet communicate with its container
Access container-managed resources, dispatch requests, write to logs Can be used as a global data store (like an application-wide session) But is specific to single web container -- does not work in clustered scenarios Recommendation is to use a resource that is shared (e.g. cached DataSource, directory) We will see/use the servlet context later on UNIT-5 WT

87 LECTURE-5 UNIT-5 WT

88 The javax.servlet Package
The javax.servlet package contains a number of interfaces and classes that establish the framework in which servlets operate. The following table summarizes the interfaces that are provided in this package. The most significant of these is Servlet. All servlets must implement this interface or extend a class that implements the interface. The ServletRequest and ServletResponse interfaces are also very important. UNIT-5 WT

89 Objectives In this lesson, you will learn:
To execute servlets with the Apache Tomcat server. To be able to respond to HTTP requests from an HttpServlet. To be able to redirect requests to static and dynamic Web resources. UNIT-5 WT

90 1 Introduction Java networking capabilities
Socket-based and packet-based communications Package java.net Remote Method Invocation (RMI) Package java.rmi Servlets and Java Server Pages (JSP) Request-response model Packages javax.servlet javax.servlet.http javax.servlet.jsp javax.servlet.tagext Form the Web tier of J2EE UNIT-5 WT

91 1 Introduction (Cont.) Servlets Thin clients
Request/response mechanism redirection Tomcat Jakarta project Official reference implementation of the JSP and servlet standards UNIT-5 WT

92 2 Servlet Overview and Architecture
Servlet container (servlet engine) Server that executes a servlet Web servers and application servers Sun ONE Application Server Microsoft’s Internet Information Server (IIS) Apache HTTP Server BEA’s WebLogic Application Server IBM’s WebSphere Application Server World Wide Web Consortium’s Jigsaw Web Server UNIT-5 WT

93 Interface Servlet and the Servlet Life Cycle (Cont.)
UNIT-5 WT

94 Interface Summary RequestDispatcher:Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server. ServletDefines methods that all servlets must implement\ ServletConfig:A servlet configuration object used by a servlet container used to pass information to a servlet during initialization. ServletContext:Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file UNIT-5 WT

95 ServletRequest:Defines an object to provide client request information to a servlet.
ServletResponse:Defines an object to assist a servlet in sending a response to the client. SingleThreadModel:Ensures that servlets handle only one request at a time. UNIT-5 WT

96 Class Summary GenericServlet:Defines a generic, protocol-independent servlet. ServletInputStream:Provides an input stream for reading binary data from a client request, including an efficient readLine method for reading data one line at a time. ServletOutputStream:Provides an output stream for sending binary data to the client. UNIT-5 WT

97 Exception Summary ServletException :Defines a general exception a servlet can throw when it encounters difficulty. UnavailableException:Defines an exception that a servlet throws to indicate that it is permanently or temporarily unavailable. UNIT-5 WT

98 LECTURE-6 UNIT-5 WT

99 Reading Servelet parameters , Reading Initialization parameters
Before delving into how a servlet can read data submitted via a form, it is necessary to understand how data from an HTML form is passed to the webserver by the browser. Their are too common ways of passing data from the webbrowser to the webserver. They are called POST and GET. Both of these methods pass the data in a 'key=value' format. The key for each data field is specified as part of the tag describing the relevant field. UNIT-5 WT

100 <FORM ACTION="/servlets/aservlet" METHOD="GET">
Using the GET method (Assume the following form is part of a web page located on the webserver <FORM ACTION="/servlets/aservlet" METHOD="GET"> <INPUT TYPE="HIDDEN" NAME="thisIsAKey" Value="xxxx"> <INPUT TYPE="HIDDEN" NAME="anotherKey" VALUE="yyyy"> <INPUT TYPE="SUBMIT" VALUE="Go...."> </FORM> When submitted, the browser would execute the following URL :-  UNIT-5 WT

101 <AHREF='/servlets/aservlet?thisIsAKey=xxxx&anotherKey=yyyy'>
See that the data is appended onto the end of the URL, using a '?' to separate the data from the main body of the URL, with '&' characters used to separate the individual key/value pairs. There is no reason why this URL, with the data appended couldn't be put straight straight into an Anchor tag thus :- <AHREF='/servlets/aservlet?thisIsAKey=xxxx&anotherKey=yyyy'> This can enable you to dispense with the need for a form altogether for cases where user input is not required for any of the key/value pairs. UNIT-5 WT

102 Using the POST Method In some cases it may not be desirable to display all of the data submitted by the user as part of the URL, for example if the user were submitting a password. The POST method of submitting data from a form allows the data to be passed to the webserver seperatly from the URL in a 'hidden' format. Excepting that this method cannot be used to pass key/value pairs from an Anchor tag, this will function in the same way as GET in all other ways. A Form Reading Servlet The following code is a simple example of a servlet which is reading parameters that have been supplied by an HTML form. UNIT-5 WT

103 import javax.servlet.http.*; import java.io.*; import java.util.*;
public class MyNameServlet extends HttpServlet { /** * Method to receive get requests from the web server (Passes them onto the doPost method) req The HttpServletRequest which contains the information submitted via get UNIT-5 WT

104 * Method to receive and process Post requests from the web server
res A response containing the required response data for this request * */ public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doPost(req,res); } /** * Method to receive and process Post requests from the web server req The HttpServletRequest which contains the information submitted via post res A response containing the required response data for this request **/ UNIT-5 WT

105 String reply="<HTML>\n"+ "<HEAD>
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { //*****Read the value of the 'yourname' parameter***** String name=req.getParameterValues("yourname")[0]; //*****Construct a response in HTML***** String reply="<HTML>\n"+ "<HEAD> <TITLE>My Name Servlet Response</TITLE> </HEAD>\n"+ "<BODY>\n"+ "<CENTER><BR><B>\n"+ "Hello "+name+"\n"+ "</B></CENTER>\n</BODY>\n</HTML>"; //*****Send the reply***** res.setContentType("text/html"); PrintWriter out=res.getWriter(); out.println(reply); out.close(); } } UNIT-5 WT

106 This servlet interprets information from the following HTML form
This servlet interprets information from the following HTML form. It users the POST method, but you can change this to GET if you wish to try both methods. The web page must be located on the same server and accessed via that server (not with a file:open in your browser), or you get '404 file not found' error messages when trying to use it. UNIT-5 WT

107 <HTML> <HEAD> <TITLE>My Name Servlet Demonstration</TITLE> </HEAD> <BODY> <CENTER> <FORM ACTION="/servlet/MyNameServlet" METHOD=POST> Please Enter your name <INPUT TYPE=TEXT NAME="yourname"> <INPUT TYPE=SUBMIT VALUE=Submit> </FORM> </CENTER> </BODY> </HTML> UNIT-5 WT

108 This is because some HTML form elements can return more than one item,
When called, this servlet will look for a parameter supplied in the HttpServletRequest called 'yourname' and then construct its reply using the data stored in this parameter. Notice that the 'getParameterValues' method actually returns an array of Strings, rather than a single string. This is because some HTML form elements can return more than one item, eg a list which allows multiple selections. If you want to try this servlet out, just use the form below : Please Enter your name   The information contained in this form will be received by the webserver and passed to the servlet as part of the HttpServletRequest object. UNIT-5 WT

109 LECTURE-7 UNIT-5 WT

110 The javax.servelet HTTP package
UNIT-5 WT

111 Client server communication
HTTP request Client HTTP response Web Server UNIT-5 WT

112 HTTP Protocol A servlet is a java component that can be plugged into a Java-enabled web server. Servlets are designed to work within a request/response oriented services. In request/response model a client sends a request message to server and server responds by sending response message back to client. This communication uses HTTP or FTP. Most commonly used protocol is HTTP. Defines a protocol used by web browsers and servers to communicate. Simple Request-Response model based protocol UNIT-5 WT

113 Application layer protocol built on TCP/IP Stateless Protocol
Does not define how network connection is initiated or managed Plain-Text Protocol (i.e. defines a set of text based request messages called HTTP methods). HTTP transaction consists of Connection: The client establishes a connection with web server. Request: The client sends a request message to the web server. Response: The web server sends a response to client. Close: The connection is closed by the web server. UNIT-5 WT

114 HTTP Methods GET POST HEAD PUT DELETE OPTIONS TRACE
HTTP GET method request information from a web server. GET requests have limitations and sends data as a part of URL. POST HTTP POST request allows a client to send data to the server. POST method passes all of its parameter data in an input stream as method body and no limitations on data. HEAD Similar to GET, but forces the server to return only an HTTP header information instead of response data (last modified date, size, server type etc..). PUT Uploads the resource to the server. DELETE Deletes the resource from the server. OPTIONS Requests the servers configuration options (for example the requests methods supported by server) TRACE Performs an HTTP TRACE UNIT-5 WT

115 javax.servlet.http package helps to write HTTP servlets.
The abstract class javax.servlet.http.HttpServlet provides an implementation of the javax.servlet.Servlet interface and provides default functionality. Extend HttpServlet class to write an HttpServlet. HttpServlet provides an implementation of service() method that dispatches the HTTP messages to one of the methods doGet(), doPost(), doHead(), doOptions(), doDelete(), doPut(), doTrace(). UNIT-5 WT

116 Web App with Servlets Servlet Container GET … Servlet doGet() …
HEADERS BODY Servlet Container UNIT-5 WT

117 HttpServlet Class HttpServletRequest and HttpServletResponse objects
Overrides method service Two most common HTTP request types get requests post requests Method doGet responds to get requests Method doPost responds to post requests HttpServletRequest and HttpServletResponse objects UNIT-5 WT

118 HttpServlet Class (Cont.)
UNIT-5 WT

119 HttpServletRequest Interface
Web server creates an HttpServletRequest object passes it to the servlet’s service method HttpServletRequest object contains the request from the client UNIT-5 WT

120 HttpServletRequest Interface (Cont.)
UNIT-5 WT

121 HttpServletResponse Interface
Web server creates an HttpServletResponse object passes it to the servlet’s service method UNIT-5 WT

122 HttpServletResponse Interface (Cont.)
UNIT-5 WT

123 Handling HTTP get Requests
Retrieve the content of a URL Example: WelcomeServlet a servlet handles HTTP get requests UNIT-5 WT

124 WelcomeServlet.java (1 of 2)
Import the javax.servlet and javax.servlet.http packages. WelcomeServlet.java (1 of 2) Extends HttpServlet to handle HTTP get requests and HTTP post requests. Override method doGet to provide custom get request processing. Uses the response object’s setContentType method to specify the content type of the data to be sent as the response to the client. Uses the response object’s getWriter method to obtain a reference to the PrintWriter object that enables the servlet to send content to the client. Create the XHTML document by writing strings with the out object’s println method. UNIT-5 WT

125 WelcomeServlet.java (2 of 2)
Closes the output stream, flushes the output buffer and sends the information to the client. UNIT-5 WT

126 WelcomeServlet.html (1 of 1)
UNIT-5 WT

127 Program output UNIT-5 WT

128 Setting Up the Apache Tomcat Server
Download Tomcat (version ) jakarta.apache.org/site/binindex.cgi Define environment variables JAVA_HOME CATALINA_HOME Start the Tomcat server startup Launch the Tomcat server UNIT-5 WT

129 Setting Up the Apache Tomcat Server (Cont.).
Fig Tomcat documentation home page. (Courtesy of The Apache Software Foundation.) UNIT-5 WT

130 Deploying a Web Application
Web applications JSPs, servlets and their supporting files Deploying a Web application Directory structure Context root Web application archive file (WAR file) Deployment descriptor web.xml UNIT-5 WT

131 Deploying a Web Application (Cont.)
UNIT-5 WT

132 Element web-app defines the configuration of each servlet in the Web application and the servlet mapping for each servlet. web.xml (1 of 2) Element display-name specifies a name that can be displayed to the administrator of the server on which the Web application is installed. Element description specifies a description of the Web application that might be displayed to the administrator of the server. Element servlet describes a servlet. Element servlet-name is the name for the servlet. Element description specifies a description for this particular servlet. UNIT-5 WT

133 Element servlet-class specifies compiled servlet’s fully qualified class name.
Element servlet-mapping specifies servlet-name and url-pattern elements. web.xml (2 of 2) UNIT-5 WT

134 Handling HTTP get Requests Containing Data
Servlet WelcomeServlet2 Responds to a get request that contains data UNIT-5 WT

135 Handling HTTP post Requests
Post data from an HTML form to a server-side form handler Browsers cache Web pages Servlet WelcomeServlet3 Responds to a post request that contains data UNIT-5 WT

136 WelcomeServlet3 .java (1 of 2)
Declare a doPost method to responds to post requests. UNIT-5 WT

137 WelcomeServlet3 .java (1 of 2)
UNIT-5 WT

138 WelcomeServlet3 .html (1 of 1)
Provide a form in which the user can input a name in the text input element firstname, then click the Submit button to invoke WelcomeServlet3. UNIT-5 WT

139 Program output UNIT-5 WT

140 Handling HTTP post Requests (Cont.)
UNIT-5 WT

141 Redirecting Requests to Other Resources
Servlet RedirectServlet Redirects the request to a different resource UNIT-5 WT

142 RedirectServlet.java (1 of 3)
Obtains the page parameter from the request. Determine if the value is either “deitel” or “welcome1” Redirects the request to Redirects the request to the servlet WelcomeServlet. UNIT-5 WT

143 RedirectServlet.java (2 of 3)
Output a Web page indicating that an invalid request was made if method sendRedirect is not called. UNIT-5 WT

144 RedirectServlet.java (3 of 3)
UNIT-5 WT

145 Program output UNIT-5 WT

146 Redirecting Requests to other Resources (Cont.)
UNIT-5 WT

147 Multi-Tier Applications: Using JDBC from a Servlet
Three-tier distributed applications User interface Business logic Database access Web servers often represent the middle tier Three-tier distributed application example SurveyServlet Survey.html MS Access database UNIT-5 WT

148 SurveyServlet.java (1 of 6)
Servlets are initialized by overriding method init. Loads the database driver. Attempt to open a connection to the animalsurvey database. UNIT-5 WT

149 SurveyServlet.java (2 of 6)
Create Statement to query database. SurveyServlet.java (2 of 6) UNIT-5 WT

150 SurveyServlet.java (3 of 6)
Obtain the survey response Create query to update total for current survey response Execute query to update total for current survey response UNIT-5 WT

151 SurveyServlet.java (4 of 6)
Create query to get total of all survey responses Execute query to get total of all survey responses SurveyServlet.java (4 of 6) Create query to get survey results Execute query to get survey results UNIT-5 WT

152 SurveyServlet.java (5 of 6)
UNIT-5 WT

153 SurveyServlet.java (6 of 6)
Method destroy closes Statement and database connection. SurveyServlet.java (6 of 6) UNIT-5 WT

154 Survey.html (1 of 2) UNIT-5 WT

155 Survey.html (2 of 2) UNIT-5 WT

156 UNIT-5 WT

157 Multi-Tier Applications: Using JDBC from a Servlet (Cont.)
UNIT-5 WT

158 Java Servlets – Classes to import
Package HttpServlet javax.servlet.http HttpServletRequest HttpServletResponse PrintWriter java.io ServletException javax.servlet IOException UNIT-5 WT

159 LECTURE-8 UNIT-5 WT

160 Handling Http Request & Response in servlets
UNIT-5 WT

161 HttpServlet Class Overrides method service
Two most common HTTP request types get requests post requests Method doGet responds to get requests Method doPost responds to post requests HttpServletRequest and HttpServletResponse objects UNIT-5 WT

162 HttpServlet Class (Cont.)
UNIT-5 WT

163 HttpServletRequest Interface
Web server creates an HttpServletRequest object passes it to the servlet’s service method HttpServletRequest object contains the request from the client UNIT-5 WT

164 HttpServletRequest Interface (Cont.)
UNIT-5 WT

165 HttpServletResponse Interface
Web server creates an HttpServletResponse object passes it to the servlet’s service method UNIT-5 WT

166 HttpServletResponse Interface (Cont.)
UNIT-5 WT

167 Handling HTTP get Requests
Retrieve the content of a URL Example: WelcomeServlet a servlet handles HTTP get requests UNIT-5 WT

168 WelcomeServlet.java (1 of 2)
Import the javax.servlet and javax.servlet.http packages. WelcomeServlet.java (1 of 2) Extends HttpServlet to handle HTTP get requests and HTTP post requests. Override method doGet to provide custom get request processing. Uses the response object’s setContentType method to specify the content type of the data to be sent as the response to the client. Uses the response object’s getWriter method to obtain a reference to the PrintWriter object that enables the servlet to send content to the client. Create the XHTML document by writing strings with the out object’s println method. UNIT-5 WT

169 WelcomeServlet.java (2 of 2)
Closes the output stream, flushes the output buffer and sends the information to the client. UNIT-5 WT

170 WelcomeServlet.html (1 of 1)
UNIT-5 WT

171 Program output UNIT-5 WT

172 LECTURE-9 UNIT-5 WT

173 Using Cookies-Session Tracking, Security Issues
UNIT-5 WT

174 Continuity Problem Session: A user sits down, enters a website, does some work, exits HTTP Stateless Does Keep-Alive Help? UNIT-5 WT

175 Client vs. Server Side Client Side
Store Variable=Value Bindings in HTML Page, or Cookies Server Side Store Variable=Value Bindings in DB/Server Memory Store Session ID on Client Side, to identify Client UNIT-5 WT

176 Three Typical Solutions
Cookies URL Rewriting Hidden Fields UNIT-5 WT

177 HTTP Cookies Grab-bag Lifetime Session – not written to file system
Persistent – written to user preferences Only returns cookie to requesting domain Cookie must be specified by content No special characters in cookie UNIT-5 WT

178 HTTP Cookies String sID = makeUniqueString();
String sID = makeUniqueString(); Hashtable sessionInfo = new Hashtable(); Hashtable globalTable = findTableStoringSessions(); globalTable.put(sID, sessionInfo); Cookie sessionCookie = new Cookie("JSESSIONID", sID); sessionCookie.setPath("/"); response.addCookie(sessionCookie); UNIT-5 WT

179 HTTP Cookies String sID = makeUniqueString();
String sID = makeUniqueString(); Hashtable sessionInfo = new Hashtable(); Hashtable globalTable = findTableStoringSessions(); globalTable.put(sID, sessionInfo); Cookie sessionCookie = new Cookie("JSESSIONID", sID); sessionCookie.setPath("/"); response.addCookie(sessionCookie); UNIT-5 WT

180 HTTP Cookies String sID = makeUniqueString();
String sID = makeUniqueString(); Hashtable sessionInfo = new Hashtable(); Hashtable globalTable = findTableStoringSessions(); globalTable.put(sID, sessionInfo); Cookie sessionCookie = new Cookie("JSESSIONID", sID); sessionCookie.setPath("/"); response.addCookie(sessionCookie); UNIT-5 WT

181 HTTP Cookies String sID = makeUniqueString();
String sID = makeUniqueString(); Hashtable sessionInfo = new Hashtable(); Hashtable globalTable = findTableStoringSessions(); globalTable.put(sID, sessionInfo); Cookie sessionCookie = new Cookie("JSESSIONID", sID); sessionCookie.setPath("/"); response.addCookie(sessionCookie); UNIT-5 WT

182 HTTP Cookies String sID = makeUniqueString();
JSESSIONID → String sID = makeUniqueString(); Hashtable sessionInfo = new Hashtable(); Hashtable globalTable = findTableStoringSessions(); globalTable.put(sID, sessionInfo); Cookie sessionCookie = new Cookie("JSESSIONID", sID); sessionCookie.setPath("/"); response.addCookie(sessionCookie); UNIT-5 WT

183 HTTP Cookies String sID = makeUniqueString();
JSESSIONID → PATH → / String sID = makeUniqueString(); Hashtable sessionInfo = new Hashtable(); Hashtable globalTable = findTableStoringSessions(); globalTable.put(sID, sessionInfo); Cookie sessionCookie = new Cookie("JSESSIONID", sID); sessionCookie.setPath("/"); response.addCookie(sessionCookie); UNIT-5 WT

184 HTTP Cookies String sID = makeUniqueString();
Set-Cookie: JSESSIONID= ; path=/; String sID = makeUniqueString(); Hashtable sessionInfo = new Hashtable(); Hashtable globalTable = findTableStoringSessions(); globalTable.put(sID, sessionInfo); Cookie sessionCookie = new Cookie("JSESSIONID", sID); sessionCookie.setPath("/"); response.addCookie(sessionCookie); UNIT-5 WT

185 HTTP Cookies // On request
Cookie: JSESSIONID= ; // On request String sID = request.getCookie("JSESSIONID"); Hashtable globalTable = findTableStoringSessions(); Hashtable sInfo = (Hashtable) globalTable.get(sID); UNIT-5 WT

186 HTTP Cookies // On request
Cookie: JSESSIONID= ; // On request String sID = request.getCookie("JSESSIONID"); Hashtable globalTable = findTableStoringSessions(); Hashtable sInfo = (Hashtable) globalTable.get(sID); UNIT-5 WT

187 HTTP Cookies // On request
Cookie: JSESSIONID= ; // On request String sID = request.getCookie("JSESSIONID"); Hashtable globalTable = findTableStoringSessions(); Hashtable sInfo = (Hashtable) globalTable.get(sID); UNIT-5 WT

188 In-Browser Cookie Management
UNIT-5 WT

189 URL Rewriting Rewrite all URLs in response to contain SessionID
Parse out session ID from request line encodeURL() in HttpResponse object will rewrite session-id onto URL Limitations Always include ?sessionID= e.g. home.html/ UNIT-5 WT

190 URL Rewriting UNIT-5 WT

191 Hidden Form Fields <input type=“hidden” name=“session” value=“...”> UNIT-5 WT

192 Java Servlet Solution Session tracking API built on top of URL rewriting or cookies Look up HttpSession object associated with current request (or create new one) All cookie/URL rewriting mechanics hidden Look up information associated with a session Associate information with a session UNIT-5 WT

193 Look up Session Info HttpSession session = request.getSession(true); ShoppingCart sc = (ShoppingCart) session.getAttribute("shoppingCart"); if (cart == null) { cart = new ShoppingCart(); session.setAttribute("shoppingCart", cart); } ... // do something with your shopping cart object UNIT-5 WT

194 HttpSession Methods public String getId() public boolean isNew()
public long getCreationTime() public long getLastAccessedTime() public int getMaxInactiveInterval() public void setMaxInactiveInterval(int secs) public void invalidate() UNIT-5 WT

195 Associate Info w/ Session
HttpSession session = request.getSession(true); session.setAttribute("referringPage", request.getHeader("Referer")); ShoppingCart cart = (ShoppingCart)session.getAttribute("previousItems"); if (cart == null) { cart = new ShoppingCart(); session.setAttribute("previousItems", cart); }String itemID = request.getParameter("itemID"); if (itemID != null) { cart.addItem(Catalog.getItem(itemID)); } UNIT-5 WT

196 Session Termination Automatic! After a long enough interval (getMaxInactiveInterval) UNIT-5 WT

197 Session Tracking Servlet Container Request Amazon Session ID = 123XYZ
Shopping Cart sc [item 1=324] Request Amazon Servlet Container UNIT-5 WT

198 Session Tracking Servlet Container Amazon Response:
Session ID = 123XYZ Shopping Cart sc [item 1=324] Amazon Response: Set-Cookie: sid=123XYZ Servlet Container UNIT-5 WT

199 Session Tracking Servlet Container Request: Set-Cookie: sid=123XYZ
Session ID = 123XYZ Shopping Cart sc [item 1=324] Amazon Servlet Container UNIT-5 WT

200 Session Tracking Servlet Container Request: Set-Cookie: sid=123XYZ
Session ID = 123XYZ Shopping Cart sc [item 1=324 item 2=115] Amazon Servlet Container UNIT-5 WT


Download ppt "WEB TECHNOLOGIES – Unit V"

Similar presentations


Ads by Google