Docsity

Java Servlets: Lecture Notes on Server-Side Programming, Lecture notes of Javascript programming

Partial preview of the text

Download Java Servlets: Lecture Notes on Server-Side Programming and more Lecture notes Javascript programming in PDF only on Docsity!

BIJU PATNAIK UNIVERSITY OF TECHNOLOGY,

ODISHA

Lecture Notes

On

Prepared by,

Dr. Subhendu Kumar Rath,

BPUT, Odisha.

J2EE

By Dr.S.K.Rath, BPUT

INTRODUCTION TO SERVLET

Java Servlets are server side Java programs that require either a Web Server or an Application Server for execution. Examples for Web Servers include Apache’s Tomcat Server and Macromedia’s JRun. Web Servers include IBM’s Weblogic and BEA’s Websphere server. Examples for other Server programs include Java Server Pages (JSPs) and Enterprise Java Beans (EJBs). In the forthcoming sections, we will get acquainted with Servlet fundamentals and other associated information required for creating and executing Java Servlets. Servlets are server side components that provide a powerful mechanism for developing server side programs. 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. 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.

METHOD OF SERVLET

A Generic servlet contains the following five methods:

1. 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. 2. service()

public void service(ServletRequest req, ServletResponse res) throws ServletException,IOException

By Dr.S.K.Rath, BPUT

The servlet will be available for service if it is loaded successfully otherwise the servlet container unloads the servlet.

  1. 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.
  2. 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

Advantages of Java Servlets

  1. Portability
  2. Powerful
  3. Efficiency
  4. Safety
  5. Integration
  6. Extensibilty
  7. Inexpensive

Each of the points are defined below:

1. 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. We can develop a servlet on Windows machine running the tomcat server or any other server and later we can deploy that servlet

By Dr.S.K.Rath, BPUT

effortlessly on any other operating system like Unix server running on the iPlanet/Netscape Application server. So servlets are write once, run anywhere (WORA) program.

2. Powerful We can do several things with the servlets which were difficult or even impossible to do with CGI, for example the servlets can talk directly to the web server while the CGI programs can't do. Servlets can share data among each other, they even make the database connection pools easy to implement. They can maintain the session by using the session tracking mechanism which helps them to maintain information from request to request. It can do many other things which are difficult to implement in the CGI programs. 3.Efficiency As compared to CGI the servlets invocation is highly efficient. When the servlet get loaded in the server, it remains in the server's memory as a single object instance. However with servlets there are N threads but only a single copy of the servlet class. Multiple concurrent requests are handled by separate threads so we can say that the servlets are highly scalable. 4.Safety As servlets are written in java, servlets inherit the strong type safety of java language. Java's automatic garbage collection and a lack of pointers means that servlets are generally safe from memory management problems. In servlets we can easily handle the errors due to Java's exception handling mechanism. If any exception occurs then it will throw an exception. 5.Integration Servlets are tightly integrated with the server. Servlet can use the server to translate the file paths, perform logging, check authorization, and MIME type mapping etc. 6.Extensibility The servlet API is designed in such a way that it can be easily extensible. As it stands today, the servlet API support Http Servlets, but in later date it can be extended for another type of servlets. 7.Inexpensive There are number of free web servers available for personal use or for commercial purpose. Web servers are relatively expensive. So by using the free available web servers you can add servlet support to it.

Basic Servlet Structure

As seen earlier, Java servlets are server side programs or to be more specific; web applications that run on servers that comply HTTP protocol. The javax.servlet and javax.servlet.http packages provide the necessary interfaces and classes to work with servlets. Servlets generally extend the HttpServlet class and override the doGet or the doPost methods. In addition, other methods such as init, service and destroy also called as life cycle methods might be used which will be discussed in the following section. The skeleton of a servlet is given in Figure

By Dr.S.K.Rath, BPUT

By Dr.S.K.Rath, BPUT

Output Screens

To appreciate the execution of the servlet life cycle methods, keep refreshing the browser (F5 in Windows). In the background, what actually happens is – with each refresh, 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. The procedure to run the servlets using a Web Server will be demonstrated in the next section (1.3.).

