0% found this document useful (0 votes)
46 views42 pages

Tomcat JSP and Servlet Guide

The document provides information on Java Servlets and Java Server Pages (JSP). It discusses what servlets are, how they work, and their advantages over CGI. It then covers the anatomy of a servlet including the lifecycle methods. The document provides steps to create a simple Java servlet including setting up the directory structure, creating the servlet class, compiling, creating the deployment descriptor (web.xml), deploying to a server, and accessing the servlet. It also discusses reading data from HTTP requests including important request headers.

Uploaded by

ramyab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views42 pages

Tomcat JSP and Servlet Guide

The document provides information on Java Servlets and Java Server Pages (JSP). It discusses what servlets are, how they work, and their advantages over CGI. It then covers the anatomy of a servlet including the lifecycle methods. The document provides steps to create a simple Java servlet including setting up the directory structure, creating the servlet class, compiling, creating the deployment descriptor (web.xml), deploying to a server, and accessing the servlet. It also discusses reading data from HTTP requests including important request headers.

Uploaded by

ramyab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT IV

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).

 A web application is an application accessible from the web. A web application is


composed of web components like Servlet, JSP, Filter, etc. and other elements such
as HTML, CSS, and JavaScript. The web components typically execute in Web Server
and respond to the HTTP request.

 Servlet is a technology which is used to create a web application.


 Servlet is an API that provides many interfaces and classes including
documentation.
 Servlet is an interface that must be implemented for creating any Servlet.
 Servlet is a class that extends the capabilities of the servers and responds to the
incoming requests. It can respond to any requests.
 Servlet is a web component that is deployed on the server to create a dynamic web
page.
Java Servlet and CGI programming:

CGI (Common Gateway Interface)

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

There are many problems in CGI technology:

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.

Anatomy of a java Servlet:

1. Servlet class is loaded.


2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.
1) Servlet class is loaded

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.

2) Servlet instance is created

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.

3) init method is invoked

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

4) service method is invoked

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:

public void service(ServletRequest request, ServletResponse response)


throws ServletException, IOException

5) destroy method is invoked

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:

public void destroy()

A simple java Servlet

There are given 6 steps to create a servlet example. These steps are required for all the
servers.

The servlet example can be created by three ways:


1. By implementing Servlet interface,
2. By inheriting GenericServlet class, (or)
3. By inheriting HttpServlet class

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:

1. Create a directory structure


2. Create a Servlet
3. Compile the Servlet
4. Create a deployment descriptor
5. Start the server and deploy the project
6. Access the servlet

1)Create a directory structures

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

There are three ways to create the servlet.


1. By implementing the Servlet interface
2. By inheriting the GenericServlet class
3. By inheriting the HttpServlet class

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

//writing html in the stream


[Link]("<html><body>");
[Link]("Welcome to servlet");
[Link]("</body></html>");

[Link]();//closing the stream


}}

3)Compile the servlet

For compiling the Servlet, jar file is required to be loaded. Different Servers provide
different jar files:

Jar file Server

1) [Link] Apache Tomcat


2) [Link] Weblogic
3) [Link] Glassfish
4) [Link] JBoss

Two ways to load the jar file

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.

4)Create the deployment descriptor ([Link] file)

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>

Description of the elements of [Link] file


There are too many elements in the [Link] file. Here is the illustration of some elements
that is used in the above [Link] file. The elements are as follows:

<web-app> represents the whole application.


<servlet> is sub element of <web-app> and represents the servlet.
<servlet-name> is sub element of <servlet> represents the name of the
servlet.
<servlet-class> is sub element of <servlet> represents the class of the
servlet.
<servlet-mapping> is sub element of <web-app>. It is used to map the
servlet.
<url-pattern> is sub element of <servlet-mapping>. This pattern is used at
client side to invoke the servlet.

5)Start the Server and deploy the project

To start Apache Tomcat server, double click on the [Link] file under
apache-tomcat/bin directory.

6) How to access the servlet

Open broser and write [Link] For


example:

