Java Servlets are server side components that provides a powerful mechanism for developing server side of web application. Earlier CGI was developed to provide server side capabilities to the web applications. Although CGI played a major role in the explosion of the Internet, its performance, scalability and reusability issues make it less than optimal solutions. Java Servlets changes all that. Built from ground up using Sun's write once run anywhere technology java servlets provide excellent framework for server side processing. With Java servlets web developers can create fast and efficient server side application and can run it on any

milklivereddeepInternet and Web Development

Nov 13, 2013 (3 years and 9 months ago)

684 views

Web Technologies III B.Tech II Sem (R09) CSE UNIT-V
Prepared by A. Sharath Kumar
(M.Tech), Asst.Prof
Page 1

Java Servlets

Java Servlets are server side components that provides a powerful mechanism for developing server side of
web application. Earlier CGI was developed to provide server side capabilities to the web applications.
Although CGI played a major role in the explosion of the Internet, its performance, scalability and reusability
issues make it less than optimal solutions. Java Servlets changes all that. Built from ground up using Sun's
write once run anywhere technology java servlets provide excellent framework for server side processing.

With Java servlets web developers can create fast and efficient server side application and can run it on any
Servlet enabled web server. Servlets runs entirely inside the Java Virtual Machine. Because the Servlet is
running on the server side, it does not depend on browser compatibility. I just send the result in html formats.

Java Servlets have a number of advantages over CGI and other API's. They are:

Platform Independence
:Java Servlets are 100% pure Java, so it is platform independent. It can run on any
Servlet enabled web server. 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. Platform independency of servlets provides a great advantage over
alternatives of servlets.

Performance
: Due to interpreted nature of java, programs written in java are slow. But the java servlets runs
very fast. These are due to the way servlets run on web server. For any program initialization takes significant
amount of time. But in case of servlets initialization takes place very first time it receives a request and
remains in memory till times out or server shut downs. After servlet is loaded,

Tomcat Web server
Introduction :Tomcat, developed by Apache (www.apache.org), it can be used standalone as a Web server or
be plugged into a Web server like Apache, Netscape Enterprise Server, or Microsoft Internet Information
Server. There are many versions of Tomcat.
Obtaining Tomcat

You can download Tomcat from
http://archive.apache.org/dist/jakarta/
as compressed file(zip). You can
use WinZip to decompress into c:\ compression/decompression utility

Installing Tomcat

Before running the servlet, you need to start the Tomcat servlet engine. To start Tomcat, you have to first set
the JAVA_HOME environment variable to the JDK home directory. The JDK home directory is where your
JDK is stored.
Testing Tomcat
By default, Tomcat runs on part 8080.
To prove that Tomcat is running, type the URL http://localhost:8080 from a Web browser.

The default Tomcat page is displayed.



Web Technologies III B.Tech II Sem (R09) CSE UNIT-V
Prepared by A. Sharath Kumar
(M.Tech), Asst.Prof
Page 2


Creating Servlet

import java.io.*;
import javax.servlet.*;
public class FirstServlet extends GenericServlet
{
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter pw= res.getWriter();
pw.println("<b> Welcome to My Servlets</B>");
pw.close();
}
}

Compiling Servlets

servlet.jar contains the classes and interfaces to support servlets. Servlet package is not bundled with JDK,
any webserver software will have servlet package Tomcat has servlet packages in a file called servlet.jar for
lower versions of Tomcat 5 and higher versions including Tomcat 5 contains servlet-api.jar

Suppose you have installed Tomcat 4.1 at C:\Program Files\Apache Group\Tomcat 1.4

To compile FirstServlet.java, you need to add to the classpath from DOS prompt as follows:
set classpath=%classpath%; C:\Program Files\Apache Group\Tomcat 1.4\common\lib\servlet.jar

or you can also use following classpath at compailation time as

c:/>Javac FirstServlet.java –classpath “C:\Program Files\
Apache Group\Tomcat 1.4\common\lib\servlet.jar”

Copy the resultant .class file into C:\Program Files\Apache Group\Tomcat1.4\webapps \examples \ WEB-
INF\ classes, so it can be found at runtime.

Running Servlets

To run the servlet FirstServlet, start a Web browser and type

http://localhost:8080/examples/servlet/FirstServlet in the URL

NOTE: You can use the servlet from anywhere on the Internet if your Tomcat is running on a host machine on
the Internet. Suppose the host name is sicet.cse.edu, use the URL http://
sicet.cse.edu:8080/examples/servlet/FirstServlet to test the servlet.

