Servlet Container

A servlet container is nothing but a compiled, executable program. The main function of the container is to load, initialize and execute servlets. The servlet container is the official Reference Implementation for the Java Servlet and JavaServer Pages technologies. The Java Servlet and JavaServer Pages specifications are developed by Sun under the Java Community Process. A container handles large number of requests as it can hold many active servlets, listeners etc. It is interesting to note here that the container and the objects in a container are multithreaded. So each object must be thread safe in a container as the multiple requests are being handled by the container due to the entrance of more than one thread to an object at a time. Note : A Servlet container may run stand alone i.e. without a web server or even on another host. We can categorize the servlet containers as: I. A simple servlet container is not fully functional and therefore it can only run very simple servlets and does the following :
• • •

Wait for HTTP request. Construct a ServletRequest object and a ServletResponse object. If the request is for a static resource, invoke the process method of the StaticResourceProcessor instance, passing the ServletRequest and ServletResponse objects. If the request is for a servlet, load the servlet class and invoke its service method, passing the ServletRequest and ServletResponse objects. Note that in this servlet container, the servlet class is loaded every time the servlet is requested.

II. A fully functional servlet container additionally does the following for each HTTP request for a servlet:
• • • •

When the servlet is called for the first time, load the servlet class and call its init method (once only). For each request, construct an instance of javax.servlet.ServletRequest and an instance of javax.servlet.ServletResponse. Invoke the servlet's service method, passing the ServletRequest and ServletResponse objects. When the servlet class is shut down, call the servlet's destroy method and unload the servlet class.

Now lets see what a servlet container does for each HTTP request for a servlet, in general :
• • • •

The servlet container loads the servlet class and calls the init method of the servlet as soon as the servlet is called for the first time. Then this container makes an instance of javax.servlet.ServletRequest and javax.servlet.ServletResponse for each request. Then it passes the ServletRequest and ServletResponse objects by invoking the servlet's service method. Finally, it calls the destroy method and unload the servlet class when the servlet class is to be shut down.

What is Java Servlets?
Servlets are server side components that provide a powerful mechanism for developing server side programs. Servlets provide component-based, platform-independent methods for building Web-based applications, without the performance limitations of CGI programs. Unlike proprietary server extension mechanisms (such as the Netscape Server API or Apache modules), servlets are server as well as platform-independent. This leaves you free to select a "best of breed" strategy for your servers, platforms, and tools. Using servlets web developers can create fast and efficient server side application which can run on any servlet enabled web server. Servlets run entirely inside the Java Virtual Machine. Since the Servlet runs at server side so it does not checks the browser for compatibility. Servlets can access the entire family of Java APIs, including the JDBC API to access enterprise databases. Servlets can also access a library of HTTP-specific calls, receive all the benefits of the mature java language including portability, performance, reusability, and crash protection. Today servlets are the popular choice for building interactive web applications. Third-party servlet containers are available for Apache Web Server, Microsoft IIS, and others. Servlet containers are usually the components of web and application servers, such as BEA WebLogic Application Server, IBM WebSphere, Sun Java System Web Server, Sun Java System Application Server and others. Servlets are not designed for a specific protocols. It is different thing that they are most commonly used with the HTTP protocols Servlets uses the classes in the java packages javax.servlet and javax.servlet.http. Servlets provides a way of creating the sophisticated server side extensions in a server as they follow the standard framework and use the highly portable java language. HTTP Servlet typically used to:
• • •

Priovide dynamic content like getting the results of a database query and returning to the client. Process and/or store the data submitted by the HTML. Manage information about the state of a stateless HTTP. e.g. an online shopping car manages request for multiple concurrent customers.

Methods of Servlets
A Generic servlet contains the following five methods: init() public void init(ServletConfig config) throws ServletException The init() method is called only once by the servlet container throughout the life of a servlet. By this init() method the servlet get to know that it has been placed into service. The servlet cannot be put into the service if
• •

The init() method does not return within a fix time set by the web server. It throws a ServletException

Parameters - The init() method takes a ServletConfig object that contains the initialization parameters and servlet's configuration and throws a ServletException if an exception has occurred. service() public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException Once the servlet starts getting the requests, the service() method is called by the servlet container to respond. The servlet services the client's request with the help of two objects. These two objects javax.servlet.ServletRequest and javax.servlet.ServletResponse are passed by the servlet container. The status code of the response always should be set for a servlet that throws or sends an error. Parameters - The service() method takes the ServletRequest object that contains the client's request and the object ServletResponse contains the servlet's response. The service() method throws ServletException and IOExceptions exception. getServletConfig() public ServletConfig getServletConfig() This method contains parameters for initialization and startup of the servlet and returns a ServletConfig object. This object is then passed to the init method. When this interface

is implemented then it stores the ServletConfig object in order to return it. It is done by the generic class which implements this inetrface. Returns - the ServletConfig object getServletInfo() public String getServletInfo() The information about the servlet is returned by this method like version, author etc. This method returns a string which should be in the form of plain text and not any kind of markup. Returns - a string that contains the information about the servlet destroy() public void destroy() This method is called when we need to close the servlet. That is before removing a servlet instance from service, the servlet container calls the destroy() method. Once the servlet container calls the destroy() method, no service methods will be then called . That is after the exit of all the threads running in the servlet, the destroy() method is called. Hence, the servlet gets a chance to clean up all the resources like memory, threads etc which are being held.

Life cycle of Servlet
The life cycle of a servlet can be categorized into four parts: 1. Loading and Inatantiation: The servlet container loads the servlet during startup or when the first request is made. The loading of the servlet depends on the attribute <load-on-startup> of web.xml file. If the attribute <load-on-startup> has a positive value then the servlet is load with loading of the container otherwise it load when the first request comes for service. After loading of the servlet, the container creates the instances of the servlet. 2. Initialization: After creating the instances, the servlet container calls the init() method and passes the servlet initialization parameters to the init() method. The init() must be called by the servlet container before the servlet can service any request. The initialization parameters persist untill the servlet is destroyed. The init() method is called only once throughout the life cycle of the servlet. The servlet will be available for service if it is loaded successfully otherwise the servlet container unloads the servlet.

3. Servicing the Request: After successfully completing the initialization process, the servlet will be available for service. Servlet creates seperate threads for each request. The sevlet container calls the service() method for servicing any request. The service() method determines the kind of request and calls the appropriate method (doGet() or doPost()) for handling the request and sends response to the client using the methods of the response object. 4. Destroying the Servlet: If the servlet is no longer needed for servicing any request, the servlet container calls the destroy() method . Like the init() method this method is also called only once throughout the life cycle of the servlet. Calling the destroy() method indicates to the servlet container not to sent the any request for service and the servlet releases all the resources associated with it. Java Virtual Machine claims for the memory associated with the resources for garbage collection.

Life Cycle of a Servlet