[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

Header and Description

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.

Methods to read HTTP Header


There are following methods which can be used to read HTTP header in your servlet
program. These methods are available with HttpServletRequest object

Method & Description


Cookie[] getCookies()
Returns an array containing all of the Cookie objects the
client sent with this request.
Enumeration getAttributeNames()
Returns an Enumeration containing the names of the
attributes available to this request.
Enumeration getHeaderNames()
Returns an enumeration of all the header names this
request contains.
Enumeration getParameterNames()
Returns an Enumeration of String objects containing the
names of the parameters contained in this request
HttpSession getSession()
Returns the current session associated with this request,
or if the request does not have a session, creates one.
HttpSession getSession(boolean create)
Returns the current HttpSession associated with this
request or, if if there is no current session and value of
create is true, returns a new session.
Locale getLocale()
Returns the preferred Locale that the client will accept
content in, based on the Accept-Language header.
Object getAttribute(String name)
Returns the value of the named attribute as an Object, or
null if no attribute of the given name exists.
ServletInputStream getInputStream()
Retrieves the body of the request as binary data using a
ServletInputStream.
String getAuthType()
Returns the name of the authentication scheme used to
protect the servlet, for example, "BASIC" or "SSL," or null
if the JSP was not protected.
String getCharacterEncoding()
Returns the name of the character encoding used in the
body of this request.
String getContentType()
Returns the MIME type of the body of the request, or null
if the type is not known.
String getContextPath()
Returns the portion of the request URI that indicates the
context of the request.
String getHeader(String name)
Returns the value of the specified request header as a
String.
String getMethod()
Returns the name of the HTTP method with which this
request was made, for example, GET, POST, or PUT.
String getParameter(String name)
Returns the value of a request parameter as a String, or
null if the parameter does not exist.
String getPathInfo()
Returns any extra path information associated with the
URL the client sent when it made this request
String getProtocol()
Returns the name and version of the protocol the
request.
String getQueryString()
Returns the query string that is contained in the request
URL after the path.
String getRemoteAddr()
Returns the Internet Protocol (IP) address of the client
that sent the request.
String getRemoteHost()
Returns the fully qualified name of the client that sent the
request.
String getRemoteUser()
Returns the login of the user making this request, if the
user has been authenticated, or null if the user has not
been authenticated.

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.

HTTP Header Request Example


Following is the example which
ses getHeaderNames() method of HttpServletRequest to
read the HTTP header information. This method returns
an Enumeration that contains the header information
associated with the current HTTP request.
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

// Import required java libraries


import [Link].*;
import [Link].*;

import [Link].*;
import [Link].*;
// Extend HttpServlet class
public class DisplayHeader extends HttpServlet {

// Method to handle GET method request.


public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

// Set response content type


[Link]("text/html");

PrintWriter out = [Link]();


String title = "HTTP Header Request Example";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";

[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>");
}

// Method to handle POST method request.


public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

doGet(request, response);
}
}

Now calling the above servlet would generate the


following result −

HTTP Header Request Example

Header Name Header Value(s)

