Monday 26 November 2012

Advanced Java Programming - Servlets

Advanced Java Programming - Servlets
Structure
5.1 Introduction
Objectives
5.2 History of Web Application
5.3 Web Architecture
Self Assessment Questions
5.4 Servlet Life Cycle
Self Assessment Questions
5.5 The Java Servlet Development Kit
5.6 Summary
5.7 Terminal Questions
5.1 Introduction
The rise of server-side Java applications is one of the latest and most exciting trends in Java programming. The Java language was originally intended for use in small, embedded devices. Java’s potentially as a server-side development platform had been sadly overlooked until recently.
Businesses in particular have been quick to recognize Java’s potential on the server-side. Java is inherently suited for large client/server applications. The cross platform nature of Java is extremely useful for organizations that have a heterogeneous collection of servers running various flavors of the UNIX and Windows operating systems. Java’s modern, object-oriented, memory-protected design allows developers to cut development cycles and increase reliability. In addition, Java’s built-in support for networking and enterprise APIs provides access to legacy data, easing the transition from older client/server system.
Advanced Java Programming Unit 5
Sikkim Manipal University Page No. 103
Java servlets are a key component of server-side Java development. A servlet is a small pluggable extension to a server that enhances the server’s functionality. Servlets allow developers to extend and customize any Java-enabled Server- a web server, a mail server, an application server or any custom server.
Objectives
In this chapter, you will learn about the:-
 Defining Servlet.
 Servlet Lifecycle.
 Writing Servlet program
5.2 History of Web Application
To understand the advantages of servlets, you must have a basic understanding of how Web browsers and servers cooperate to provide content to a user. Consider a request for a static Web page. A user enters a Uniform Resource Locator (URL) to a browser. The browser generates an HTTP request to the appropriate Web server. The Web server maps this request to a specific file. That file is returned in an HTTP response to the browser. The HTTP header in the response indicates the type of the content. The
Multipurpose Internet Mail Extensions (MIME) are used for this purpose. For example, ordinary ASCII text has a MIME type of text/plain. The Hypertext Markup Language (HTML) source code of a Web page has a MIME type of text/html.
Now consider dynamic content. Assume that an online bookstore uses a database to store information about its business, including book prices, availability, orders, and so forth. It wants to make this information accessible to customers via Web pages. The contents of those Web pages must be dynamically generated, to reflect the latest information in the database.
Advanced Java Programming Unit 5
Sikkim Manipal University Page No. 104
In the early days of the Web, a server could dynamically construct a page by creating a separate process to handle each client request. The process would open connections to one or more databases in order to obtain the necessary information. It communicated with the Web server via an interface known as the Common Gateway Interface (CGI). CGI allowed the separate process to read data from the HTTP request and write data to the HTTP response. A variety of different languages were used to build CGI programs, including C, C++, and Perl.
However, CGI suffered serious performance problems. Creating a separate process for each client request was expensive, in terms of processor and memory resources. It was also expensive to open and close database connections for each client request. In addition, the CGI programs were not platform-independent. Therefore, other techniques were introduced, including servlets.
Servlets offer several advantages over CGI:
 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.
 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.
 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.
 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 that you have seen already.
Advanced Java Programming Unit 5
Sikkim Manipal University Page No. 105
While servlets can be used to extend the functionality of any Java-enabled server, today they are most often used to extend web servers, providing a powerful, efficient replacement for CGI scripts. When you use servlet to create dynamic content for a web page or otherwise extend the functionality of a web server, you are in effect creating a Web application. While a web page merely displays static content and lets the user navigate through that content, a web application provides a more interactive experience. A web application may be as simple as a key word search on a document archive or as complex as an electronic storefront. Web applications are being deployed on the internet and on corporate intranets and extranets, where they have the potential to increase productivity and change role of servlets in any web application it is necessary to understand the architecture of any current web application.
5.3 Web Architecture
 2-tier Architecture