By Dr.S.K.Rath, BPUT

Installation, Configuration and running Servlets

In this section, we will see as how to install a WebServer, configure it and finally run servlets using this server. Throughout this tutorial, we will be using Apache’s Tomcat server as the WebServer. Tomcat is not only an open and free server, but also the most preferred WebServer across the world. A few reasons we can attribute for its popularity is – Easy to install and configure, very less memory footprint, fast, powerful and portable. It is the ideal server for learning purpose.

  1. Installation of Tomcat Server and JDK

As mentioned earlier, Apache’s Tomcat Server is free software available for download @ www.apache.org. The current version of Tomcat Server is 6.0 (as of November 2007). This Server supports Java Servlets 2.5 and Java Server Pages (JSPs) 2.1 specifications. In case of doubt or confusion, you can refer to the abundant documentation repository available on this site.

Important software required for running this server is Sun’s JDK (Java Development Kit) and JRE (Java Runtime Environment). The current version of JDK is 6.0. Like Tomcat, JDK is also free and is available for download at www.java.sun.com.

  1. Configuring Tomcat Server

o Set JAVA_HOME variable - You have to set this variable which points to the base installation directory of JDK installation. (e.g. c:\program file\java\jdk1.6.0). You can either set this from the command prompt or from My Computer -> Properties -> Advanced -> Environment Variables. o Specify the Server Port – You can change the server port from 8080 to 80 (if you wish to) by editing the server.xml file in the conf folder. The path would be something like this – c:\program files\apache software foundation\tomcat6\conf\server.xml

  1. Run Tomcat Server

Once the above pre-requisites are taken care, you can test as whether the server is successfully installed as follows:

By Dr.S.K.Rath, BPUT

Step 1

  • Go to C:\Program Files\Apache Software Foundation\Tomcat 6.0\bin and double click on tomcat

OR

  • Go to Start->Programs->Apache Tomcat 6.0 -> Monitor Tomcat. You will notice an icon appear on the right side of your Status Bar. Right click on this icon and click on Start service.

Step 2

  • Open your Browser (e.g. MS Internet Explorer) and type the following URL :

http://localhost/ (If you have changed to port # to 80)

OR

  • Open your Browser (e.g. MS Internet Explorer) and type the following URL :

http://localhost:8080/ (If you have NOT changed the default port #)

In either case, you should get a page similar to the one in Figure-8 which signifies that the Tomcat Server is successfully running on your machine.

  1. 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. Though this explanation is specific to Tomcat, the procedure explained holds true for other Web servers too (e.g. JRun, Caucho’s Resin).

Step 1 – Compile your servlet program

The first step is to compile your servlet program. The procedure is no different from that of writing and compiling a java program. But, the point to be noted is that neither the javax.servlet.* nor the javax.servlet.http.* is part of the standard JDK. It has to be exclusively added in the CLASSPATH. The set of classes required for writing servlets is available in a jar file called servlet-api.jar. This jar file can be downloaded from several sources. However, the easiest one is to use this jar file available with the Tomcat server (C:\Program Files\Apache Software Foundation\Tomcat 6.0\lib\servlet-api.jar). You need to include this path in CLASSPATH. Once you have done this, you will be able to successfully compile your servlet program. Ensure that the class file is created successfully.

Step 2 – Create your Web application folder

The next step is to create your web application folder. The name of the folder can be any valid and logical name that represents your application (e.g. bank_apps, airline_tickets_booking, shopping_cart,etc). But the most important criterion is that this folder should be created under webapps folder. The path would be similar or close to this - C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps. For demo purpose, let us create a folder called demo-examples under the webapps folder.

By Dr.S.K.Rath, BPUT

application.

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. All you need to do is copy the servlet class file (the file we obtained from Step 1) to this folder. Figure-12 shows the servlet_lifecycle (refer section 1.2.3.) class being placed in the classes folder.

Figure – servlet class file placed under classes folder

Step 6 – Edit web.xml to include servlet’s name and url pattern