NOTE: If you have modified the servlet, you need to shutdown and restart Tomcat.

TIP: If your servlet class uses packages (e.g., package pros), you have to create a directory named pros under
c:\jakarta-tomcat-4.1.27\webapps\examples\WEB-INF\classes and copy the .class into the new directory.
You have to use the URL http://localhost:8080/examples/servlet/.FirstServlet to invoke the servlet.
Web Technologies III B.Tech II Sem (R09) CSE UNIT-V
Prepared by A. Sharath Kumar
(M.Tech), Asst.Prof
Page 3


Running JSP
To run a JSP (e.g., Factorial.jsp), store it in webapps/examples/jsp, start a Web browser and type
http://localhost:8080/examples/jsp/Factorial.jsp in the URL

Using JSDK Web Server

For the windows machine, the default location of version 2 of the JSDK is c:\jsdk2.0. The directory
c:\jsdk2.0\bin contains servletrunner.exe. update your path environment variable so that it includes this
directory. The directory c:\jsdk2.0\lib contains jsdk.jar. This JAR file contains the classes and interfaces that
are needed to build servlets. Update your CLASSPATH environment variable so that it includes
c:\jsdk2.0\lib\jsdk.jar

The JSDK comes with the jsdk WebServer so you can test your servlets. The JSDK WebServer assumes that the
.class files for the servlets are installed in the subdirectory
Webpages\WEB-INF\servlets

In the JSDK install directory are a windows batch file (startserver.bat) can be used to start the JSDK
WebServer on windows. The JSDK also provides stopserver.bat to terminate the JSDK WebServer.

To test your webserver type in web browser url as
http://localhost:8080


Servlet Interfaces and Servlet Life Cycle:

Architecturally, all servlets must implement the Servlet interfaces. This interface defines five methods


void init(ServletConfig cnfig)
The Servlet container calls this method once during a servlet’s execution cycle to initialize the Servlet.
The ServletConfig argument is supplied by the Servlet container that executes the Servlet.
ServletConfig getServletConfig()
This method returns a reference to an object that implements interface ServletConfig. This object
provides access to the servlet’s configuration information such as Servlet initialization parameters and
servlet’s ServletContext, which provides the Servlet e with access to its environment.
String getServletInfo()
This method is defined by a servlet programmer to return a string containing Servlet information such
as the servlet’s author and version.
Web Technologies III B.Tech II Sem (R09) CSE UNIT-V
Prepared by A. Sharath Kumar
(M.Tech), Asst.Prof
Page 4

void service(ServletRequest request, ServletResponse response)
The Servlet container calls this method to respond to a client request to the servlet.
void destroy()
This “cleanup” method is called when a Servlet is terminated by its Servlet container. Resources used
by the Servlet, such as open file or an open database connection, should be deallocated here.

A Servlet life cycle begins when the Servlet container loads the Servlet into memory. Now it is ready to
respond the requests. Before the Servlet can handle that request, the Servlet container invokes the servlet’s
init method. After init completes execution, the Servlet can respond to its first request. All requests are
handled by a servlet’s service method, which receives the request, process the request and sends a response to
the client. During a servlet’s life cycle, method service is called once per request. Each new request typically
results in a new thread of execution in which method service executes. When Servlet container terminates the
servlet, the servlet’s destroy method is called to release servlet resources.

Servlet Interfaces:
The servlet packages define two abstract classes that implement the interfaces Servlet-class GenericServlet
(from package javax.servlet) and class HttpServlet (from package javax.servlet.http). These classes provide
default implementations of all the servlet methods.

HttpServlet Class:
Web based servlets typically extend class HttpServlet. Class HttpServlet overrides method service() to
distinguish between the typical requests received from a client web browser. The two common HTTP request
methods are get() and post(). A get() request gets (or receives) information from a server. Common uses of
get requests are to retrieve an HTML document or an image. A post() request posts (or sends) data to a
server. Common uses of post requests typically sends information, such as authentication information or
data from a form that gathers user input, to server.
Class HttpServlet defines methods doGet and doPost to respond to get and post requests from a client,
respectively. These methods are called by method service, which is called when a request arrives at the
server.