Typical client/server systems are all 2-tiered in nature where the application resides entirely on the client PC and database resides on a remote server. But 2-tier systems have some disadvantages such as:
 The processing load is given to the PC while more powerful server acts as a traffic controller between the application and the database.
 Maintenance is the greatest problem. Imagine a situation where there is a small modification to be done in the application program. Then in case of a 2-tier architecture system, it is necessary to go to each client machine and make the necessary modifications to the programs loaded on them.
That is the reason why the modern web applications are all developed based on 3-tier architecture.
Advanced Java Programming Unit 5
Sikkim Manipal University Page No. 106
 N-tier Architecture
Although the title of this section is given as N-Tier architecture, here the concentration is on the 3-tier architecture. Basic reason for this is that any web application developed based on N-tier architecture functions just similar to typical 3-tier architecture.
 First-Tier:
 Basically the presentation Layer.
 Represented by the GUI kind of thing.
 Middle-Tier :
 Application Logic
 Third-Tier :
 Data that is needed for the application.
The basic idea behind 3-tier architecture is that to separate application logic from the user interface. This gives the flexibility to the design of the application as well as ease of maintenance. If you compare this with 2-tier architecture, it is very clear that in 3-tier architecture the application logic can be modified without affecting the user interface and the database.
 Typical Web Application
A typical web application consists of following steps to complete a request and response.
 Web application will collect data from the user. (First tier)
 Send a request to the web server.
 Run the requested server program. (Second and third tier)
 Package up the data to be presented in the web browser.
 Send it back to the browser for display. (First tier)