4 five new request attributes has been added for providing extra information during a RequestDispatcher forward() call.1 and J2SE 1.4 the SingleThreadModel interface has been deprecated.servlet.request_uri o javax.path_info o javax.4 In this tutorial you will learn the new features added in Servlet 2. 4.servlet.Features of Servlets 2. This features has been added is Servlet 2. Upgraded supports for Http. setLocale().forward.4 four new methods are added in the ServletRequest o getRemotePort(): It returns the IP source port of the client.4 to know the true original request URI. This method helps us to pass a charset parameter to setContentType(String) or passing a Locale to setLocale(Locale). J2SE.4 has added two new methods in the ServletResponse interface. and the method getContentType() provides a way to view the generated type string.3. o getLocalAddr(): It returns the IP address on which the request was recieved.forward. getContentType(): It is responsible for returning the response's content type.forward.4 depends on Http1. o getLocalName(): It returns the host name on which the request was recieved. 1. SingleThreadModel interface has been deprecated: In Servlet 2. The content type can be dynamically set with a combination of setContentType(). Additional ServletRequest methods : In Servlet 2.servlet. Servlet 2.servlet. . and J2EE: Servlet 2.forward. and setCharacterEncoding() calls.servlet.servlet_path o javax.context_path o javax.forward. o setCharacterEncoding(String encoding): The purpose of this method is to set the response's character encoding.charset=UTF-8") as setCharacterEncoding() method pairs with the pre-existing getCharacterEncoding() method to manipulate and view the response's character encoding. New features has been added in RequestDispatcher: In Servlet 2.query_string o 5.4. 2. We can now avoid setting the charset in the setContentType("text/html. o getLocalPort(): It returns the IP port number. New Support for Internationalization and charset choice: To provide support of internationization. 3. The following request attributes are: o javax.