HttpServletRequest Interface:
Every call to doGet or doPost for an HttpServlet receives an object that implements interface
HttpServletRequest. The Web server that executes the servlet creates an HttpServletRequest object and passes
this to the servlet’s service() method. A few key methods are given below:
Styring getParameter(String name)
Obtain the value of a parameter sent to the servlet as part of a get or post request. The name
argument represents the parameter name.
Enumeration getParameterNames()
Returns the names of all the parameters sent to the servlet as part of a post request.
String[] getParameterValues(String name)
For a parameter with multiple values, this method returns an array of strings containing the values for
a specified servlet parameter.
Cookie[] getCookes()
Return an array of Cookie objects stored on the client by the server. Cookie objects can be used to
uniquely identify clients to the servlet.
HttpSession getSession(Boolean create)
Return an HttpSession Object associated with the client’s current browsing session. This method can
create an HttpSession object if one does not already exist for the client. HttpSession objects are used in similar
ways to Cookies for uniquely identifying clients.

HttpServletResponse Interfce:
Web Technologies III B.Tech II Sem (R09) CSE UNIT-V
Prepared by A. Sharath Kumar
(M.Tech), Asst.Prof
Page 5

Every call to doGet or doPost for an HttpServlet receives an object that implements interface
HttpServletResponse. The Web server that executes the servlet creates an HttpServletResponse object and
passes this to the servlet’s service() method. A few key methods are given below:
void addCookie(Cookie cookie)
Used to add a Cookie to the header of the response to the client. The Cookie’s maximum age and
whether Cookies are enabled on the client determine if Cookies are stored on the client.
ServletOutputStream getOutputStream()
Obtains a byte-based output stream for sending binary data to the client.
PrintWriter getWriter()
Obtains a character-based output stream for sending text data to the client
void setContentType(String type)
Specifies the MIME type of the response to the browser. The MIME type helps the browser determine
how to display the data. For example, MIME type “text/html” indicates that the response is an HTML
document, so the browser displays the HTML page.

Getting Started with Servlets

import
java.io.*;
import
javax.servlet.*;
import
javax.servlet.http.*;
public class
ThirdServlet
extends
HttpServlet {

public
void
doGet(HttpServletRequest req, HttpServletResponse res)

throws
ServletException, IOException {

res.setContentType(
"text/html"
);

PrintWriter out = res.getWriter();

out.println(
"<HTML>"
);

out.println(
"<HEAD><TITLE>
Hello
</TITLE></HEAD>"
);

out.println(
"<BODY>
Welcome to Servlets
"
);

out.println(
"</BODY></HTML>"
);

}
}

This servlet extends the HttpServlet class and overrides the doGet() method inherited from it. Each time the
web server receives a GET request for this servlet, the server invokes this doGet() method, passing it an
HttpServletRequest object and an HttpServletResponse object.

The HttpServletRequest represents the client's request. This object gives a servlet access to information about
the client, the parameters for this request, the HTTP headers passed along with the request, and so forth.

The HttpServletResponse represents the servlet's response. A servlet can use this object to return data to the
client. This data can be of any content type, though the type should be specified as part of the response.

Our servlet first uses the setContentType() method of the response object to set the content type of its
response to "text/html", the standard MIME content type for HTML pages. Then, it uses the getWriter()
method to retrieve a PrintWriter , the international-friendly counterpart to a PrintStream. PrintWriter
converts Java's Unicode characters to a locale-specific encoding. For an English locale, it behaves same as a
PrintStream. Finally, the servlet uses this PrintWriter to send its "
Welcome to Servlets
" HTML to the client.
Reading Servlet Parameters
The ServletRequest class includes methods that allow you to read the names and values of parameters that
are included in a client request. We will develop a servlet that illustrates their use. The example contains two
files. A Web page is defined in test.htm and a servlet is defined in ThirdServlet.java.
Web Technologies III B.Tech II Sem (R09) CSE UNIT-V
Prepared by A. Sharath Kumar
(M.Tech), Asst.Prof
Page 6


The HTML source code for test.htm is shown in the following listing. It defines label, text field and a submit
button. Notice that the action parameter of the form tag specifies a URL. The URL identifies the servlet to
process the HTTP GET request.

The source code for ThirdServlet.java is shown in the following listing. The doGet( ) method is overridden to
process client requests. The getParameterNames( ) method returns an enumeration of the parameter names.
The parameter value is obtained via the getParameter( ) method.