This step involves two actions viz. including the servlet’s name and then mentioning the url pattern. Let us first see as how to include the servlet’s name in the web.xml file. Open the web.xml file and include the servlet’s name as shown in Figure-13.

Figure– Include servlet’s name using the 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. This is one of the main reasons as why this tag is used for.

Next, include the url pattern using the <servlet-mapping> </servlet-mapping> tag. The url pattern defines as how a user can access the servlet from the browser. Figure-14 shows the url pattern entry for our current servlet.

By Dr.S.K.Rath, BPUT

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. This means that this path is w.r.t. 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. running the Web Server and then executing the servlet. To run the server, follow the steps explained in Section 1.3.3.

After ensuring that the web server is running successfully, you can run your servlet. To do this, open your web browser and enter the url as specified in the web.xml file. The complete url that needs to be entered in the browser is:

http://localhost/demo-examples/servlet_lifecycle

Figure – Our servlet’s output!

By Dr.S.K.Rath, BPUT

<servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/DateDisplay</url-pattern> </servlet-mapping> </web-app>

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. In this example firstly we are going to create one class named as HolisticCounterInServlet. Now declare a variable counter of int with initial value 0, the value of this counter will be different for each servlet and create a Hashtable object. This object will be shared by all the threads in the container. Inside the doGet() method use the method getWriter() method of the response object which will return the PrintWriter object. The code of the program is given below:

import java.io.; import java.io.IOException; import java.util.; import javax.servlet.; import javax.servlet.http.;

public class HolisticCounter extends HttpServlet{ int counter = 0; //separate For Each Servlet static Hashtable hashTable = new Hashtable(); //Shared by all the threads

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); counter++; pw.println("This servlet has been accessed" + counter + "times
"); hashTable.put(this,this); pw.println("There are currently" + hashTable.size() + "threads
");

By Dr.S.K.Rath, BPUT

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. In this program we are going to make use of the init method of the Servlet interface which takes one argument of ServletConfig. Firstly declare a variable counter which will have the initial value of the counter. The init() method accepts an object which implements ServletConfig interface. 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. You need to parse the String value which you will get from the getInitParameter() method to a Integer. The code of the program is given below:

import java.io.; import javax.servlet.; import javax.servlet.http.*;

public class CounterInInit extends HttpServlet { int counter; public void init(ServletConfig config) throws ServletException{ super .init(config); String initValue = config.getInitParameter("initial"); try { counter = Integer.parseInt(initValue); } catch (NumberFormatException e){ counter = 0; } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType("text/html"); PrintWriter pw = response.getWriter(); counter++; pw.println("Since loading this servlet has been accessed" + counter + "times"); } }

By Dr.S.K.Rath, BPUT

web.xml file for this program:

<web-app> <servlet-name>Hello</servlet-name> <servlet- class >SnoopingServerServlet</servlet- class > <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. To make a program over this firstly we need to make one class named GettingSnoopingHeader. In HttpRequest there are too many headers. 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 get a header names call the method getHeaderNames() of the request object which will return the Enumeration of the headers. Now to retrieve all the headers from the Enumeration use the method hasMoreElements(). This method checks whether there are more headers or not. To display the output on your browser use the PrintWriter object. The code of the program is given below:

import java.io.; import java.util.; import javax.servlet.; import javax.servlet.http.;

public class HeaderSnoopServlet extends HttpServlet{ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter pw = response.getWriter(); pw.println("Request Headers are");

By Dr.S.K.Rath, BPUT

Enumeration enumeration = request.getHeaderNames(); while (enumeration.hasMoreElements()){ String headerName = (String)enumeration.nextElement(); Enumeration headerValues = request.getHeaders(headerName); if (headerValues != null ){ while (headerValues.hasMoreElements()){ String values = (String) headerValues.nextElement(); pw.println(headerName + ": " + values); } } } } }

web.xml file for this program:

<web-app> <servlet-name>Hello</servlet-name> <servlet- class >HeaderSnoopServlet</servlet- class > <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/HeaderSnoopServlet</url-pattern> </servlet-mapping> </web-app>

The output of the program is given below:

Dice Roller