Java Servlets: What Is Server-Side Programming?
Java Servlets: What Is Server-Side Programming?
JAVA SERVLETS
What is server-side programming?
1. For many web applications server side processing is necessary. i.e., whenever a web Browser
sends the data to a web Server the web Server forwards the same to a program on the server
which is referred as server side program.
2. The ServerSideProgram receives the data from the web Server, process the data and returns
the output back to the web Server which will be given to the web Browser.
3. The web browser receives the data and presents the data on the document.
4. These ServerSidePrograms can be written in any language but the current technologies are
ASP,JSP etc.
1. Java servlets are small independent Java programs that can run on the server.
2. Just as an applet runs on the client-side in a Java-enabled web browser, servlets execute on a
Java-enabled web server.
3. A servlet executes on the server but its output is returned to the client in the form of a HTML
page.
4. Although applets display in a graphical user interface, servlets do not display in GUI
environment.
5. When a browser sends a request, the server may forward it to a servlet. The servlet processes
the request, and constructs an appropriate message and sends it back to the client (browser).
This model is based on the HTTP protocol.
6. The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing
servlets. All servlets must implement the Servlet interface, which defines life-cycle methods.
6. Automatically attach web page elements such as header and footer to all pages returned by the
server.
7. Interact with server resources such as databases and other applications and return useful
information to the client.
8. Provide user authentication and other security mechanisms.
Main thread
Request 1 Thread
Request 1 Thread
Request 1 Thread
Request 2 Request 3
Request 1
2. Compiled: Unlike scripting languages, servlets are compiled into Java byte-code. Therefore
they can execute much more quickly than scripting languages. Compilation also offers the
advantage of error and type checking. Compilation makes servlets more stable and easier to
develop and debug than scripting languages. Also, compiled code is more compact.
3. Crash-resistant: Servlets are written in Java and executed by a Java Virtual Machine (JVM).
JVM does not allow direct memory access and hence crashes do not occur. Also, before
execution, JVM verifies that the compiled Java class files are valid and do not perform any
illegal operations.
5. Durable: Servlets are durable object. That is they remain in memory until they are destroyed.
Thus, servlets are instantiated only once in order to service many requests. A servlet can
create other objects, e.g., a servlet can create a database connection when it is first loaded.
This connection can then be shared across all requests.
6. Dynamic Loading: Servlets can be dynamically loaded locally or across a network. This
ensures that the unused servlets are not occupying system resources. They are loaded only
when needed.
Page 2 of 18 mukeshtekwani@hotmail.com
Java Servlets
8. Protocol Independent: Servlets are protocol independent. Thus, servlet can support FTP
commands, SMTP(Simple Mail Transfer Protocol), POP3 (Post Office Protocol), telnet,
HTTP and other protocols.
9. Cross server: Servlets can run on almost all popular web servers.
10. Written in Java: Since servlets are written in Java, they offer many advantages. These
advantages are: true OOPs-based language, strong type checking, multithreading support,
built-in security, optimized code, automatic garbage collection, built-in network support, and
built-in internationalization through Unicode.
Applet Servlet
1. An applet is a Java program that runs 1. A servlet is a Java program that runs on the
within a Web browser on the client web server.
machine.
2. An applet can use the interface classes 2. A servlet does not have a user interface.
such as AWT or Swing.
3. Applets do not communicate with the 3. Servlets run on the server.
server.
4. Client-side java programs that run in 4. Server-side Java programs are called
browser are called applets. Servlets.
Step 1: A user enters a URL to a browser. The browser generates an HTTP request for
this URL and this request is sent to the appropriate server.
Step 2: The HTTP request is received by the web server. The server maps this request to a
particular servlet. This servlet is dynamically retrieved and loaded into the server.
Step 3: The server invokes the init() method of the servlet. This method is invoked
only when the servlet is first loaded into the memory. We can pass initialization
parameters to the servlet.
Step 4: The server invokes the service() method of the servlet. This method is called
to process the request HTTP request. The servlet can read data that has been provided in
the HTTP request. The service method can also create a HTTP response for the client. The
servlet remains in the server’s address space and is available to process any other requests
from other clients. The service method is called for each request.
Step 5: The server calls the destroy() method when a servlet has to be unloaded from
the server memory. Once this method is called, the servlet will give up all file handles that
were allotted to it. Important data may be saved to a persistent store. The memory
allocated to the servlet and its objects is released.
Sometimes it may be necessary to store the current state of a servlet in some text file or in
a database. This is required if the servlet wants the data from the previous state. This
stored data is called persistent data and his technique is called persistence.
Initializing a servlet:
1. When a server loads a servlet, the server runs the servlet's init method.
2. Initialization is completed before client requests are handled.
3. The server calls the init() method once, when the server loads the servlet, and will not call the
init() method again unless the server is reloading the servlet.
4. The server will reload a servlet only after it has destroyed the servlet by running the destroy()
method.
5. If an initialization error occurs and the servlet cannot handle client requests, the program
throws an UnavailableException. E.g., not able to establish a required network connection.
6. If a servlet uses a database, the init() method could try to open a connection and throw the
UnavailableException if it was unsuccessful.
Page 4 of 18 mukeshtekwani@hotmail.com
Java Servlets
2. Each client request is done through a servlet object of type ServletRequest. The response of
the servlet is sent back through the servlet response object of type ServletResponse.
3. When the client makes a request, the servlet engine passes both the servlet request object and
the servlet response object as parameters to the servlet. The ServletRequest gives the servlet
the following: form data, and protocol methods. The ServletResponse allows the servlet to set
the response headers.
Destroying a Servlet:
1. A server calls the destroy() method after all service calls have been completed. This method
can also be called after a pre-defined time.
2. When the servlet engine decides to destroy a servlet, it invokes the destroy() method. The
servlet releases system resources.
Creating a Servlet :
To create a servlet, we create a class that extends the “HttpServlet” class and overrides the following
methods (i) doGet( ) (ii) doPost( )
• If the WEB Browser sends the data in the Get( ) method then doGet( ) method of servlet will be
executed.
• If the WEB Browser sends the data in the Post method then the doPost( ) method of the servlet will be
executed.
• If the WEB Browser does not specify any method, then the doGet( ) will be executed
HTTP requests are of two type: GET and POST. A web browser after receiving the details from the user,
can forward these to the web server by one of the following ways: GET, or POST
When a web Browser is required to send data to the web Server, the browser converts the data in a
particular format, which is known as URL coding. The server side program receives the converted data,
undoes the conversion, and processes the data.
The following 4 rules will be used by the WEB Browsers for URL coding.
1. All the fields will be separated by & symbol.
2. Each field contains the name of the field and the value of the field separated by = symbol.
3. All spaces will be converted to + symbols.
4. All special characters such as +, & etc., will be converted to hexadecimal values prefixed with
% symbol.
Example 1:
http://myserver.com/SSPname?Empno = 101&Ename = abc+xyz&Job = clk
Example 2: http://localhost:8080/servlet/ColorServlet?color=Red
The characters to the right of the question mark are called the query string.
<HTML>
<BODY>
<FORM name = “form1” action = http://localhost:8080/servlet/ColorServlet>
<B>Color: </B>
<SELECT Name = “color”, Size = “1”>
<option value = “Red”>Red</option>
<option value = “Blue”>Blue</option>
<option value = “Green”>Green</option>
</SELECT>
<BR><BR>
<INPUT TYPE = Submit value = “Submit”>
</FORM>
</BODY>
</HTML>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Page 6 of 18 mukeshtekwani@hotmail.com
Java Servlets
{
String color = req.getParameter(“color”);
res.setContentType(“text/”html”);
PrintWriter out = res.getWriter();
out.println(“The selected color is “ );
out.println(color);
out.close();
}
}
In the Http form, if the user selects the Red color and clicks on the SUBMIT button, the URL
sent to the servlet is http://localhost:8080/servlet/ColorServlet?color=Red
Consider the following statement in the HTML form code at the client side:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
res.setContentType(“text/”html”);
PrintWriter out = res.getWriter();
out.println(“The selected color is “ );
out.println(color);
out.close();
}
}
When the user clicks on the SUBMIT button in the HTML form, the URL sent from the browser
is:
http://localhost:8080/servlet/ColorPostServlet. The parameter names and values are sent in the body of the
HTTP request unlike the query string that was created in GET method.
• The GenericServlet class defines generic server-side operations; the HttpServlet extends this
to define HTTP-specific operations; and application-specific servlets extend this to provide
application-specific operations.
• Client Interaction:
o When a servlet accepts a call from a client, it receives two objects:
A ServletRequest, which encapsulates the communication from the client to
the server.
A ServletResponse, which sends the response from the servlet back to the
client.
o ServletRequest and ServletResponse are interfaces defined by the javax.servlet
package.
Page 8 of 18 mukeshtekwani@hotmail.com
Java Servlets
o names of the parameters passed by the client, the protocol being used by the client,
and the names of the remote host that made the request and the server that received it.
o the input stream, ServletInputStream. Servlets use the input stream to get data from
clients that use application protocols such as the HTTP methods (POST and PUT).
Method Description
doPut() This method is used for uploading a file.
doDelete() This method is used for deleting a document from the server. The documented to
be deleted is indicated in the URL section of the request.
doOptions() This is called by the server to allow a servlet to handle an OPTIONS request.
The OPTIONS request determines which HTTP methods the server supports.
doTrace() This is used for debugging
doGet() This method is called in response to an HTTP GET request. This happens when
the user clicks on a link, or enters a URL in the browser address bar. It also
happens when the HTML form uses the GET method.
doPost() This method is called in response to an HTTP GET request. This happens when
the HTML form uses the POST method.
What is a cookie?
1. Cookies are small files which are stored on a user’s computer by the server.
2. They can hold small amounts of data for a specific client and website.
3. Cookies can be accessed either by the web server or the client computer. The server can send
a page custom-made for a particular client, or location, or time of day. Thus, we can say that
cookies are used for session management.
4. A cookie can be read back by the server. Thus the server can “remember” the client. This is
important because HTTP itself is a stateless protocol. Once the data is delivered by the server
to the client browser, the server will not keep any further information about the client.
5. Cookies have a name and a single value. They may have optional attributes such as version
number, expiry date, a comment for the user, etc.
6. Cookies are assigned by the server to the client. They is sent using fields added to the HTTP
response header. Cookies are passed back to the server using fields added to the HTTP
request headers.
Cookie methods:
Method Description
getName() Gets the name of the cookie. The name of the cookie cannot be changed
after it is created.
getValue() Returns the value of the cookie
setValue(String) Sets the value of the cookie
getMaxAge() Returns the maximum specified age of the cookie.
setMaxAge() Sets the maximum age of the cookie. The unit of measurement is seconds. If it is
set to 0, the cookie will be deleted..
getDomain() Returns the domain that this cookie belongs to
setDomain(String) Sets the domain to which this cookie belongs.The cookie will be visible only to
the specified domain.
Cookie(string, This is a constructor of the class. It defines a cookie with an initial name-value
string) pair.
1. HTTP is a stateless protocol. Each request is independent of the previous one. But in some
applications such as online shopping, banking, etc, it is necessary to save the state information
so that the information can be collected from the user over several interactions. Sessions
provide this mechanism.
2. A session can be created by the getSession() method of HttpServletRequest. This method
returns an HttpSession object. The setAttribute(), getAttribute(), removeAttribute() and
getAttributeNames() methods of the HttpSession manage the bindings between the names and
objects.
Program 1: Write a servlet that illustrates how to use the session state.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http;
//get writer
res.setContentType("text/html");
PrintWriter out = res.getWriter();
if(dt != null)
Page 10 of 18 mukeshtekwani@hotmail.com
Java Servlets
{
out.println("Last access was on " + dt);
}
import java.io.*;
import javax.servlet.*;
out.println("<HTML>");
out.println("<HEAD><TITLE>Hello World</TITLE></HEAD>");
out.println("<BODY>");
out.println("<B>Hello World</B>");
out.println("</BODY></HTML>");
out.close();
}
}
• We import the javax.servlet package. This package contains the classes and interfaces
required to build the srvlet.
• We define HelloServlet as a subclass of GenericServlet. The GenericServlet class simplifies
the creation of a servlet. The GenericServlet class provides init() and destroy() methods and
we have to only write the service() method.
• We have overridden the service() method. This method handles the client requests. In this
method, the first argument is the ServletRequest object. Through this object we can read the
data provided by the client. The second argument is the ServletResponse object and this
object enables the servlet to send a response to the client.
• The call to setContentType() indicates that the browse should interpret the content as HTML
source code.
• The getWriter() method obtains a PrintWriter. The println() method is used to send HTML
source code as the HTTP response.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
out.println("<HTML>");
out.println("<HEAD><TITLE>Hello World</TITLE></HEAD>");
out.println("<BODY>");
out.println("<BIG>Hello World</BIG>");
out.println("</BODY></HTML>");
}
}
a) We import the javax.servlet package. This package contains classes and interfaces required to build
servlets.
b) We define HelloWorld as a subclass of HttpServlet.
c) The HttpServlet class provides specialized methods that handle the various types of HTTP requests.
These methods are doGet(), doDelete(), doPost(), doPut(), doHead(). The GET and POST requests are
commonly used when handling form input. In this program we have used the doGet() method.
d) PrintWriter – This is a class for character stream I/O. We can use the System.out to write to the
console, but PrintWriter is preferred because it can be used to internationalize the output. This class
supports the print and println methods.
Program 4: Write a servlet that counts and displays the number of times it has been
accessed since the last server reboot:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Page 12 of 18 mukeshtekwani@hotmail.com
Java Servlets
Program 5: Write a servlet that counts the number of times it has been accessed, the
number of instances created by the server, and the total times all of them have been
accessed.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
count++;
out.println("Since loading, this servlet instance has been
accessed " + count + " times.");
instances.put(this, this);
out.println("There are currently " + instances.size() + "
instances.");
classCount++;
out.println("Across all instances, this servlet class has been " +
"accessed " + classCount + " times.");
}
}
Program 6: Write a servlet that counts and displays the number of times it has been
accessed, and reads an init parameter to know what at what number to begin counting.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
count++;
Program 7: Write a servlet that counts and displays the number of times it has been
accessed, and saves the count to a file in its destroy() method to make the count persistent.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
try
{
fileReader = new FileReader("InitDestroyCounter.initial");
bufferedReader = new BufferedReader(fileReader);
String initial = bufferedReader.readLine();
count = Integer.parseInt(initial);
return;
}
catch (FileNotFoundException ignored) { } // no saved state
Page 14 of 18 mukeshtekwani@hotmail.com
Java Servlets
Program 8: Write a servlet prints its query string, then prints the name and value for all its
parameters.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
out.println("Query String:");
out.println(req.getQueryString());
out.println();
out.println("Request Parameters:");
while (enum.hasMoreElements())
{
String name = (String) enum.nextElement();
String values[] = req.getParameterValues(name);
if (values != null)
{
for (int i = 0; i < values.length; i++)
{
out.println(name + " (" + i + "): " + values[i]);
}
}
}
}
}
Page 16 of 18 mukeshtekwani@hotmail.com
Java Servlets
Program 9: Write a servlet that gets the value of a parameter called “data” from a HTML
form and stores this data in a cookie called “MyCookie” with the value “data”.
<html>
<body>
<form name = “form1” method = “post” action =
“http://localhost:8080/servlets/AddCookie>
Enter a value for MyCookie:
<Input Type = textbox name = “data” value = “” size = 25>
<input type = submit value = “Submit”>
</form>
</body>
</html>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
//Create a cookie
Cookie ck = New Cookie(“MyCookie”, data);
Program 10: Write a servlet that reads any cookies that are included in the HTTP GET
request. Write the names and values of the cookies in the HTTP response.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetCookies extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
//Get cookies from header of HTTP request
Cookie [] cks = req.getCookies();
out.close();
}
}
Page 18 of 18 mukeshtekwani@hotmail.com