You are on page 1of 34

Java Servlets

-by Ayush Thakur & Shivanshu Bansal

Servlets are programs that run on a Web server and build Web pages. Building Web pages on the fly is useful (and commonly done) for a number of reasons: The Web page is based on data submitted by the user. For example the results pages from search engines are generated this way, and programs that process orders for e-commerce sites do this as well.

The data changes frequently. For example, a weatherreport or news headlines page might build the page dynamically, perhaps returning a previously built page if it is still up to date. The Web page uses information from corporate databases or other such sources. For example, you would use this for making a Web page at an on-line store that lists current prices and number of items in stock.

Java Servlets technology provides an HTTPbased request and response paradigm on web servers. Java Servlets can handle generic service requests and respond to the clients requests. Java Servlets are used in embedded systems, wireless communication, and any other generic request/response application. The Common Gateway Interface (CGI) was a popular technology used to generate dynamic HTTP web contents in the mid-1990s.

Efficient :With traditional CGI, a new process is started for each HTTP request. If the CGI program does a relatively fast operation, the overhead of starting the process can dominate the execution time. With servlets, the Java Virtual Machine stays up, and each request is handled by a lightweight Java thread, not a heavyweight operating system process. Similarly, in traditional CGI, if there are N simultaneous request to the same CGI program, then the code for the CGI program is loaded into memory N times. With servlets, however, there are N threads but only a single copy of the servlet class.

Convenient. Hey, you already know Java. Why learn Perl too? Besides the convenience of being able to use a familiar language, servlets have an extensive infrastructure for automatically parsing and decoding HTML form data, reading and setting HTTP headers, handling cookies, tracking sessions, and many other such utilities.

Powerful. Java servlets let you easily do several things that are difficult or impossible with regular CGI. For one thing, servlets can talk directly to the Web server (regular CGI programs can't). This simplifies operations that need to look up images and other data stored in standard places. Servlets can also share data among each other, making useful things like database connection pools easy to implement.

Portable. Servlets are written in Java and follow a wellstandardized API. Consequently, servlets written for, say IPlanet Enterprise Server can run virtually unchanged on Apache, Microsoft IIS, or WebStar. Servlets are supported directly or via a plugin on almost every major Web server. Inexpensive. There are number of inexpensive Web servers available that are good for "personal" use or lowvolume Web sites.

A Servlet component can delegate the requests to its back-end tier such as a database management system, RMI, EAI, or other Enterprise Information System (EIS). A Servlet is deployed as a middle tier just like other web components such as JSP components. The Servlet components are building block components, which always work together with other components such as JSP components, JavaBean components, Enterprise Java Bean (EJB) components, and web service components. A Servlet component is also a distributed component, which can provide services to remote clients and also access remote resources.

A Java Servlet application is supported by its Servlet container. The Apache Tomcat web server is the official reference implementation of Servlet containers, supporting Servlets and JSP.

The Java Servlet is a server-side web component that takes a HTTP request from a client, handles it, talks to a database, talks to a JavaBean component, and responds with a HTTP response or dispatches the request to other Servlets or JSP components. Servlets can dynamically produce text-based HTML markup contents and binary contents as well contents based on the clients request.

A Java Servlet is a typical Java class that extends the abstract class HttpServlet. The HttpServlet class extends another abstract class called GenericServlet. The GenericServlet class implements three interfaces: javax.servlet.Servlet, javax.servlet.ServletConfig, and java.io.Serializable.

A Servlet has a lifecycle just like a Java applet. The lifecycle is managed by the Servlet container. Three methods are central to the life cycle of a servlet. These are init(), service() and destroy(). They are implemented by every servlet and are invoked at specific times by te server.

Firstly, let us assume that a user enters a URL to a web browser. The browser will then generate an HTTP request for this URL. This request is sent to the appropriate server. Second, 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.

Third, the server now invokes the init() method of the servlet. This method is invoked only when the servlet is first loaded into the memory. It is possible to pass initial parameters to the servlet so it may configure itself.

Fourth, the server invokes the service() method of the servlet. This method is called to process the HTTP request. The servlet to read the data that has been provided in the HTTP request. It may also formulate an HTTP response for the client. The servlet remains in the servers address space and is available to process any other HTTP request received from the client. It is called for each HTTP request.

Finally, the server may decise to unload the servlet from the memory. The server calls the destroy() method to relinquish any resources such as file handles that are allocated for the servlet. The memory allocated for the servlet and its objects can then be garbage collected.

To become familiar with the key servlet components. We will begin by building and testing a simple servlet. The basic steps are as follows: 1. Create and compile the servlet source code. 2. Start Tomcat. 3. Start the web browser and request the servlet.

import java.io.*; import javax.servlet.*; public class HelloServlet extends GenericServlet { public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException{ response.setContentType(text/html); PrintWriter pw= response.getWriter();

pw.println(<B>Hello!); pw.close(); } }

You can download Tomcat through the Sun Microsystems Web site at java.sun.com. The current version is 7.0. . The default location for Tomcat 7.0 is C:\Program Files\Apache Tomcat 7.0\ To start Tomcat, select Start Tomcat in the Start | Programs menu, or run startup.bat from the C:\Program Files\Apache Tomcat 7.0\bin\ directory. When you are done testing servlets, you can stop Tomcat by selecting Stop Tomcat in the Start | Programs menu, or run shutdown.bat.

Your first step is to download software that implements the Java Servlet 2.1 or 2.2 and Java Server Pages 1.0 or 1.1 specifications. You can get a free version from Sun, known as the JavaServer Web Development Kit (JSWDK), at http://java.sun.com/products/servlet/. Next, you need to tell javac where to find the servlet and JSP classes when you compile a servlet file. The JSWDK installation instructions explain this, but it basically amounts to putting servlet.jar and jsp.jar(which come with the JSWDK) on your CLASSPATH. If you've never dealt with the CLASSPATH before, it is the variable that specifies where Java looks for classes

If it is unspecified, Java looks in the current directory and the standard system libraries. If you set it yourself, you need to be sure to include ".", signifying the current directory.

Start a web browser and enter the URL shown here: http://localhost:8080/examples/servlets/HelloServlets OR http://127.0.0.1:8080/examples/servlets/HelloServlets

This can be done because 127.0.0.1 is defined as the IP address of the local machine. You will observe the output of the servlet in the browser display area. And it will contain the string Hello! In bold type.

Two packages contain the classes and interfaces that are required to build servlets. These are javax.servlet and javax.servlet.http.

The javax.servlet package contains a number of classes and interfaces that describe and define the contracts between a servlet class and the runtime environment provided for an instance of such a class by a conforming servlet container.

The javax.servlet.http package contains a number of classes and interfaces that describe and define the contracts between a servlet class running under the HTTP protocol and the runtime environment provided for an instance of such a class by a conforming servlet container

Thank You.