4.6.2 and 2. Welcome file behavior and Classloading has been clarified: In servlet 2. The web. Annotations are mark code in such a way that code processors may alter their behavior based on the metadata information. we can now use an asterisk in a <servlet-name> which will represent all servlets as well as JSP.5 introduces several small changes to the web.5 is JDK 1.logout() has been added in Servlet 2. an improved for loop etc are guaranteed available to Servlet 2. Features of Servlet 2.3 deployment descriptor formats. etc. It is not necessary that all web servers and application servers support the features of Servlet 2. All the available features of JDK1. 7.0 support Servlet 2.xml file to make it more convenient to use. Servet 2.4. but all new elements are solely specified in Schema.4 welcome file can be a servlet. autoboxing.xml convenience: Servlet 2.5 can't be used in versions below than JDK1. Dependency on J2SE 5.5 This version has been released on September 26.5 programmers. Still most of the popular containers like Tomcat 5.5. <filter-mapping> <filter-name>FilterName</filter-name> . For example while writing a <filter-mapping>.) with metadata information. methods. 3.0: The minimum platform requirement for Servlet 2.5. Now session allows zero or negative values in the <session-timeout> element to indicate sessions should never time out. 2005 by the Sun MicroSystems. The list of the added features is given below: 1. 2.5. If the object in the session can't be serialize in a distributed environment then it must throw an IllegalArgumentException. 8. Support For annotations: Annotations provide a mechanism for decorating java code constructs (classes. HttpSession details and interaction with logins has been clarified: The new method HttpSession. fields.5 like generics. Several web.5 and JBoss 4.xml file now uses XML Schema: Version 2. Previously we used to do <filter-mapping> <filter-name>FilterName</filter-name> <servlet-name>FilterName</servlet-name> </filter-mapping> Now.4 servers must still accept the 2.

2. A Handful of removed restrictions: Servlet 2.<servlet-name>*</servlet-name> </filter-mapping> Previously in <servlet-mapping> or <filter-mapping> there used to be only one <url-pattern>. run anywhere (WORA) program. Advantages of Java Servlets 1. We can develop a servlet on Windows machine running the tomcat server or any other server and later we can deploy that servlet effortlessly on any other operating system like Unix server running on the iPlanet/Netscape Application server. Some edge case clarifications: The servlet 2. 6. Now it has removed the restriction that the <error-page> could not call the setStatus() method to alter the error code that triggered them.4 specification says that before calling request. So servlets are write once. Servlet 2. 7.xml. 5.setCharacterEncoding(). In session tracking. However there is no such clarification given why it is so. many more facilities added in web. 5. like <servlet-mapping> <servlet-name>abc</servlet-name> <url-pattern>/abc/*</url-pattern> <url-pattern>/abc/*</url-pattern> </servlet-mapping> Apart from these changes. 4.getReader() we must call request. 4. Powerful We can do several things with the servlets which were difficult or even impossible to do with CGI.5 removed a few restrictions around error handling and session tracking. 3. Portability Powerful Efficiency Safety Integration Extensibilty Inexpensive Each of the points are defined below: Portability As we know that the servlets are written in java and follow well known standardized APIs so they are highly portable across operating systems and server implementations. but now we can have multiple <url-pattern>. for example the servlets can talk directly to the web server while the CGI .5 eased a rule that a servlet called by RequestDispatcher include() couldn't set response headers.

Integration Servlets are tightly integrated with the server. It can do many other things which are difficult to implement in the CGI programs. Earlier CGI was developed to provide server side capabilities to the web applications. it remains in the server's memory as a single object instance. Efficiency As compared to CGI the servlets invocation is highly efficient. but in later date it can be extended for another type of servlets. As it stands today. Built from ground up using Sun's write once run anywhere technology java servlets provide excellent framework for server side processing. Safety As servlets are written in java. and MIME type mapping etc. If any exception occurs then it will throw an exception. Servlet can use the server to translate the file paths. Extensibility The servlet API is designed in such a way that it can be easily extensible. However with servlets there are N threads but only a single copy of the servlet class. So by using the free available web servers you can add servlet support to it. scalability and reusability issues make it less than optimal solutions. perform logging. Inexpensive There are number of free web servers available for personal use or for commercial purpose. check authorization. . Java's automatic garbage collection and a lack of pointers means that servlets are generally safe from memory management problems. Servlets can share data among each other. the servlet API support Http Servlets.programs can't do. They can maintain the session by using the session tracking mechanism which helps them to maintain information from request to request. they even make the database connection pools easy to implement. Multiple concurrent requests are handled by separate threads so we can say that the servlets are highly scalable. In servlets we can easily handle the errors due to Java's exception handling mechanism. Advantages of Servlets over CGI Servlets are server side components that provides a powerful mechanism for developing server web applications for server side. When the servlet get loaded in the server. servlets inherit the strong type safety of java language. Java Servlets changes all that. Although CGI played a major role in the explosion of the Internet. Web servers are relatively expensive. its performance.

For example if you develop an web application in windows machine running Java web server. you can easily run the same on apache web server (if Apache Serve is installed) without modification or compilation of code. They are: 1. Performance Due to interpreted nature of java. But the java servlets runs very fast. Since the servlet runs on server side so it does not depend on browser compatibility. In addition. JAVA SERVLETS – An Overview This tutorial covers concepts pertaining to Server side programming in general and Java Servlets in particular. But in case of servlets initialization takes place first time it receives a request and remains in memory till times out or server shut downs. 4. These are due to the way servlets run on web server. After servlet is loaded. programs written in java are slow. It also guides the student through a step by step approach as how to install the above Server. Platform Independence Servlets are written entirely in java so these are platform independent. Platform independency of servlets provide a great advantages over alternatives of servlets. Servlet runs entirely inside the Java Virtual Machine. Servlets are also benefited with Java Security Manager. to handle a new request it simply creates a new thread and runs service method of servlet. Servlets inherits all these features and emerged as a very powerful web server extension. Secure Servlets are server side components. Safety Java provides very good safety features like memory management. configure it and create the relevant folders and files.Using servlets web developers can create fast and efficient server side applications and can run it on any servlet enabled web server. After completion of this . Servlets have a number of advantages over CGI and other API's. 3. Servlets can run on any Servlet enabled web server. exception handling etc. So the java servlets take all these advantages and can be extended from existing class to provide the ideal solutions. 2. well-designed and object oriented language which can be extended or polymorphed into new objects. In comparison to traditional CGI scripts which creates a new process to serve the request. For any program initialization takes significant amount of time. it demonstrates as how to create and compile a simple Servlet and finally execute it using a Web Server such as an Apache Tomcat Server. 5. so it inherits the security provided by the web server. Extensibility Java Servlets are developed in java which is robust.

Why Server Side Programming? Though it is technically feasible to implement almost any business logic using client side programs. logically or functionally it carries no ground when it comes to enterprise applications (e. . e-shopping etc. If you can recollect. Configuration and running Servlets Introduction to Server Side Programming All of us (or most of us) would have started programming in Java with the ever famous “Hello World!” program. Installation. No doubt. this is the easiest and fastest way to write.000 programs! In addition. going by the client side programming logic.000 customers would mean that each customer should have a copy of the program(s) in his or her PC which translates to 10. Figure-1 illustrates Server side architecture in the simplest terms.java extension and later compiled the program using javac and then executed the class file with java.g. Introduction to Server Side Programming 2. air ticketing. a bank having 10. This means that you write. compile and also execute the program on a client machine (e. The answer to most of the issues cited above is – “Server Side Programming”. concurrent access and manipulations to the database which simply cannot be handled by client side programs. there are issues like security. To further explain. the student would not only be familiar with Servlet fundamentals.). 1. But. 1. but also get hands-on experience in terms of creating and executing simple Servlet programs. Your PC). Introduction to Java Servlets 3. banking.g.tutorial. compile and execute programs. Apart from introducing you to the language basics. resource pooling. we saved this file with a . it has little practical significance when it comes to real world programming. the point to be noted about this program is that – “It is a client side program”.

3. session management. iii. Migrating to newer versions. Issues relating to enterprise applications like resource management.2.g. the objective of server side programs is to centrally manage all programs relating to a particular application (e.g. displaying transaction information of credit card or debit card depending on user’s choice). security and performance are managed by service side applications. New functionalities to existing programs can be added at the server side which the clients’ can advantage without having to change anything from their side. adding patches. design patterns. v. They are portable and possess the capability to generate dynamic and userbased content (e. Insurance. v. Types of Server Side Programs i. iv. ii. ii. concurrency. Banking. architectures. All programs reside in one machine called the Server. To summarize. switching to new databases can be done at the server side without having to bother about clients’ hardware or software capabilities. Any number of remote machines (called clients) can access the server programs. Advantages of Server Side Programs The list below highlights some of the important advantages of Server Side programs. e- . iii. i. Active Server Pages (ASP) Java Servlets Java Server Pages (JSPs) Enterprise Java Beans (EJBs) PHP iv.

http packages provide the necessary interfaces and classes to work with servlets. etc). Pentium II. Examples for Web Servers include Apache’s Tomcat Server and Macromedia’s JRun. 1. MS Internet Explorer and an internet connection) can experience the power and performance of a Server (e. server programs are not only portable but also possess the capability to generate dynamic responses based on user’s request. The skeleton of a servlet is given in Figure . Clients with bare minimum requirement (e.g. Unix Server. The javax. we will get acquainted with Servlet fundamentals and other associated information required for creating and executing Java Servlets. More importantly. Basic Servlet Structure As seen earlier. other methods such as init. etc) from a remote location without having to compromise on security or speed. Java servlets are server side programs or to be more specific. IBM Mainframe. Windows XP Professional. In the forthcoming sections.servlet. Web Servers include IBM’s Weblogic and BEA’s Websphere server.servlet and javax. In addition.g. service and destroy also called as life cycle methods might be used which will be discussed in the following section. Servlets generally extend the HttpServlet class and override the doGet or the doPost methods. Introduction to Java Servlets Java Servlets are server side Java programs that require either a Web Server or an Application Server for execution. web applications that run on servers that comply HTTP protocol. Examples for other Server programs include Java Server Pages (JSPs) and Enterprise Java Beans (EJBs).shopping.

. It is in a sense equivalent to the finally method. service or doGet /doPost). More often than not. Finally. You can reset or close references / connections done earlier in the servlet’s methods (e. However. it is the init method which is called. A Servlet’s Life Cycle The first time a servlet is invoked. After this method is called.g. And remember that this is called only once during the lifetime of a servlet. The service method in turn calls the doGet or doPost methods (whichever the user has overridden).2. please note that it is not mandatory to override all these methods. the servlet ceases to exist for all practical purposes. you can put all your initialization code here. it is the doGet or doPost method used with one or more of the other life cycle methods. So. the servlet calls the destroy method. This method next calls the service method. init.

3. A Servlet Program .

.

keep refreshing the browser (F5 in Windows). .).Output Screens To appreciate the execution of the servlet life cycle methods. what actually happens is – with each refresh.3. The procedure to run the servlets using a Web Server will be demonstrated in the next section (1. In the background. the doGet method is called which increments i’s value and displays the current value. Find below the screen shots (Figures 5 through 7) captured at random intervals.

.

but also the most preferred WebServer across the world. Throughout this tutorial. The current version of Tomcat Server is 6.sun. 2.org.0 (as of November 2007).apache. 1.com. The current version of JDK is 6.5 and Java Server Pages (JSPs) 2. Apache’s Tomcat Server is free software available for download @ www. Installation of Tomcat Server and JDK As mentioned earlier. we will be using Apache’s Tomcat server as the WebServer.Installation. fast. you can refer to the abundant documentation repository available on this site. Like Tomcat.1 specifications. we will see as how to install a WebServer. In case of doubt or confusion. Configuring Tomcat Server . It is the ideal server for learning purpose. powerful and portable. Configuration and running Servlets In this section. Important software required for running this server is Sun’s JDK (Java Development Kit) and JRE (Java Runtime Environment).java. This Server supports Java Servlets 2. very less memory footprint.0. Tomcat is not only an open and free server. configure it and finally run servlets using this server. JDK is also free and is available for download at www. A few reasons we can attribute for its popularity is – Easy to install and configure.

Step 2 • Open your Browser (e. c:\program file\java\jdk1.0\bin and double click on tomcat6 OR • Go to Start->Programs->Apache Tomcat 6. Though this explanation is specific to Tomcat. JRun. MS Internet Explorer) and type the following URL : http://localhost:8080/ (If you have NOT changed the default port #) In either case. Step 1 – Compile your servlet program .Set JAVA_HOME variable .g. MS Internet Explorer) and type the following URL : http://localhost/ (If you have changed to port # to 80) OR • Open your Browser (e. (e.g. o Specify the Server Port – You can change the server port from 8080 to 80 (if you wish to) by editing the server. The path would be something like this – c:\program files\apache software foundation\tomcat6\conf\server.xml 3.0). Compile and Execute your Servlet This section through a step by step (and illustration) approach explains as how to compile and then run a servlet using Tomcat Server. you should get a page similar to the one in Figure-8 which signifies that the Tomcat Server is successfully running on your machine. You will notice an icon appear on the right side of your Status Bar. Caucho’s Resin). you can test as whether the server is successfully installed as follows: Step 1 • Go to C:\Program Files\Apache Software Foundation\Tomcat 6. 4.6.g. Right click on this icon and click on Start service.You have to set this variable which points to the base installation directory of JDK installation. You can either set this from the command prompt or from My Computer -> Properties -> Advanced -> Environment Variables. Run Tomcat Server o Once the above pre-requisites are taken care.0 -> Monitor Tomcat. the procedure explained holds true for other Web servers too (e.xml file in the conf folder.g.

The first step is to compile your servlet program. airline_tickets_booking.etc). Step 2 – Create your Web application folder The next step is to create your web application folder.0\lib\servlet-api. the easiest one is to use this jar file available with the Tomcat server (C:\Program Files\Apache Software Foundation\Tomcat 6. . It has to be exclusively added in the CLASSPATH. But.servlet. The procedure is no different from that of writing and compiling a java program.jar. For demo purpose.jar). you will be able to successfully compile your servlet program.0\webapps. Step 3 – Create the WEB-INF folder The third step is to create the WEB-INF folder. Figure-10 shows the WEB-INF folder being placed under the demo-examples folder.g.depicts the same. the point to be noted is that neither the javax. The path would be similar or close to this . The set of classes required for writing servlets is available in a jar file called servlet-api.C:\Program Files\Apache Software Foundation\Tomcat 6.* is part of the standard JDK. This folder should be created under your web application folder that you created in the previous step.http. Ensure that the class file is created successfully. shopping_cart. However. Figure. But the most important criterion is that this folder should be created under webapps folder.servlet. You need to include this path in CLASSPATH. Once you have done this. The name of the folder can be any valid and logical name that represents your application (e. This jar file can be downloaded from several sources.* nor the javax. let us create a folder called demo-examples under the webapps folder. bank_apps.

xml and classes folder are created under the WEB-INF folder.Figure – WEB-INF folder inside web application folder Step 4 – Create the web. Step 5 – Copy the servlet class to the classes folder We need to copy the servlet class file to the classes folder in order to run the servlet that we created.g. All you need to do is copy the servlet class file (the file we obtained from Step 1) to this folder.xml file and the classes folder. Figure-11 shows this file and folder being placed under the WEB-INF folder.xml file and the classes folder Note – Instead of creating the web. Ensure that the web.0\webapps\examples\WEB-INF) and paste it into this folder.xml file and the classes folder The fourth step is to create the web. . Figure-12 shows the servlet_lifecycle (refer section 1.) class being placed in the classes folder.xml file an easy way would be to copy an existing web. You can later edit this file and add relevant information to your web application. C:\Program Files\Apache Software Foundation\Tomcat 6.xml file (e.2.3. Figure – web.

.xml file. Figure– Include servlet’s name using the <servlet> </servlet> tag Note – The servlet-name need not be the same as that of the class name. You can give a different name (or alias) to the actual servlet. Open the web. including the servlet’s name and then mentioning the url pattern.Figure – servlet class file placed under classes folder Step 6 – Edit web. This is one of the main reasons as why this tag is used for. Figure-14 shows the url pattern entry for our current servlet. The url pattern defines as how a user can access the servlet from the browser. Next.xml to include servlet’s name and url pattern This step involves two actions viz. include the url pattern using the <servlet-mapping> </servlet-mapping> tag.xml file and include the servlet’s name as shown in Figure-13. Let us first see as how to include the servlet’s name in the web.

running the Web Server and then executing the servlet. open your web browser and enter the url as specified in the web. This means that this path is w. After ensuring that the web server is running successfully.3.xml file. you can run your servlet. your web applications folder (demo-examples in this case). Step 7 – Run Tomcat server and then execute your Servlet This step again involves two actions viz.3. To run the server. follow the steps explained in Section 1. To do this.Figure – Include url-pattern using the <servlet-mapping> </servlet-mapping> tag Note – Please remember that the path given in the url-pattern is a relative path.t.r. The complete url that needs to be entered in the browser is: http://localhost/demo-examples/servlet_lifecycle .

jar . For Windows XP. you can keep refreshing the browser window and see for yourself as how i value is incremented (a proof that the doGet is called every time you re-invoke a servlet). How to Run a Servlet To run a servlet one should follow the steps illustrated below: • • Download and Install the tomcat server: Install the tomcat server in a directory in which you want to install and set the classpath.for the variable JAVA_HOME in the environment variable. To get details about the installation process and setting the classpath click the link Tomcat installation.jar For Windows 2000 and NT Go to Start->Settings->Control Panel->System->Environment Variables->New button and Set the values as Variable Name: CLASSPATH Variable Value: C:\Program Files\Java\Tomcat 6.0\lib\servlet-api. Set the class for the jar file: Set the classpath of the servlet-api.2.Figure – Our servlet’s output! Eureka! Here’s the output of our first servlet. we finally got an output! As mentioned in Section 1. Go to Start->Control Panel->System->Advanced->Environment Variables->New button and Set the values as Variable Name: CLASSPATH Variable Value: C:\Program Files\Java\Tomcat 6.0\lib\servlet-api. After a long and pain staking effort.3.jar file in the variable CLASSPATH inside the environment variable by using the following steps.

servlet. import javax.setContentType("text/html").xml file in a directory structure. The doGet() method takes two arguments first is HttpServletRequest object and the second one is HttpServletResponse object and this method throws the ServletException.*. HttpServletRequest object represents the client's request and the HttpServletResponse represents the servlet's response.getWriter(). open a browser window and type the URL http://localhost:8080/directory (folder name of your application) name/servler name and press enter. Whenever the user sends the request to the server then server generates two obects. .IOException{ response. HttpServletResponse res ponse) throws ServletException. first is HttpServletRequest object and the second one is HttpServletResponse object. It is the standard MIME content type for the Html pages. To display the output on the browser we use the println() method of the PrintWriter class.*.println("<head><title>Hello World</title></title>").servlet.http.• • • Create a java source file and a web. put the compiled file (. Writing Servlet Hello World We should start understanding the servlets from the beginning. public class HelloWorld extends HttpServlet{ public void doGet(HttpServletRequest request. The server invokes doGet() method whenever web server recieves the GET request from the servlet. pw.println("<html>"). As we know that the our servlet extends the HttpServlet and overrides the doGet() method which it inherits from the HttpServlet class. If everything is correct your servlet will run. pw. Inside the doGet(() method our servlet has first used the setContentType() method of the response object which sets the content type of the response to text/html.*. import javax. After that it has used the method getWriter() of the response object to retrieve a PrintWriter object. The code the program is given below: import java. PrintWriter pw = response. Each time the user visits this page it will display "Hello World" to the user. Compile the java source file. Lets start by making one program which will just print the "Hello World" on the browser. Start the tomcat server.io.class file) in the classes folder of your application and deploy the directory of your application in the webapps folder inside the tomcat directory.

pw.xml file for this program: <?xml version="1.dtd"> --> <web-app> <servlet> <servlet-name>Hello</servlet-name> <servlet-class>HelloWorld</servlet-class> </servlet> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/HelloWorld</url-pattern> </servlet-mapping> </web-app> The output of the program is given below: . Inc.println("<h1>Hello World</h1>").println("</body></html>"). } } web.com/dtd/web-app_2_3.sun.pw.0" encoding="ISO-8859-1"?> <!--<!DOCTYPE web-app PUBLIC "-//Sun Microsystems. pw.3//EN" "http://java.println("<body>").//DTD Web Application 2.

public class DisplayingDate extends HttpServlet{ public void doGet(HttpServletRequest request. As we know that the our servlet extends the HttpServlet and overrides the doGet() method which it inherits from the HttpServlet class. IOException{ PrintWriter pw = response. javax.servlet.//DTD Web Application 2. Inc.*. Whenever the user sends the request to the server then server generates two obects.com/dtd/web-app_2_3. HttpServletRequest object represents the client's request and the HttpServletResponse represents the servlet's response. HttpServletResponse response) throws ServletException. To display the output on the browser we use the println() method of the PrintWriter class. The doGet() method takes two arguments first is HttpServletRequest object and the second one is HttpServletResponse object and this method throws the ServletException.getWriter().util package. } } XML File for this program <?xml version="1. The MIME type tells the browser what kind of data the browser is about to receive. It is very easy to display it on our browser by using the Date class of the java. Date today = new Date().*.3//EN" "http://java. It is the standard MIME content type for the Html pages.println("<b>"+ today+"</b></body>"+ "</html>"). javax.println("<html>"+"<body><h1>Today Date is</h1>"). The code the program is given below: import import import import java. pw. pw.http.*.servlet. The server invokes doGet() method whenever web server recieves the GET request from the servlet. After that it has used the method getWriter() of the response object to retrieve a PrintWriter object.sun. Inside the doGet(() method our servlet has first used the setContentType() method of the response object which sets the content type of the response to text/html.*.Displaying Date in Servlet In this example we are going to show how we can display a current date and time on our browser.util. first is HttpServletRequest object and the second one is HttpServletResponse object. java.0" encoding="ISO-8859-1"?> <!--<!DOCTYPE web-app PUBLIC "-//Sun Microsystems.dtd"> --> .io.

The code of the program is given below: import java.*. Remember to keep the name of the class in such a way that it becomes easy to understand what the program is going to do just by seeing the class name. To display the output use the method getWriter() method of the response object which will in turn return the object of the PrintWriter class. Now use method either doGet() or doPost() to write a logic of the program. The name of the class should follow the naming convention.<web-app> <servlet> <servlet-name>Hello</servlet-name> <servlet-class>DateDisplay</servlet-class> </servlet> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/DateDisplay</url-pattern> </servlet-mapping> </web-app> The output of the program is given below: Simple Counter in Servlet In this example we are going to know how we can make a program on counter which will keep track how many times the servlet has been accessed. Our program logic is simple. . We have to just increment the value of the counter by 1.io. To make this program firstly we have to make one class SimpleCounterInServlet. After making a class define one variable counter which will keep record for how many times the servlet has been accessed. Now display the value of the counter.

servlet.*. .io. IOException { response. pw. javax.import javax.*.IOException. Inside the doGet() method use the method getWriter() method of the response object which will return the PrintWriter object.io. The code of the program is given below: import import import import import java. This object will be shared by all the threads in the container.println("At present the value of the counter is " + counter).http.http.getWriter().*. the value of this counter will be different for each servlet and create a Hashtable object.*. HttpServletResponse res ponse) throws ServletException. public void doGet(HttpServletRequest request.servlet. counter++. In this example firstly we are going to create one class named as HolisticCounterInServlet. } } The output of the program is given below: A Holistic counter in Servlet In this program we are going to make a such a servlet which will count the number it has been accessed and the number of threads created by the server. Now declare a variable counter of int with initial value 0. import javax.util.*. java. javax. java.servlet.setContentType("text/html").servlet.*. public class SimpleCounter extends HttpServlet{ int counter = 0. PrintWriter pw = response.

HttpServletResponse respo nse) throws ServletException.this).getWriter().println("This servlet has been accessed" + counter + "times<br>"). //separate For Each Servlet static Hashtable hashTable = new Hashtable(). PrintWriter pw = response. The init() method accepts an object which implements ServletConfig interface. } } The output of the program is given below: Counter in Init() Method In this program we are going to make a such a servlet which will count and displays the number of times it has been accessed and by reading the init parameter to know from where the counting will begin. IOException { response. hashTable. pw.setContentType("text/html").public class HolisticCounter extends HttpServlet{ int counter = 0. pw. In this program we are going to make use of the init method of the Servlet interface which takes one argument of ServletConfig. You need to parse the String value which you will get from the getInitParameter() method to a Integer. //Shared by all the threa ds public void doGet(HttpServletRequest request.println("There are currently" + hashTable. The code of the program is given below: . counter++.put(this.size() + "threads<br>"). It uses the method getInitParameter() method of the ServletConfig interface to the value of the init parameter initial which we have defined in the deployment descriptor file. Firstly declare a variable counter which will have the initial value of the counter.

servlet.servlet.0" encoding="ISO-8859-1"?> <!--<!DOCTYPE web-app PUBLIC "-//Sun Microsystems.dtd"> --> <web-app> <servlet> <servlet-name>Hello</servlet-name> <servlet-class>CounterInInit</servlet-class> </servlet> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/CounterInInit</url-pattern> </servlet-mapping> </web-app> The output of the program is given below: . HttpServletResponse response) throws ServletException. import javax.sun. counter++.getWriter(). } catch(NumberFormatException e){ counter = 0.*.println("Since loading this servlet has been accessed" + counter + "times"). } } protected void doGet(HttpServletRequest request.parseInt(initValue).io.import java. try{ counter = Integer. import javax. } } web.3//EN" "http://java.getInitParameter("initial").*.http. String initValue = config.*. Inc. public void init(ServletConfig config) throws ServletException{ super. pw. IOException {response.init(config).//DTD Web Application 2.setContentType("text/ht ml"). public class CounterInInit extends HttpServlet { int counter.com/dtd/web-app_2_3. PrintWriter pw = response.xml file for this program: <?xml version="1.

Firstly we will create a class in which there will be doGet() method which takes two objects as arguments.http.getProtocol()+ "<br>"). import javax. pw. pw.servlet.xml file for this program: .getWriter(). pw. first is request object and the second one is of response. IOException { PrintWriter pw = response.println("The scheme used is " + request.*.getServerPort()+ "<br>").getServerName() + "<br>" ). To display the server port number use the method getServerPort().io. import javax. pw.getScheme()). You can also use other methods of the ServletRequest interface like getProtocol() to display the protocol you are using and many more methods depending on your needs. HttpServletResponse response) throws ServletException.*. } } web.servlet.println("The protocol is " + request.println("The server port number is " + request. To display the name of the server you are using use the method getServerName() of the ServletRequest interface.Snooping the server In this program we are going to tell you how can a use servlet to display information about its server.*. The code of the program is given below: import java. public class SnoopingServerServlet extends HttpServlet{ protected void doGet(HttpServletRequest request.println("The server name is " + request.

//DTD Web Application 2.sun. Inc. This method checks whether there are more headers or not.dtd"> --> <web-app> <servlet> <servlet-name>Hello</servlet-name> <servlet-class>SnoopingServerServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/SnoopingServerServlet</url-pattern> </servlet-mapping> </web-app> The output of the program is given below: Snooping Headers In this program we are going to going to make a servlet which will retrieve all the Http request header.3//EN" "http://java. To get a header names call the method getHeaderNames() of the request object which will return the Enumeration of the headers.com/dtd/web-app_2_3.0" encoding="ISO-8859-1"?> <!--<!DOCTYPE web-app PUBLIC "-//Sun Microsystems. To make a program over this firstly we need to make one class named GettingSnoopingHeader.<?xml version="1. The code of the program is given below: . In HttpRequest there are too many headers. Now to retrieve all the headers from the Enumeration use the method hasMoreElements(). To retrieve all the headers firstly we need to call the getWriter() which returns PrintWriter object and helps us to display all the headers. To display the output on your browser use the PrintWriter object.

3//EN" "http://java.println(headerName + ": " + values).nextElement(). IOException { PrintWriter pw = response. Enumeration enumeration = request. public class HeaderSnoopServlet extends HttpServlet{ protected void doGet(HttpServletRequest request.getHeaders(headerName).*. if (headerValues != null){ while (headerValues.sun.dtd"> --> <web-app> <servlet> <servlet-name>Hello</servlet-name> <servlet-class>HeaderSnoopServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/HeaderSnoopServlet</url-pattern> </servlet-mapping> </web-app> The output of the program is given below: .util.servlet.//DTD Web Application 2.getHeaderNames().xml file for this program: <?xml version="1. javax.hasMoreElements()){ String values = (String) headerValues. Enumeration headerValues = request. java.*. pw.com/dtd/web-app_2_3. Inc.import import import import java.servlet.getWriter(). } } } } } web.0" encoding="ISO-8859-1"?> <!--<!DOCTYPE web-app PUBLIC "-//Sun Microsystems.hasMoreElements()){ String headerName = (String)enumeration.println("Request Headers are"). while(enumeration.io. javax. pw. HttpServletResponse response) throws ServletException.nextElement().*.http.*.

Dice Roller We are going to make one program on the dice roller in which the number in the dice will be selected randomly.getWriter(). public class DiceRollerServlet extends HttpServlet{ protected void doGet(HttpServletRequest request. IOException{ PrintWriter pw = response. String dice1 = Integer.lang.*.println("dice1 value is " + dice1 + " and <br>dice2 value is " +di ce2).random()*6)+1).Math.http. HttpServletResponse re sponse) throws ServletException. To make the dice working randomly use the random() method of the class java. pw.*. Now by the object of the PrintWriter class print the values of the dice on the browser.println("<html><body>").println("dice roller<br>"). . To print the number on the browser call the method getWriter() of the response object which will return the PrintWriter object. pw.servlet. String dice2 = Integer. The code of the program is given below: import java. import javax.toString((int)(Math.*.random()*6)+1).servlet.io. import javax. To make a program over this firstly we need to make a class DiceRoller in which we will have a doGet() method in which we will have our application logic.toString((int)(Math. pw.

xml.} } XML File for this program: <?xml version="1. Whenever the container makes a servlet it always reads it deployment descriptor file i.sun.xml file.e.3//EN" "http://java. Container creates name/value pairs for the ServletConfig object.dtd"> <web-app> <servlet> <servlet-name>Zulfiqar</servlet-name> <servlet-class>DiceRollerServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Zulfiqar</servlet-name> <url-pattern>/DiceRollerServlet</url-pattern> </servlet-mapping> </web-app> The output of the program is given below: Getting Init Parameter Names In this example we are going to retreive the init paramater values which we have given in the web.com/dtd/web-app_2_3.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems. Once the parameters are in ServletConfig they will never be read again by the Container. The main job of the ServletConfig object is to give the init parameters. . web.//DTD Web Application 2. Inc.

in</param-value> </init-param> <init-param> <param-name>Address</param-name> . the service method calls either the doGet() or the doPost().com/dtd/web-app_2_3.servlet.print(enumeration.*.print("Init Parameters are : ").xml file of this program: <?xml version="1.*.dtd"> <web-app> <servlet> <init-param> <param-name>AdminEmail</param-name> <param-value>zulfiqar_mca@yahoo.getInitParameter( "Address")).http. The code of the program is given below: import import import import java.util. HttpServletResponse res ponse) throws ServletException. } pw.sun. pw.nextElement() + " ").println("The phone no is " + getServletConfig(). By default it will be doGet() method. Enumeration enumeration = getServletConfig().getInitParameterNames( ).*. javax.co. To retrieve all the values of the init parameter use method getInitParameterNames() which will return the Enumeration of the init parameters.3//EN" "http://java. pw.io.println("\nThe email address is " + getServletConfig().println("The address is " + getServletConfig(). while(enumeration.getInitParameter( "PhoneNo")).*. public class InitServlet extends HttpServlet { public void doGet(HttpServletRequest request. Now inside the doGet() method use getWriter() method of the response object which will return a object of the PrintWriter class which helps us to print the content on the browser.getInitPa rameter("AdminEmail")). Inc.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems.servlet. javax. The container calls the servlet's service() method then depending on the type of request. pw.//DTD Web Application 2. IOException { PrintWriter pw = response. java.getWriter().hasMoreElements()){ pw.To retrieve the init parameters in the program firstly we have made one class named GettingInitParameterNames. } } web.

on pressing the submit button the request will go to the server and the result will be displayed to us. And we will also have one submit button. The code of the program is given below: . To get the desired result firstly we have to make one html form which will have only one field named as name in which we will enter the name.<param-value>Okhla</param-value> </init-param> <init-param> <param-name>PhoneNo</param-name> <param-value>9911217074</param-value> </init-param> <servlet-name>Zulfiqar</servlet-name> <servlet-class>InitServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Zulfiqar</servlet-name> <url-pattern>/InitServlet</url-pattern> </servlet-mapping> </web-app> The output of the program is given below: Passing Parameter Using Html Form This is a very simple example in which we are going to display the name on the browser which we have entered from the Html page. In the servlet which will work as a controller here picks the value from the html page by using the method getParameter(). The output will be displayed to you by the object of the PrintWriter class.

dtd"> --> <web-app> . out.*.getWriter().java import java.servlet.servlet.*. String pass = request. public class LoginServlet extends HttpServlet{ public void doGet(HttpServletRequest request.xml file for this program: <?xml version="1. PrintWriter out = response.<html> <head> <title>New Page 1</title> </head> <body> <h2>Login</h2> <p>Please enter your username and password</p> <form method="GET" action="/htmlform/LoginServlet"> <p> Username <input type="text" name="username" size="20"></p> <p> Password <input type="text" name="password" size="20"></p> <p><input type="submit" value="Submit" name="B1"></p> </form> <p>&nbsp.println("</body></html>").println("Thanks Mr.getParameter("password").getParameter("username"). import javax. IOException { response.</p> </body> </html> LoginServlet.*.println("<html>"). import javax.http.com/dtd/web-app_2_3. Inc. out. out.3//EN" "http://java. } } web.println("<body>"). out.io.//DTD Web Application 2.setContentType("text/html"). out.sun. HttpServletResponse res ponse) throws ServletException.0" encoding="ISO-8859-1"?> <!--<!DOCTYPE web-app PUBLIC "-//Sun Microsystems." + " " + name + " " + "for visiting rose india<br>" ).println("Now you can see your password : " + " " + pass + "<br >"). String name = request.

<servlet> <servlet-name>Hello</servlet-name> <servlet-class>LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/LoginServlet</url-pattern> </servlet-mapping> </web-app> The output of the program is given below: .

In this program we have used the checkbox which will have the same name but with different values. public class GetParameterValues extends HttpServlet{ protected void doPost(HttpServletRequest request.servlet.http. HttpServletResponse response) throws ServletException. PrintWriter pw = response.*. The output will be displayed to you by the PrintWriter object. We have one more button submit.io. IOException { response. on pressing this button the request will be forwarded. The code of the program is given below: Index.< br> <input type = "checkbox" name ="whisky" value = "Bagpiper">Bagpiper. At last to retrieve all the values from the array use the for loop.html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4. To make such a servlet which we have made one html form from where the values will be passed to the controller.*. import javax. Now in the servlet that is working like a controller will retrieve the values we have entered in the html form by the method getParameterValues() which returns the array of String.java import java.servlet.setContentType("text/html").*. We are going to make one program over it. .Multiple values for a single parameter In our program it may be that we may have multiples values for a single parameter like in checkboxes.<br> <input type ="submit" name= "submit"> </form> </body> </html> GetParameterValues.getWriter().01 Transitional//EN"> <html> <head> <title>Insert title here</title> </head> <body> <form method = "post" action = "/GetParameterServlet/GetParameterValues" > <p>Which of the whisky you like most</p> <input type = "checkbox" name ="whisky" value = "RoyalChallenge">RoyalC hallenge.<br> <input type = "checkbox" name ="whisky" value = "RoyalStag">RoyalStag. import javax.

xml file for this program: <?xml version="1. Inc.length. i++){ pw.sun.com/dtd/web-app_2_3.getParameterValues("whisky").0" encoding="ISO-8859-1"?> <!--<!DOCTYPE web-app PUBLIC "-//Sun Microsystems.} } String[] whisky = request.println("<br>whisky : " + whisky[i]).3//EN" "http://java. i<whisky.dtd"> --> <web-app> <servlet> <servlet-name>Hello</servlet-name> <servlet-class>GetParameterValues</servlet-class> </servlet> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/GetParameterValues</url-pattern> </servlet-mapping> </web-app> The output of the program is given below: Here is the result of the above selection: . } web.//DTD Web Application 2. for(int i=0.

IOException { PrintWriter pw = response.Time Updater in Servlet In this program we are going to make one program on servlet which will keep on updating the time in every second and the result will be displayed to you. import javax. response. The code of the program is given below: import java. import java.toString()). HttpServletResponse response) throws ServletException.*. Call the method getWriter() method of the response object which will return a PrintWriter object.io. The setHeader() method overrides the previous set header.*.*.http. The name of the class should be such that it becomes easy to understand what the program is going to do.util. import javax. We can also use setHeader() in place of getHeader().servlet.addHeader("Refresh". To make this servlet firstly we need to make a class named TimeUpdater. "1"). Now by using the PrintWriter object display the result on the browser. } } . public class TimeUpdater extends HttpServlet { public void doGet(HttpServletRequest request.*.println(new Date().getWriter().servlet. pw. Use the method getHeader() of the response object to add a new header.

The code of the example is given below: html file for this program: <html> <head> <title>New Page 1</title> </head> <body> <form method="POST" action="/SendRedirect/SendRedirectServlet"> <p>Enter your name&nbsp. If not then the servlet decides that the request can be handle by other servlet or jsp.&nbsp. In all this process the client is unaware of the processing. <input type="text" name="password" size= "20"></p> .&nbsp. In this example we are going to make one html in which we will submit the user name and his password.&nbsp. Then the servlet calls the sendRedirect() method of the response object and sends back the response to the browser along with the status code.The output of the program is given below: Send Redirect in Servlet When we want that someone else should handle the response of our servlet.&nbsp. If the password entered by the user is correct then the servlet will redirect the request to the other servlet which will handle the request. there the container decides whether the concerned servlet can handle the request or not. If the password entered by the user is wrong then the request will be forwarded to the html form. In send Redirect whenever the client makes any request it goes to the container. but with the name of that servlet which can now handle the request and the result will be displayed to you by the browser. The controller will check if the password entered by the user is correct or not. Then the browser sees the status code and look for that servlet which can now handle the request. then there we should use sendRedirect() method.&nbsp.&nbsp. <input type="text" name="username" size="20"></p> <p>Enter your password&nbsp. Again the browser makes a new request.&nbsp.

&nbsp. public class SendRedirectServlet extends HttpServlet{ protected void doPost(HttpServletRequest request.getParameter("username").&nbsp. } . &nbsp.&nbsp. HttpServletResponse response) throws ServletException.&nbsp.&nbsp.equals("abc")){ response.getWriter().servlet.io. &nbsp. IOException { PrintWriter pw = response.&nbsp . IOException { response.*.&nbsp.&nbsp.&nbsp.&nbsp. &nbsp. HttpServletResponse re sponse) throws ServletException. String name = request.println("how are you").equals("James")&& password.io.&nbsp.servlet.setContentType("text/html").&nbsp. } else{ pw.servlet.<p>&nbsp.&nbsp.servlet.&nbsp.http.getParameter("password").&nbsp.&nbsp. pw.&nbsp.&nbsp. String password = request.*. import javax. <input type="submit" value="Submit" name="B1"></p> </form> </body> </html> import java. public class ValidUserServlet extends HttpServlet{ protected void doGet(HttpServletRequest request. PrintWriter pw = response.net " + " ").&nbsp.*.getWriter().*.&nbsp.&nbsp.println("Welcome to roseindia. import javax.sendRedirect("/SendRedirect/ValidUserServlet").&nbsp.&nbsp.&nbsp.&nbsp. } } } import java. import javax.&nbsp.&nbsp. if(name.*.*. pw.println("u r not a valid user"). import javax.http.&nbsp.&nbsp.

xml file for this program: <?xml version="1.3//EN" "http://java. Inc.dtd"> <web-app> <servlet> <servlet-name>Zulfiqar</servlet-name> <servlet-class>SendRedirectServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Zulfiqar</servlet-name> <url-pattern>/SendRedirectServlet</url-pattern> </servlet-mapping> <servlet> <servlet-name>Hello</servlet-name> <servlet-class>ValidUserServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/ValidUserServlet</url-pattern> </servlet-mapping> </web-app> The output of the program is given below: .0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems.//DTD Web Application 2.} web.sun.com/dtd/web-app_2_3.

.

As we know by the name.. Whenever the browser sends a request then it is always interpreted as a new request because http protocol is a stateless protocol as it is not persistent. the container receives the request and generate a unique session ID and gives it back to the client along with the response. In hidden form fields the html entry will be like this : <input type ="hidden" name = "name" value="">. Cookies: When cookie based session management is used. the server is able to identify the user. This means that when you submit the form. Session Tracking can be done in three ways: 1. a token is generated which contains user's information. In session management client first make a request for any servlet or any page. . the specified name and value will be get included in get or post method. In this way the session is maintained. In this session ID information would be embedded within the form as a hidden field and submitted with the Http POST command. There the container sees the Id and sends back the request. URL Rewriting: This is another way to support the session tracking. sends the request. The token is transmitted to the client by the response object and gets stored on the client machine. is sent to the browser by the server. If we want then we can also disable the cookie. Cookie is nothing but a name. Thereafter when the client request again sends a request to the server then it also sends the session Id with the request. means that it can't persist the information. For security reasons.Session Tracking As we know that the Http is a stateless protocol. Hidden Form Fields: This is one of the way to support the session tracking. 3. 2. By default the cookie is implemented in most of the browsers. By this cookie. and closes the connection.value pair. The hidden form field are sent back to the server when the form is submitted. that in this fields are added to an HTML form which are not displayed in the client's request. Whenever we want that out request object to stay alive till we decide to end the request object then. gets the response. cookie based session management uses two types of cookies. The cookie is sent back to the server when the user sends a new request. This ID gets stores on the client machine. Then server creates a token which will be used to maintain the session. which is stored on the client machine. It always treats each request as a new request. there we use the concept of session tracking. In session tracking firstly a session object is created when the first request goes to the server. In Http client makes a connection to the server. URLRewriting can be used in place where we don't want to use cookies. By default the server creates a cookie and the cookie get stored on the client machine. It is used to maintain the session.

Inside the doGet() method.xml file for this program: <?xml version="1.To Determine whether the Session is New or Old In this program we are going to make one servlet on session in which we will check whether the session is new or old. PrintWriter pw = response.servlet. HttpServletResponse response) throws ServletException. public class CheckingTheSession extends HttpServlet{ protected void doGet(HttpServletRequest request.println("Checking whether the session is new or old<br>"). Inc. Use getSession() of the request object.dtd"> --> <web-app> <servlet> <servlet-name>Hello</servlet-name> <servlet-class>CheckingTheSession</servlet-class> </servlet> <servlet-mapping> <servlet-name>Hello</servlet-name> .io. pw.//DTD Web Application 2. which takes two objects one of request and second of response.println("You have created a new session"). import javax.getSession().*. Inside this method call the method getWriter() of the response object.servlet. To make this program firstly we need to make one class named CheckingTheSession.*. } } } web.setContentType("text/html").*.getWriter().http.sun.0" encoding="ISO-8859-1"?> <!--<!DOCTYPE web-app PUBLIC "-//Sun Microsystems. Now by using the HttpSession we can find out whether the session is new or old. import javax.isNew()){ pw. } else{ pw.com/dtd/web-app_2_3. IOException { response. The code of the program is given below: import java.3//EN" "http://java. HttpSession session = request. which returns the HttpSession object. if(session.println("Session already exists").

<url-pattern>/CheckingTheSession</url-pattern> </servlet-mapping> </web-app> The output of the program is given below: Pre.*. pw. If we don't want to create a new session then we should use getSession(false).servlet.getWriter().java import java. public class PreExistingSessionServlet extends HttpServlet{ protected void doGet(HttpServletRequest request.Existing Session In this example we are going to find out whether the session is pre-existing or not.setContentType("text/html"). To perform this work we have one overloaded method getSession(boolean) of the request object. . import javax. If there will be no session then the new session will be created by the method getSession().println("Testing The Session : "). import javax.*. HttpServletResponse response) throws ServletException. PrintWriter pw = response.io. In the example below we have used the method getSession(false) which will test whether the session is null or not.http.*. The code of the program is given below: PreExistingSessionServlet. It is not always a good idea to create a new session. IOException { response.servlet. Consider a situation where servlet want to use only a existing session.

//DTD Web Application 2..println("Session already exists")...HttpSession session = request. Inc.. if(session==null){ pw.println("Can we create a session for you.println("There is no session"). } else{ pw.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems.").3//EN" "http://java. pw..com/dtd/web-app_2_3.xml file for this program: <?xml version="1.dtd"> <web-app> <servlet> <servlet-name>Zulfiqar</servlet-name> <servlet-class>PreExistingSessionServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Zulfiqar</servlet-name> <url-pattern>/PreExistingSessionServlet</url-pattern> </servlet-mapping> </web-app> The output of the program is given below: .getSession(false). } } } web. session = request.. Creating..sun..getSession().

Master your semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master your semester with Scribd & The New York Times

Cancel anytime.