Tomcat JSP and Servlet Guide
Tomcat JSP and Servlet Guide
Java Servlets: Java Servlet and CGI programming- A simple java Servlet-Anatomy of a
java Servlet-Reading data from a client-Reading http request header-sending data to
a client and writing the http response header-working with cookies . Java Server
Pages: JSP Overview-Installation-JSP tags-Components of a JSP page- Expressions-
Scriptlets-Directives-Declarations-A complete example.
Java Servlet:
Servlet technology is used to create a web application (resides at server side and
generates a dynamic web page).
CGI technology enables the web server to call an external program and pass HTTP request
information to the external program to process the request. For each request, it starts a
new process.
Disadvantages of CGI
1. If the number of clients increases, it takes more time for sending the response.
2. For each request, it starts a process, and the web server is limited to start processes.
3. It uses platform dependent language e.g. C, C++, perl.
Advantages of Servlet
There are many advantages of Servlet over CGI. The web container creates threads for
handling the multiple requests to the Servlet. Threads have many benefits over the
Processes such as they share a common memory area, lightweight, cost of communication
between the threads are low. The advantages of Servlet are as follows:
1. Better performance: because it creates a thread for each request, not process.
2. Portability: because it uses Java language.
3. Robust: JVM manages Servlets, so we don't need to worry about the memory
leak, garbage collection, etc.
4. Secure: because it uses java language.
The classloader is responsible to load the servlet class. The servlet class is loaded when the
first request for the servlet is received by the web container.
The web container creates the instance of a servlet after loading the servlet class. The
servlet instance is created only once in the servlet life cycle.
The web container calls the init method only once after creating the servlet
instance. The init method is used to initialize the servlet. It is the life cycle
method of the [Link] interface. Syntax of the init method is
given below:
public void init(ServletConfig config) throws ServletException
The web container calls the service method each time when request for the servlet is
received. If servlet is not initialized, it follows the first three steps as described above then
calls the service method. If servlet is initialized, it calls the service method. Notice that
servlet is initialized only once. The syntax of the service method of the Servlet interface is
given below:
The web container calls the destroy method before removing the servlet instance from the
service. It gives the servlet an opportunity to clean up any resource for example memory,
thread etc. The syntax of the destroy method of the Servlet interface is given below:
There are given 6 steps to create a servlet example. These steps are required for all the
servers.
The mostly used approach is by extending HttpServlet because it provides http request
specific method such as doGet(), doPost(), doHead() etc.
Here, we are going to use apache tomcat server in this example. The steps are as follows:
The directory structure defines that where to put the different types of files so that
web container may get the information and respond to the client.
The Sun Microsystem defines a unique standard to be followed by all the server
vendors. Let's see the directory structure that must be followed to create the servlet.
As you can see that the servlet class file must be in the classes folder. The [Link]
file must be under the WEB-INF folder.
2)Create a Servlet
The HttpServlet class is widely used to create the servlet because it provides
methods to handle http requests such as doGet(), doPost, doHead() etc.
In this example we are going to create a servlet that extends the HttpServlet
class. In this example, we are inheriting the HttpServlet class and providing
the implementation of the doGet() method. Notice that get request is the
default request.
[Link]
import [Link].*;
import [Link].*;
import [Link].*;
public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
[Link]("text/html");//setting the content type
PrintWriter pw=[Link]();//get the stream to write the data
For compiling the Servlet, jar file is required to be loaded. Different Servers provide
different jar files:
1. set classpath
2. paste the jar file in JRE/lib/ext folder
Put the java file in any folder. After compiling the java file, paste the class file of servlet
in WEB-INF/classes directory.
The deployment descriptor is an xml file, from which Web Container gets the information
about the servet to be invoked.
The web container uses the Parser to get the information from the [Link] file. There are
many xml parsers such as SAX, DOM and Pull.
There are many elements in the [Link] file. Here is given some necessary elements to run
the simple servlet program.
[Link] file
<web-app>
<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
To start Apache Tomcat server, double click on the [Link] file under
apache-tomcat/bin directory.
[Link]
Reading data from a client-Reading http request header
When a browser requests for a web page, it sends lot of information to the web server
which cannot be read directly because this information travel as a part of header of HTTP
request. You can check HTTP Protocol for more information on this.
Following is the important header information which comes from browser side and you
would use very frequently in web programming
Accept
This header specifies the MIME types that the browser
or other clients can handle. Values
of image/png or image/jpeg are the two most
common possibilities.
Accept-Charset
This header specifies the character sets the browser
can use to display the information. For example ISO-
8859-1.
Accept-Encoding
This header specifies the types of encodings that the
browser knows how to handle. Values
of gzip or compress are the two most common
possibilities.
Accept-Language
This header specifies the client's preferred languages
in case the servlet can produce results in more than
one language. For example en, en-us, ru, etc
Authorization
This header is used by clients to identify themselves
when accessing password-protected Web pages.
Connection
This header indicates whether the client can handle
persistent HTTP connections. Persistent connections
permit the client or other browser to retrieve multiple
files with a single request. A value of Keep-
Alive means that persistent connections should be
used.
Content-Length
This header is applicable only to POST requests and
gives the size of the POST data in bytes.
Cookie
This header returns cookies to servers that previously
sent them to the browser.
Host
This header specifies the host and port as given in the
original URL.
If-Modified-Since
This header indicates that the client wants the page
only if it has been changed after the specified date. The
server sends a code, 304 which means Not
Modified header if no newer result is available.
If-Unmodified-Since
This header is the reverse of If-Modified-Since; it
specifies that the operation should succeed only if the
document is older than the specified date.
Referer
This header indicates the URL of the referring Web
page. For example, if you are at Web page 1 and click
on a link to Web page 2, the URL of Web page 1 is
included in the Referrer header when the browser
requests Web page 2.
User-Agent
This header identifies the browser or other client
making the request and can be used to return different
content to different types of browsers.
String getRequestURI()
Returns the part of this request's URL from the protocol
name up to the query string in the first line of the HTTP
request.
String getRequestedSessionId()
Returns the session ID specified by the client.
String getServletPath()
Returns the part of this request's URL that calls the JSP.
String[] getParameterValues(String name)
Returns an array of String objects containing all of the
values the given request parameter has, or null if the
parameter does not exist.
boolean isSecure()
Returns a Boolean indicating whether this request was
made using a secure channel, such as HTTPS.
int getContentLength()
Returns the length, in bytes, of the request body and
made available by the input stream, or -1 if the length is
not known.
int getIntHeader(String name)
Returns the value of the specified request header as an
int.
int getServerPort()
Returns the port number on which this request was
received.
import [Link].*;
import [Link].*;
// Extend HttpServlet class
public class DisplayHeader extends HttpServlet {
[Link](docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n"+
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<table width = \"100%\" border = \"1\" align
= \"center\">\n" +
"<tr bgcolor = \"#949494\">\n" +
"<th>Header Name</th><th>Header
Value(s)</th>\n"+
"</tr>\n"
);
Enumeration headerNames =
[Link]();
while([Link]()) {
String paramName =
(String)[Link]();
[Link]("<tr><td>" + paramName + "</td>\n");
String paramValue =
[Link](paramName);
[Link]("<td> " + paramValue + "</td></tr>\n");
}
[Link]("</table>\n</body></html>");
}
doGet(request, response);
}
}
accept */*
accept-
en-us
language
accept-
gzip, deflate
encoding
host localhost:8080
connection Keep-Alive
cache-control no-cache
After receiving and interpreting a request message, a server responds with an HTTP
response message:
A Status-line
Zero or more header (General|Response|Entity) fields followed by CRLF
An empty line (i.e., a line with nothing preceding the CRLF)
indicating the end of the header fields
Optionally a message-body
The following sections explain each of the entities used in an HTTP response message.
Message Status-Line
A Status-Line consists of the protocol version followed by a numeric status code and its
associated textual phrase. The elements are separated by space SP characters.
HTTP Version
A server supporting HTTP version 1.1 will return the following version information:
HTTP-Version = HTTP/1.1
Status Code
The Status-Code element is a 3-digit integer where first digit of the Status-Code defines the
class of response and the last two digits do not have any categorization role. There are 5
values for the first digit:
1xx: Informational
1
It means the request was received and the process is continuing.
2xx: Success
2
It means the action was successfully received, understood, and accepted.
3xx: Redirection
3
It means further action must be taken in order to complete the request.
HTTP status codes are extensible and HTTP applications are not required to understand
the meaning of all registered status codes. A list of all the status codes has been given in a
separate chapter for your reference.
We will study General-header and Entity-header in a separate chapter when we will learn
HTTP header fields. For now, let's check what Response header fields are.
The response-header fields allow the server to pass additional information about the
response which cannot be placed in the Status- Line. These header fields give information
about the server and about further access to the resource identified by the Request-URI.
Accept-Ranges
Age
ETag
Location
Proxy-Authenticate
Retry-After
Server
Vary
WWW-Authenticate
You can introduce your custom fields in case you are going to write your own custom Web
Client and Server.
The following example shows an HTTP response message displaying error condition when
the web server could not find the requested page:
Following is an example of HTTP response message showing error condition when the web
server encountered a wrong HTTP version in the given HTTP request:
o When a user sends a request to the server, then each of that request is treated as a
new request sent by the different user.
o So, to recognize the old user, we need to add the cookie with the response from the
server.
o browser at the client-side.
o Now, whenever a user sends a request to the server, the cookie is added with that
request automatically. Due to the cookie, the server recognizes the users.
[Link]="name=value";
Example
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="button" value="setCookie" onclick="setCookie()">
<input type="button" value="getCookie" onclick="getCookie()">
<script>
function setCookie()
{
[Link]="username=Duke Martin";
}
function getCookie()
{
if([Link]!=0)
{
alert([Link]);
}
else
{
alert("Cookie not available");
}
}
</script>
</body>
</html>
JSP – Overview:
Java Server Pages (JSP) is a technology for developing Webpages that supports dynamic
content. This helps developers insert java code in HTML pages by making use of special JSP
tags, most of which start with <% and end with %>.A JavaServer Pages component is a type
of Java servlet that is designed to fulfill the role of a user interface for a Java web
application. Web developers write JSPs as text files that combine HTML or XHTML code,
XML elements, and embedded JSP actions and [Link] JSP, you can collect input
from users through Webpage forms, present records from a database or another source,
and create Webpages [Link] tags can be used for a variety of purposes, such as
retrieving information from a database or registering user preferences, accessing
JavaBeans components, passing control between pages, and sharing information between
requests, pages etc.
JavaServer Pages often serve the same purpose as programs implemented using
the Common Gateway Interface (CGI). But JSP offers several advantages in comparison
with the CGI.
JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also
has access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB,
JAXP, etc.
JSP pages can be used in combination with servlets that handle the business logic,
the model supported by Java servlet template engines.
Finally, JSP is an integral part of Java EE, a complete platform for enterprise class
applications. This means that JSP can play a part in the simplest applications to the most
complex and demanding.
Advantages of JSP
Following table lists out the other advantages of using JSP over other technologies −
The advantages of JSP are twofold. First, the dynamic part is written in Java, not Visual
Basic or other MS specific language, so it is more powerful and easier to use. Second, it is
portable to other operating systems and non-Microsoft Web servers.
SSI is really only intended for simple inclusions, not for "real" programs that use form data,
make database connections, and the like.
vs. JavaScript
JavaScript can generate HTML dynamically on the client but can hardly interact with the
web server to perform complex tasks like database access and image processing etc.
Installation-JSP:
A development environment is where you would develop your JSP programs, test them and
finally run them.
This step involves downloading an implementation of the Java Software Development Kit
(SDK) and setting up the 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 the 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 install the SDK in C:\jdk1.5.0_20, you need to add the
following line in your C:\[Link] file.
set PATH = C:\jdk1.5.0_20\bin;%PATH%
set JAVA_HOME = C:\jdk1.5.0_20
A number of Web Servers that support JavaServer Pages and Servlets development are
available in the market. Some web servers can be downloaded for free and Tomcat is one of
them.
Apache Tomcat is an open source software implementation of the JavaServer Pages and
machine
Tomcat can be started by executing the following commands on the Windows machine −
%CATALINA_HOME%\bin\[Link]
or
C:\apache-tomcat-5.5.29\bin\[Link]
Tomcat can be started by executing the following commands on the Unix (Solaris, Linux,
etc.) machine −
$CATALINA_HOME/bin/[Link]
or
/usr/local/apache-tomcat-5.5.29/bin/[Link]
After a successful startup, the default web-applications included with Tomcat will be
available by visiting [Link]
Upon execution, you will receive the following output −
Further information about configuring and running Tomcat can be found in the
documentation included here, as well as on the Tomcat web site
− [Link]
Tomcat can be stopped by executing the following commands on the Windows machine −
%CATALINA_HOME%\bin\shutdown
or
C:\apache-tomcat-5.5.29\bin\shutdown
Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.)
machine −
$CATALINA_HOME/bin/[Link]
or
/usr/local/apache-tomcat-5.5.29/bin/[Link]
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:\
[Link] file.
set CATALINA = C:\apache-tomcat-5.5.29
set CLASSPATH = %CATALINA%\common\lib\[Link];%CLASSPATH%
Alternatively, on Windows NT/2000/XP, you can also right-click on My Computer,
select Properties, then Advanced, then Environment Variables. Then, you would update
the CLASSPATH value and press the OK button.
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/[Link]:$CLASSPATH
NOTE –
Assuming that your development directory is C:\JSPDev (Windows) or /usr/JSPDev
(Unix), then you would need to add these directories as well in CLASSPATH.
1. Directive Tag:
Directive tags provide general information about the JSP page to the JSP engine. A directive
tag always starts with <%@ and ends with %>.
In the above shown syntax, the attribute-list represents one or more attribute value-pairs
that are specific to the directive. Some important points that are needed to be remembered
about the syntax of the directive are as follows:
The tag names, their attributes, and their values are all case sensitive.
The value must be enclosed within a pair of single or double quotes.
A pair of single quotes is equivalent to a pair of double quotes.
There must be no space between the equals sign (=) and the value.
A page directive informs the JSP engine about the overall properties of a JSP page. For
example, the following page directives inform the JSP engine that Java will be used as
scripting language in our JSP page:
<%@ page language=”java” %>
An include directive tells the JSP engine to include the contents of another file (HTML, JSP,
etc) into the current file. For example:
<%@ include file=”[Link]” %>
or
2. Declaration Tag:
Declarations declare and define variables and methods that can be used in the JSP page (a
JSP declaration can contain any valid Java declaration including inner classes and static code
blocks. However, such declarations are rarely used). A declaration always starts with <%!
and ends with %>.
For e.g.: <%! int i = 0; %>
This declares an integer variable i and initializes to 0. The variable is initialized only once
when the page is first loaded by the JSP engine, and retains its value in subsequent client
requests i.e. the value of i is not reset to 0 each time we access the page. It can contain any
number of valid Java declaration statements. For example, the following tag declares a
variable and a method in a single tag:
<%!
String name[] = {“biswa”, “amit”, “sreejan”};
String getName(int i) {
return name[i];
}
%>
The above declaration can also be written using two separate JSP declaration tags.
3. Scriptlet Tag:
Scriptlets are used to embed any Java code fragments in the JSP page.
4. Expression Tag:
Expression tags are used as a shortcut to print values in the output HTML in a JSP page.
Syntax of Expression tag is:
The expression is evaluated each time the page is accessed, and its value is then embedded
in the output HTML. Unlike variable declarations, expressions must not be terminated with
a semicolon. Thus, the following is not valid: <%= i; %>
The below tables denotes some valid and invalid JSP expressions:
The method does not return any value. The return type
<%= [Link](12); %> is void
5. Action Tag:
Action tags are used to provide request–time instructions to the JSP container or JSP
engine. There are 7 types of action tags. The following table describes various JSP action
tags:
resource to be included.
the bean.
request parameter to be
used.
Defines a
be included.
6. Comment Tag:
Comments are used for documentation purposes but do not affect the output of the JSP
page in any way. The syntax of a JSP comment is:
<%-- Anything you want to be commented --%>
In this example of jsp expression tag, we are simply displaying a welcome message.
<html>
<body>
<%= "welcome to jsp" %>
</body>
</html>
To display the current time, we have used the getTime() method of Calendar class. The
getTime() is an instance method of Calendar class, so we have called it after getting the
instance of Calendar class by the getInstance() method.
<html>
<body>
Current Time: <%= [Link]().getTime() %>
</body>
</html>
In this example, we are printing the username using the expression tag. The [Link] file
gets the username and sends the request to the [Link] file, which displays the
username.
File: [Link]
<html>
<body>
<form action="[Link]">
<input type="text" name="uname"><br/>
<input type="submit" value="go">
</form>
</body>
</html>
File: [Link]
<html>
<body>
<%= "Welcome "+[Link]("uname") %>
</body>
</html>
1. Scripting elements
2. JSP scriptlet tag
3. Simple Example of JSP scriptlet tag
4. Example of JSP scriptlet tag that prints the user name
In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's see what are
the scripting elements first
The scripting elements provides the ability to insert java code inside the jsp. There are
three types of scripting elements.
o scriptlet tag
o expression tag
o declaration tag
A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:
<html>
<body>
<% [Link]("welcome to jsp"); %>
</body>
</html>
In this example, we have created two files [Link] and [Link]. The [Link] file
gets the username from the user and the [Link] file prints the username with the
welcome message.
File: [Link]
<html>
<body>
<form action="[Link]">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
File: [Link]
<html>
<body>
<%
String name=[Link]("uname");
[Link]("welcome "+name);
%>
</form>
</body>
</html>
JSP directives :
The jsp directives are messages that tells the web container how to translate a JSP page
into the corresponding servlet.
o page directive
o include directive
o taglib directive
The page directive defines attributes that apply to an entire JSP page.
1)import
The import attribute is used to import class,interface or all the members of a [Link] is similar to impo
keyword in java class or interface.
<html>
<body>
</body>
</html>
2)contentType
The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type of
the HTTP [Link] default value is "text/html;charset=ISO-8859-1".
<html>
<body>
</body>
</html>
3)extends
The extends attribute defines the parent class that will be inherited by the generated
[Link] is rarely used.
4)info
This attribute simply sets the information of the JSP page which is retrieved later by using
getServletInfo() method of Servlet interface.
<html>
<body>
</body>
</html>
The web container will create a method getServletInfo() in the resulting [Link]
example:
public String getServletInfo() {
return "composed by Sonoo Jaiswal";
}
5)buffer
The buffer attribute sets the buffer size in kilobytes to handle output generated by the JSP
[Link] default size of the buffer is 8Kb.
<html>
<body>
</body>
</html>
6)language
The language attribute specifies the scripting language used in the JSP page. The default
value is "java".
7)isELIgnored
We can ignore the Expression Language (EL) in jsp by the isELIgnored attribute. By default its value is fal
i.e. Expression Language is enabled by default. We see Expression Language later.
1. <%@ page isELIgnored="true" %>//Now EL will be ignored
8)isThreadSafe
Servlet and JSP both are [Link] you want to control this behaviour of JSP page, you can u
isThreadSafe attribute of page [Link] value of isThreadSafe value is [Link] you make it false, the w
container will serialize the multiple requests, i.e. it will wait until the JSP finishes responding to a reque
before passing another request to [Link] you make the value of isThreadSafe attribute like:
The web container in such a case, will generate the servlet as:
9)errorPage
The errorPage attribute is used to define the error page, if exception occurs in the current
page, it will be redirected to the error page.
//[Link]
<html>
<body>
</body>
</html>
10)isErrorPage
The isErrorPage attribute is used to declare that the current page is the error page.
</body>
</html>
<html>
<body>
<% [Link](2*5); %>
</body>
</html>
A complete Example:
<html>
<head><title>First JSP</title></head>
<body>
<%
double num = [Link]();
if (num > 0.95) {
%>
<h2>You'll have a luck day!</h2><p>(<%= num %>)</p>
<%
} else {
%>
<h2>Well, life goes on ... </h2><p>(<%= num %>)</p>
<%
}
%>
<a href="<%= [Link]() %>"><h3>Try Again</h3></a>
</body>
</html>
o execute the JSP script: Simply start your Tomcat server and use a browser to issue an URL
to browse the JSP page (i.e., [Link]
From your browser, choose the "View Source" option to check the response message. It
should be either of the followings depending on the random number generated.
<html>
<h2>You'll have a luck day!</h2>
<p>(0.987)</p>
<a href="[Link]"><h3>Try Again</h3></a>
</html>
<html>
<h2> Well, life goes on ... </h2>
<p>(0.501)</p>
<a href="[Link]"><h3>Try Again</h3></a>
</html>
It is important to note that the client is not able to "view" the original JSP script (otherwise,
you may have security exposure), but merely the result generated by the script.
Explanations
1. A JSP script is a regular HTML page containing Java programs. Recall that JSP is "Java
inside HTML" (whereas servlet is "HTML inside Java"). The Java statements are
enclosed by <% ... %> (called JSP scriptlet) or <%= ... %> (called JSP expression).
2. JSP Scriptlet <% ... %> is used to include Java statements.
3. JSP Expression <%= ... %> is used to evaluate a single Java expression and display its
result.
4. The method [Link]() is used to retrieve the URL of the current page.
This is used in the anchor tag <a> for refreshing the page to obtain another random
number.