accept */*

accept-
en-us
language

Mozilla/4.0 (compatible; MSIE 7.0;


user-agent Windows NT 5.1; Trident/4.0;
InfoPath.2; MS-RTC LM 8)

accept-
gzip, deflate
encoding

host localhost:8080

connection Keep-Alive

cache-control no-cache

Sending data to a client and writing the http response header:

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.

Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF

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:

S.N. Code and Description

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.

4 4xx: Client Error


It means the request contains incorrect syntax or cannot be fulfilled.

5xx: Server Error


5
It means the server failed to fulfill an apparently valid 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.

Response Header Fields

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.

Examples of Response Message


Now let's put it all together to form an HTTP response for a request to fetch
the [Link] page from the web server running on [Link]
HTTP/1.1 200 OK
Date: Mon, 27 Jul 2009 [Link] GMT
Server: Apache/2.2.14 (Win32)
Last-Modified: Wed, 22 Jul 2009 [Link] GMT
Content-Length: 88
Content-Type: text/html
Connection: Closed
<html>
<body>
<h1>Hello, World!</h1>
</body>
</html>

The following example shows an HTTP response message displaying error condition when
the web server could not find the requested page:

HTTP/1.1 404 Not Found


Date: Sun, 18 Oct 2012 [Link] GMT
Server: Apache/2.2.14 (Win32)
Content-Length: 230
Connection: Closed
Content-Type: text/html; charset=iso-8859-1
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head>
<title>404 Not Found</title>
</head>
<body>
<h1>Not Found</h1>
<p>The requested URL /[Link] was not found on this server.</p>
</body>
</html>

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:

HTTP/1.1 400 Bad Request


Date: Sun, 18 Oct 2012 [Link] GMT
Server: Apache/2.2.14 (Win32)
Content-Length: 230
Content-Type: text/html; charset=iso-8859-1
Connection: Closed

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">


<html>
<head>
<title>400 Bad Request</title>
</head>
<body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.</p>
<p>The request line contained invalid characters following the protocol string.</p>
</body>
</html>

working with cookies:


A cookie is an amount of information that persists between a server-side and a client-side.
A web browser stores this information at the time of browsing. A cookie contains the
information as a string generally in the form of a name-value pair separated by semi-
colons. It maintains the state of a user and remembers the user's information among all the
web pages.

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.

In JavaScript, we can create, read, update and delete a cookie by


using [Link] property.

The following syntax is used to create a cookie:

[Link]="name=value";
Example

Let's see an example to set and get a cookie.

<!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.

 Performance is significantly better because JSP allows embedding Dynamic


Elements in HTML Pages itself instead of having separate CGI files.
 JSP are always compiled before they are processed by the server unlike CGI/Perl
which requires the server to load an interpreter and the target script each time the
page is requested.

 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 −

vs. Active Server Pages (ASP)

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.

vs. Pure Servlets


It is more convenient to write (and to modify!) regular HTML than to have plenty of println
statements that generate the HTML.

vs. Server-Side Includes (SSI)

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.

vs. Static HTML

Regular HTML, of course, cannot contain dynamic information.

Installation-JSP:

A development environment is where you would develop your JSP programs, test them and
finally run them.

Setting up Java Development Kit

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

Alternatively, on Windows NT/2000/XP, you can also right-click on My Computer,


select Properties, then Advanced, followed by Environment Variables. Then, you would
update the PATH value and press the OK button.
On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and you use
the C shell, you will put the following into your .cshrc file.
setenv PATH /usr/local/jdk1.5.0_20/bin:$PATH
setenv JAVA_HOME /usr/local/jdk1.5.0_20
Alternatively, if you use an Integrated Development Environment (IDE) like Borland
JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to
confirm that the IDE knows where you installed Java.

Setting up Web Server: Tomcat

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

 Download the latest version of Tomcat from [Link]


 Once you downloaded the installation, unpack the binary distribution into a
convenient location. For example, in C:\apache-tomcat-5.5.29 on windows, or
/usr/local/apache-tomcat-5.5.29 on Linux/Unix and
create CATALINA_HOME environment variable pointing to these locations.

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.

JSP tags-Components of a JSP page:

JSP Tag Brief Description Tag Syntax

Specifies translation time instructions to the


JSP engine.
Directive <%@ directives %>

Declaration Declares and defines methods


and variables. <%! variable dceclaration &
Declaration method definition %>

Allows the developer to write free-form Java


code in a JSP page.
Scriptlet <% some Java code %>

Used as a shortcut to print values in the


output HTML of a JSP page.
Expression <%= an Expression %>

Provides request-time instructions to the JSP


engine.
Action <jsp:actionName />
Used for documentation and for commenting
out parts of JSP code.
Comment <%– any Text –%>

Example code showing different types of JSP Tags:


<%-- [Link] --%> <%-- Comment Tag --%>

<%@ page language="java" %> <%-- Directive Tag --%>


<%! int count = 0; %> <%-- Declaration Tag --%>
<% count++; %> <%-- Scriptlet Tag --%>
Welcome! You are visitor number
<%= count %> <%-- Expression Tag --%>
Note: Here, by using comment tag, example of five JSP tags are shown.

Discussions about the JSP Tags


Different types of JSP Tags are discussed below one-by-one.

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 %>.

There are 3 types of directives: page, include, and taglib.


The general syntax for the 3 directives is:

<%@ page attribute-list %>


<%@ include attribute-list %>
<%@ taglib attribute-list %>

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

<%@ include file=”[Link]” %>


A taglib directive is used to associate a prefix with a tag library. For example:
<%@ taglib prefix=”test” uri=”[Link]” %>

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.

For example: <% i++; %>


Here the scriptlet tag is executed and the value of i is incremented each time the page is
requested. We can use scriptlets for printing HTML statements also. For e.g.:
<%@ page language="java" %>
<%! int i = 0; %>
<%
[Link]("");
i++;
[Link]("The value of i is now: " + i);
[Link]("");
%>

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:

<%= variable %>


The variable denotes the variable value that is needed to be printed in the output HTML
page. For e.g.: <%= i %>

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:

Valid JSP Expressions:


Expression Explanation

<%= 500 %> An integral literal

<%= anInt*3.5/100-500 %> An arithmetic expression

<%= aBool %> A Boolean variable

<%= false %> A Boolean literal


<%= !false %> A Boolean expression

<%= getChar() %> A method returning a char

<%= [Link]() %> A method returning a double

<%= aVector %> A variable referring to a Vector object

<%= aFloatObj %> A method returning a float

<%= [Link]() %> A method returning a float

<%= [Link]() %> A method that returns a String object

Invalid JSP expressions:


Expression Explanation

<%= aBool; %> We cannot use a semicolon in an expression

<%= int i = 20 %> We cannot define anything inside an expression

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:

Table 2. JSP Action Tags


JSP Action Description Attribute Description of Attributes

Used to forward a Specifies the URL of the


request to a target
page page target page
<jsp:forward>

Specifies the URL of the

resource to be included.

Specifies whether the

Includes a file in buffer should be flushed or

the current JSP page not. The flush value can be

page flush either true or false


<jsp:include>

<jsp:useBean> Invokes and id Uniquely identifies the instance

searches for class of the bean.

an existing scope Identifies the class from which

bean. beanName the bean objects are to be


implemented.

Defines the scope of the bean.

Defines the referential name for

the bean.

Defines the name for the

Retrieves the bean.

property of a Defines the property from

bean or create a name which the values are to


bean into a defined
scope property be retrieved.
<jsp:getProperty>

<jsp:setProperty> Used to set the name Specifies a name for the


property for a bean
property bean.

value Defines the property for

param which values are to be set.

Defines an explicit value

for the bean property.

Defines the name of the

request parameter to be
used.

Defines a

parameter to be Defines the name of the

passed to an reference parameter.

included or name Defines the value of the

forwarded page value specified parameter


<jsp:param>

Defines the type of plug-in to

be included.

Embed a Java type Defines the name of the class

applets or a code to be executed by the plug-in.

JavaBean codebase Defines the path of the code


<jsp:plugin>

The general syntax of a JSP action tag is:


<jsp:actionName attribute-list />
In this tag, actionName is one of the seven actions mentioned and attribute-list represents
one or more attribute-value pairs that are specific to the action.

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 --%>

JSP expression tag


The code placed within JSP expression tag is written to the output stream of the response.
So you need not write [Link]() to write data. It is mainly used to print the values of
variable or method.

Syntax of JSP expression tag

<%= statement %>

Example of JSP expression tag

In this example of jsp expression tag, we are simply displaying a welcome message.

<html>
<body>
<%= "welcome to jsp" %>
</body>
</html>

Example of JSP expression tag that prints current time

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>

Example of JSP expression tag that prints the user name

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>

JSP Scriptlet tag (Scripting elements)

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

.JSP Scripting elements.

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

JSP scriptlet tag

A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:

<% java source code %>

Example of JSP scriptlet tag

<html>
<body>
<% [Link]("welcome to jsp"); %>
</body>
</html>

Example of JSP scriptlet tag that prints the user name

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.

There are three types of directives:

o page directive
o include directive
o taglib directive

Syntax of JSP Directive

<%@ directive attribute="value" %>

JSP page directive

The page directive defines attributes that apply to an entire JSP page.

Syntax of JSP page directive

<%@ page attribute="value" %>

Attributes of JSP page directive


o import
o contentType
o extends
o info
o buffer
o language
o isELIgnored
o isThreadSafe
o autoFlush
o session
o pageEncoding
o errorPage
o isErrorPage

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.

Example of import attribute

<html>
<body>

<%@ page import="[Link]" %>


Today is: <%= new Date() %>

</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".

Example of contentType attribute

<html>
<body>

<%@ page contentType=application/msword %>


Today is: <%= new [Link]() %>

</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.

Example of info attribute

<html>
<body>

<%@ page info="composed by Sonoo Jaiswal" %>


Today is: <%= new [Link]() %>

</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.

Example of buffer attribute

<html>
<body>

<%@ page buffer="16kb" %>


Today is: <%= new [Link]() %>

</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:

<%@ page isThreadSafe="false" %>

The web container in such a case, will generate the servlet as:

public class SimplePage_jsp extends HttpJspBase


implements SingleThreadModel{
.......
}

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.

Example of errorPage attribute

//[Link]
<html>
<body>

<%@ page errorPage="[Link]" %>

<%= 100/0 %>

</body>
</html>

10)isErrorPage

The isErrorPage attribute is used to declare that the current page is the error page.

Example of isErrorPage attribute


//[Link]
<html>
<body>

<%@ page isErrorPage="true" %>

Sorry an exception occured!<br/>


The exception is: <%= exception %>

</body>
</html>

Simple JSP PROGRAM.

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

You might also like