OOPS unit 5
OOPS unit 5
Unit-V
Servlets
Servlets provide a component-based, platform-independent method for building Web-based
applications, without the performance limitations of CGI programs. Servlets have access to the
entire family of Java APIs, including the JDBC API to access enterprise databases.
Using Servlets, you can collect input from users through web page forms, present records from a
database or another source, and create web pages dynamically
Servlets Architecture:
Servlets Tasks:
A development environment is where you would develop your Servlet, test them and finally
run them.
1
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023
Like any other Java program, you need to compile a servlet by using the Java compiler javac
and after compilation the servlet application, it would be deployed in a configured
environment to test and run.
This step involves downloading an implementation of the Java Software Development Kit
(SDK) and setting up PATH environment variable appropriately.
You can download SDK from Oracle's Java site: Java SE Downloads.
Once you download your Java implementation, follow the given instructions to install and
configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to
the directory that contains java and javac, typically java_install_dir/bin and java_install_dir
respectively.
If you are running Windows and installed the SDK in C:\jdk1.5.0_20, you would put the
following line in your C:\autoexec.bat file.
set PATH=C:\jdk1.5.0_20\bin;%PATH%
set JAVA_HOME=C:\jdk1.5.0_20
On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and you use
the C shell, you would put the following into your .cshrc file.
A number of Web Servers that support servlets are available in the market. Some web servers
are freely downloadable and Tomcat is one of them.
Apache Tomcat is an open source software implementation of the Java Servlet and
JavaServer Pages technologies and can act as a standalone server for testing servlets and can
be integrated with the Apache Web Server. Here are the steps to setup Tomcat on your
machine:
2
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023
%CATALINA_HOME%\bin\startup.bat
or
C:\apache-tomcat-5.5.29\bin\startup.bat
Tomcat can be started by executing the following commands on Unix (Solaris, Linux, etc.)
machine:
$CATALINA_HOME/bin/startup.sh
or
/usr/local/apache-tomcat-5.5.29/bin/startup.sh
After startup, the default web applications included with Tomcat will be available by visiting
http://localhost:8080/. If everything is fine then it should display following result:
Further information about configuring and running Tomcat can be found in the
documentation included here, as well as on the Tomcat web site: http://tomcat.apache.org
C:\apache-tomcat-5.5.29\bin\shutdown
3
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023
Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.)
machine:
/usr/local/apache-tomcat-5.5.29/bin/shutdown.sh
Setting up CLASSPATH
Since servlets are not part of the Java Platform, Standard Edition, you must identify the
servlet classes to the compiler.
If you are running Windows, you need to put the following lines in your C:\autoexec.bat file.
set CATALINA=C:\apache-tomcat-5.5.29
set CLASSPATH=%CATALINA%\common\lib\servlet-api.jar;%CLASSPATH%
On Unix (Solaris, Linux, etc.), if you are using the C shell, you would put the following lines
into your .cshrc file.
setenv CATALINA=/usr/local/apache-tomcat-5.5.29
setenv CLASSPATH $CATALINA/common/lib/servlet-api.jar:$CLASSPATH
A servlet life cycle can be defined as the entire process from its creation till the destruction.
The following are the paths followed by a servlet
The init method is designed to be called only once. It is called when the servlet is first
created, and not called again for each user request. So, it is used for one-time initializations,
just as with the init method of applets.
The servlet is normally created when a user first invokes a URL corresponding to the servlet,
but you can also specify that the servlet be loaded when the server is first started.
4
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023
When a user invokes a servlet, a single instance of each servlet gets created, with each user
request resulting in a new thread that is handed off to doGet or doPost as appropriate. The
init() method simply creates or loads some data that will be used throughout the life of the
servlet.
The service() method is the main method to perform the actual task. The servlet container
(i.e. web server) calls the service() method to handle requests coming from the client(
browsers) and to write the formatted response back to the client.
Each time the server receives a request for a servlet, the server spawns a new thread and calls
service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE,
etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
The service () method is called by the container and service method invokes doGe, doPost,
doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service()
method but you override either doGet() or doPost() depending on what type of request you
receive from the client.
The doGet() and doPost() are most frequently used methods with in each service request.
Here is the signature of these two methods.
A GET request results from a normal request for a URL or from an HTML form that has no
METHOD specified and it should be handled by doGet() method.
A POST request results from an HTML form that specifically lists POST as the METHOD
and it should be handled by doPost() method.
5
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023
The destroy() method is called only once at the end of the life cycle of a servlet. This method
gives your servlet a chance to close database connections, halt background threads, write
cookie lists or hit counts to disk, and perform other such cleanup activities.
After the destroy() method is called, the servlet object is marked for garbage collection. The
destroy method definition looks like this:
Architecture Digram:
First the HTTP requests coming to the server are delegated to the servlet container.
The servlet container loads the servlet before invoking the service() method.
Then the servlet container handles multiple requests by spawning multiple threads,
each thread executing the service() method of a single instance of the servlet.
6
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023
Examples
Servlets are Java classes which service HTTP requests and implement the
javax.servlet.Servlet interface. Web application developers typically write servlets that
extend javax.servlet.http.HttpServlet, an abstract class that implements the Servlet interface
and is specially designed to handle HTTP requests.
Following is the sample source code structure of a servlet example to write Hello World:
Compiling a Servlet:
Let us put above code if HelloWorld.java file and put this file in C:\ServletDevel (Windows)
or /usr/ServletDevel (Unix) then you would need to add these directories as well in
CLASSPATH.
$ javac HelloWorld.java
7
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023
If the servlet depends on any other libraries, you have to include those JAR files on your
CLASSPATH as well. I have included only servlet-api.jar JAR file because I'm not using any
other library in Hello World program.
This command line uses the built-in javac compiler that comes with the Sun Microsystems
Java Software Development Kit (JDK). For this command to work properly, you have to
include the location of the Java SDK that you are using in the PATH environment variable.
If everything goes fine, above compilation would produce HelloWorld.class file in the same
directory. Next section would explain how a compiled servlet would be deployed in
production.
Servlet Deployment:
If you have a fully qualified class name of com.myorg.MyServlet, then this servlet class
must be located in WEB-INF/classes/com/myorg/MyServlet.class.
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
You are almost done, now let us start tomcat server using <Tomcat-installation-
directory>\bin\startup.bat (on windows) or <Tomcat-installation-directory>/bin/startup.sh (on
Linux/Solaris etc.) and finally type http://localhost:8080/HelloWorld in browser's address
box. If everything goes fine, you would get following result:
8
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023
You must have come across many situations when you need to pass some information from
your browser to web server and ultimately to your backend program. The browser uses two
methods to pass this information to web server. These methods are GET Method and POST
Method.
GET method:
The GET method sends the encoded user information appended to the page request. The page
and the encoded information are separated by the ? character as follows:
http://www.test.com/hello?key1=value1&key2=value2
The GET method is the defualt method to pass information from browser to web server and it
produces a long string that appears in your browser's Location:box. Never use the GET
method if you have password or other sensitive information to pass to the server. The GET
method has size limtation: only 1024 characters can be in a request string.
This information is passed using QUERY_STRING header and will be accessible through
QUERY_STRING environment variable and Servlet handles this type of requests using
doGet() method.
POST method:
A generally more reliable method of passing information to a backend program is the POST
method. This packages the information in exactly the same way as GET methods, but instead
of sending it as a text string after a ? in the URL it sends it as a separate message. This
message comes to the backend program in the form of the standard input which you can parse
and use for your processing. Servlet handles this type of requests using doPost() method.
9
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023
Servlets handles form data parsing automatically using the following methods depending on
the situation:
Here is a simple URL which will pass two values to HelloForm program using GET method.
http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI
Below is HelloForm.java servlet program to handle input given by web browser. We are
going to use getParameter() method which makes it very easy to access passed information:
10
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023
$ javac HelloForm.java
If everything goes fine, above compilation would produce HelloForm.class file. Next you
would have to copy this class file in <Tomcat-installation-directory>/webapps/ROOT/WEB-
INF/classes and create following entries in web.xml file located in <Tomcat-installation-
directory>/webapps/ROOT/WEB-INF/
<servlet>
<servlet-name>HelloForm</servlet-name>
<servlet-class>HelloForm</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloForm</servlet-name>
<url-pattern>/HelloForm</url-pattern>
</servlet-mapping>
Now type http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI in your
browser's Location:box and make sure you already started tomcat server, before firing above
command in the browser. This would generate following result:
Using GET Method to Read Form Data
Here is a simple example which passes two values using HTML FORM and submit button.
We are going to use same Servlet HelloForm to handle this imput.
<html>
<body>
<form action="HelloForm" method="GET">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
11
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023
Try to enter First Name and Last Name and then click submit button to see the result on your
local machine where tomcat is running. Based on the input provided, it will generate similar
result as mentioned in the above example.
Let us do little modification in the above servlet, so that it can handle GET as well as POST
methods. Below is HelloForm.java servlet program to handle input given by web browser
using GET or POST methods.
Now compile, deploy the above Servlet and test it using Hello.htm with the POST method as
follows:
<html>
<body>
<form action="HelloForm" method="POST">
12
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023
Here is the actual output of the above form, Try to enter First and Last Name and then click
submit button to see the result on your local machine where tomcat is running.
Based on the input provided, it would generate similar result as mentioned in the above
examples.
Checkboxes are used when more than one option is required to be selected.
Here is example HTML code, CheckBox.htm, for a form with two checkboxes
<html>
<body>
<form action="CheckBox" method="POST" target="_blank">
<input type="checkbox" name="maths" checked="checked" /> Maths
<input type="checkbox" name="physics" /> Physics
<input type="checkbox" name="chemistry" checked="checked" />
Chemistry
<input type="submit" value="Select Subject" />
</form>
</body>
</html>
Below is CheckBox.java servlet program to handle input given by web browser for checkbox
button.
13
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023
Maths Flag : : on
Chemistry Flag: : on
Once we have an Enumeration, we can loop down the Enumeration in the standard manner,
using hasMoreElements() method to determine when to stop and using nextElement() method
to get each parameter name.
14
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n<td>");
String[] paramValues =
request.getParameterValues(paramName);
// Read single valued data
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0)
out.println("<i>No Value</i>");
else
out.println(paramValue);
} else {
// Read multiple valued data
out.println("<ul>");
for(int i=0; i < paramValues.length; i++) {
out.println("<li>" + paramValues[i]);
}
out.println("</ul>");
}
}
out.println("</tr>\n</table>\n</body></html>");
}
// Method to handle POST method request.
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
15
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023
doGet(request, response);
}
}
<html>
<body>
<form action="ReadParams" method="POST" target="_blank">
<input type="checkbox" name="maths" checked="checked" /> Maths
<input type="checkbox" name="physics" /> Physics
<input type="checkbox" name="chemistry" checked="checked" /> Chem
<input type="submit" value="Select Subject" />
</form>
</body>
</html>
Now calling servlet using above form would generate following result:
maths on
chemistry on
You can try above servlet to read any other form's data which is having other objects like text
box, radio button or drop down box etc.
Cookies are text files stored on the client computer and they are kept for various information
tracking purpose. Java Servlets transparently supports HTTP cookies.
Server script sends a set of cookies to the browser. For example name, age, or
identification number etc.
Browser stores this information on local machine for future use.
When next time browser sends any request to web server then it sends those cookies
information to the server and server uses that information to identify the user.
This chapter will teach you how to set or reset cookies, how to access them and how to delete
them.
16
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023
Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly
on a browser). A servlet that sets a cookie might send headers that look something like this:
HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT;
path=/; domain=tutorialspoint.com
Connection: close
Content-Type: text/html
As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a
domain. The name and value will be URL encoded. The expires field is an instruction to the
browser to "forget" the cookie after the given time and date.
If the browser is configured to store cookies, it will then keep this information until the
expiry date. If the user points the browser at any page that matches the path and domain of
the cookie, it will resend the cookie to the server. The browser's headers might look
something like this:
GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz
A servlet will then have access to the cookie through the request method request.getCookies()
which returns an array of Cookie objects.
Following is the list of useful methods which you can use while manipulating cookies in
servlet.
17
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023
you don't set this, the cookie will last only for the current session.
public int getMaxAge()
4
This method returns the maximum age of the cookie, specified in seconds, By default, -1
indicating the cookie will persist until browser shutdown.
public String getName()
5
This method returns the name of the cookie. The name cannot be changed after creation.
public void setValue(String newValue)
6
This method sets the value associated with the cookie.
public String getValue()
7
This method gets the value associated with the cookie.
public void setPath(String uri)
8
This method sets the path to which this cookie applies. If you don't specify a path, the
cookie is returned for all URLs in the same directory as the current page as well as all
subdirectories.
public String getPath()
9
This method gets the path to which this cookie applies.
public void setSecure(boolean flag)
10
This method sets the boolean value indicating whether the cookie should only be sent
over encrypted (i.e. SSL) connections.
public void setComment(String purpose)
11
This method specifies a comment that describes a cookie's purpose. The comment is
useful if the browser presents the cookie to the user.
public String getComment()
12
This method returns the comment describing the purpose of this cookie, or null if the
cookie has no comment.
(1) Creating a Cookie object: You call the Cookie constructor with a cookie name and a
cookie value, both of which are strings.
Keep in mind, neither the name nor the value should contain white space or any of the
following characters:
18
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023
[ ] ( ) = , " / ? @ : ;
(2) Setting the maximum age: You use setMaxAge to specify how long (in seconds) the
cookie should be valid. Following would set up a cookie for 24 hours.
cookie.setMaxAge(60*60*24);
(3) Sending the Cookie into the HTTP response headers: You use response.addCookie to
add cookies in the HTTP response header as follows:
response.addCookie(cookie);
Example:
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
19
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023
}
}
Compile above servlet HelloForm and create appropriate entry in web.xml file and finally try
following HTML page to call servlet.
<html>
<body>
<form action="HelloForm" method="GET">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
First Name:
Last Name:
Try to enter First Name and Last Name and then click submit button. This would display first
name and last name on your screen and same time it would set two cookies firstName and
lastName which would be passed back to the server when next time you would press Submit
button.
Next section would explain you how you would access these cookies back in your web
application.
Example:
20
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023
HttpServletResponse response)
throws ServletException, IOException
{
Cookie cookie = null;
Cookie[] cookies = null;
// Get an array of Cookies associated with this domain
cookies = request.getCookies();
Compile above servlet ReadCookies and create appropriate entry in web.xml file. If you
would have set first_name cookie as "John" and last_name cookie as "Player" then running
http://localhost:8080/ReadCookies would display the following result:
To delete cookies is very simple. If you want to delete a cookie then you simply need to
follow up following three steps:
21
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023
Example:
Following example would delete and existing cookie named "first_name" and when you
would run ReadCookies servlet next time it would return null value for first_name.
Compile above servlet DeleteCookies and create appropriate entry in web.xml file. Now
running http://localhost:8080/DeleteCookies would display the following result:
22
St.Joseph’s College of Engineering
CS1303 Object Oriented Programming Department of CSE 2022-2023
Now try to run http://localhost:8080/ReadCookies and it would display only one cookie as
follows:
You can delete your cookies in Internet Explorer manually. Start at the Tools menu and select
Internet Options. To delete all cookies, press Delete Cookies.
Notes: tutorialpoint.com
23
St.Joseph’s College of Engineering