import
java.io.*;
import
javax.servlet.*;
import
javax.servlet.http.*;
public class
ThirdServlet
extends
HttpServlet {
public
void
doGet(HttpServletRequest req, HttpServletResponse res)

throws
ServletException, IOException {

res.setContentType(
"text/html"
);

PrintWriter out = res.getWriter();

String name = req.getParameter(
"name"
);

out.println(
"<HTML>"
);

out.println(
"<HEAD><TITLE>Hello, "
+ name +
"</TITLE></HEAD>"
);

out.println(
"<BODY>"
);

out.println(
"Hello, "
+ name);

out.println(
"</BODY></HTML>"
);

}
}


<HTML>
<HEAD><TITLE>Introductions</TITLE></HEAD>
<BODY>
<FORM METHOD=GET
ACTION="http://localhost:8080/examples/servlet/ThirdServlet">
If you don't mind me asking, what is your name?
<INPUT TYPE=TEXT NAME="name"><P>
<INPUT TYPE=SUBMIT>
</FORM></BODY>
</HTML>

Differences between GET and POST service methods

A GET request is a request to get a resource from the server. Choosing GET as the "method" will append all of
the data to the URL and it will show up in the URL bar of your browser. The amount of information you can
send back using a GET is restricted as URLs can only be 1024 characters.

A POST request is a request to post (to send) form data to a resource on the server. A POST on the other hand
will (typically) send the information through a socket back to the webserver and it won't show up in the URL
bar. You can send much more information to the server this way - and it's not restricted to textual data either.
It is possible to send files and even binary data such as serialized Java objects!



Web Technologies III B.Tech II Sem (R09) CSE UNIT-V
Prepared by A. Sharath Kumar
(M.Tech), Asst.Prof
Page 7

Cookies

Cookies are small bits of textual information that a Web server sends to a browser and that the browser
returns unchanged when visiting the same Web site or domain later. By having the server read information it
sent the client previously, the site can provide visitors with a number of conveniences.

To send cookies to the client, a servlet would create one or more cookies with the appropriate names and
values via new Cookie(name, value), set any desired optional attributes via cookie.setXxx , and add the
cookies to the response headers via response.addCookie(cookie). To read incoming cookies, call
request.getCookies(), which returns an array of Cookie objects. In most cases, you loop down this array until
you find the one whose name (getName) matches the name you have in mind, then call getValue on that
Cookie to see the value associated with that name.

Creating Cookies
A Cookie is created by calling the Cookie constructor, which takes two strings: the cookie name and the
cookie value.

Attributes of the Cookies:
Before adding the cookie to the outgoing headers, you can look up or set attributes of the cookie.

getComment/setComment
Gets/sets a comment associated with this cookie.

getMaxAge/setMaxAge
Gets/sets how much time (in seconds) should elapse before the cookie expires. If you don't set this, the cookie
will last only for the current session (i.e. until the user quits the browser), and will not be stored on disk. See
the LongLivedCookie class below, which defines a subclass of Cookie with a maximum age automatically set
one year in the future.

getName/setName
Gets/sets the name of the cookie. The name and the value are the two pieces you virtually always care about.
Since the getCookies method of HttpServletRequest returns an array of Cookie objects, it is common to loop
down this array until you have a particular name, then check the value with getValue. See the
getCookieValue method shown below.

getPath/setPath
Gets/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. This method can be used to specify
something more general. For example, someCookie.setPath("/") specifies that all pages on the server should
receive the cookie. Note that the path specified must include the current directory.

getSecure/setSecure
Gets/sets the boolean value indicating whether the cookie should only be sent over encrypted (i.e. SSL)
connections.

getValue/setValue
Gets/sets the value associated with the cookie. Again, the name and the value are the two parts of a cookie
that you almost always care about, although in a few cases a name is used as a boolean flag, and its value is
ignored (i.e the existence of the name means true).


Web Technologies III B.Tech II Sem (R09) CSE UNIT-V
Prepared by A. Sharath Kumar
(M.Tech), Asst.Prof
Page 8

Reading Cookies from the Client
To send cookies to the client, you created a Cookie then used addCookie to send a Set-Cookie HTTP response
header. Read the cookies that come back from the client, you call getCookies on the HttpServletRequest. This
returns an array of Cookie objects corresponding to the values that came in on the Cookie HTTP request
header. Once you have this array, you typically loop down it, calling getName on each Cookie until you find
one matching the name you have in mind. You then call getValue on the matching Cookie, doing some
processing specific to the resultant value. This is such a common process that the following section presents a
simple getCookieValue method that, given the array of cookies, a name, and a default value, returns the value
of the cookie matching the name, or, if there is no such cookie, the designated default value

(Example: Lab Exercise program on Authentication program using cookies)