Self Assessment Questions
1. Explain the various Tires?
Advanced Java Programming Unit 5
Sikkim Manipal University Page No. 107
5.4 Servlet Life Cycle
Now that you have seen the basic structure of a servlet, let’s review the process by which a server invokes a servlet. This process can be broken down into the nine steps as follows:
1. The server loads the servlet when it is first requested by the client or if configured to do so, at server start-up. The servlet may be loaded from either a local or a remote location using the standard Java class loading facility.
This step is equivalent to the following code:
Class c=Class.forName(“com.sourcestream.MyServlet”);
It should be noted that when referring to servlets, the term load often refers to the process of both loading and instantiating the servlet.
2. The server creates one or more instances of the servlet class. Depending on implementation. The server may create a single instance that services all requests through multiple threads or create a pool of instances from which one chosen to service each new request. This step is equivalent to the following Java code:
Servlet s=(Servlet) c.newInstance (); where ‘c’ is the same Class object created in previous step.
3. The server constructs a ServerConfig object that provides initialization information to the servlet.
4. The server calls the servlet’s init () method, passing the object constructed in step 3 as a parameter. The init () method is guaranteed to finish execution prior to the servlet processing the first request. If the server has created multiple servlet instances (step 2), the init () method is called one time for each instance.
Advanced Java Programming Unit 5
Sikkim Manipal University Page No. 108
5. The server constructs a ServletRequest or HttpServletRequest object from the data included in the client’s request. It also constructs a ServletResponse or HttpServletResponse object that provides methods for customizing the server’s response. The type of object passed in these two parameters depends on whether the servlet extends the GenericServlet class or the HttpServlet class, respectively.
6. The server calls the servlet’s service() method passing the objects constructed in step 5 as parameters. When concurrent requests arrive, multiple service() methods can run in separate threads.
7. The service () method processes the client request by evaluating the ServletRequest or HttpServletRequest object and responds using ServletResponse or HttpServletResponse object.
8. If the server receives another request for this servlet, the process begins again at step 5.
9. When instructed to unload the servlet, perhaps by the server administrator or programmatically by the servlet itself, the server calls the servlet’s destroy() method. The servlet is then eligible for garbage collection.
The above mentioned nine steps illustrate the entire lifecycle of a servlet. The following figure shows the flow of the servlet lifecycle.
Advanced Java Programming Unit 5
Sikkim Manipal University Page No. 109
Self Assessment Questions
2. Explain the life cycle of a Servlet?
Server Loads the Servlet
Server creates one or more instances of the servlet .class
Server calls the init () method of each servlet instance
Servlet request is received
Server selects servlet instance and calls its service ()
Servlet’s service () method processes the request and returns output to client
Servlet waits until next request is received or it is
Server unloads the servlet after calling it’s destroy () method SERVLET LIIFE CYCLE
Advanced Java Programming Unit 5
Sikkim Manipal University Page No. 110
5.5 The Java Servlet Development Kit
The Java Servlet Development Kit (JSDK) contains the class libraries that you will need to create servlets. A utility known as the servletrunner is also included, which enables you to test some of the servlets that you create. We will use this tool to execute the examples in this chapter.
You can 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. Update your Classpath environment variable so that it includes c:\\Jsdk2.0\\lib\\jsdk.jar.
A Simple Servlet
To become familiar with the key servlet concepts, we will begin by building and testing a simple servlet. 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.
The following sections examine each of these steps in detail.
Create and Compile the Servlet Source Code
To begin, create a file named HelloServlet.java that contains the following program:
import java.io.*;
import javax.servlet.*;
public class HelloServlet extends GenericServlet {
public void service(ServletRequest request,
Advanced Java Programming Unit 5
Sikkim Manipal University Page No. 111
ServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("Hello!");
pw.close();
}
}
First, note that this program imports the javax.servlet package, which contains the classes and interfaces required to build servlets. You will learn more about these classes and interfaces later in this chapter. Next, the program defines HelloServlet as a subclass of GenericServlet. The GenericServlet class provides functionality that makes it easy to handle requests and responses.
Inside HelloServlet, the service( ) method (which is inherited from GenericServlet) is overridden. This method handles requests from a client. Notice that the first argument is a ServletRequest object. This enables a servlet to read data that is provided via the client request. The second argument is an ServletResponse object. This enables a servlet to formulate a response for the client.
The call to setContentType( ) establishes the MIME type of the HTTP response. In this program, the MIME type is text/html, which indicates that the browser should interpret the content as HTML source code.
Next, the getWriter( ) method obtains a PrintWriter. Anything written to this stream is sent to the client as part of the HTTP response. Then, println( ) is used to write some simple HTML source code as the HTTP response.
Advanced Java Programming Unit 5
Sikkim Manipal University Page No. 112
Compile this source code and place the HelloServlet.class file in the directory named c:\\Jsdk2.0\\examples. This ensures that it can be located by the servletrunner utility.
Start the servletrunner Utility
Open a command prompt window and type servletrunner to start that utility. This tool listens on port 8080 for incoming client requests.
Start a Web Browser and Request the Servlet
Start a Web browser and enter the URL shown here:
http://localhost:8080/servlet/HelloServlet
Alternatively, you may enter the URL shown here:
http://127.0.0.1:8080/servlet/HelloServlet
This can be done because 127.0.0.1 is defined as the IP address of the local machine.
You should observe the output of the servlet in the browser display area. It should contain the string Hello! in bold type.
Note
The examples in this chapter assume that the servletrunner and the Web browser execute on the same machine. However, these two applications can be installed on different machines. In that case, the URLs must be changed to identify the machine on which servletrunner is executing.
5.6 Summary
 Different Web Architecture are:
o Simple Web Request-Response Paradigm.
o 2-tier Architecture.
o N-tier Architecture.
o Typically Web Application
Advanced Java Programming Unit 5
Sikkim Manipal University Page No. 113
5.7 Terminal Questions
1. Explain 2-tier and N-tier architecture?
2. Explain the life cycle of a Servlet?
3. What are the uses of a Servlet?

1 comment:

  1. Thanks for all the updates. I am basically not a programmer and I am comparatively new to Java technology , so I was wondering what all topics should be covered up if i have to start java from the start and has any one
    studied or got any info regarding this 6 week java training online course http://www.wiziq.com/course/12145-the-6-week-complete-java-primer-with-training-certificate and should we also have knowledge of C language before we further move on to Advance Java topics??

    ReplyDelete