0% found this document useful (0 votes)
160 views

Advanced Java Module-4 Notes

This document introduces Servlets and Java Server Pages, explaining their role in handling web server requests and generating responses. It details the servlet architecture, lifecycle, and advantages over CGI, highlighting the importance of the Servlet API and its components. The document also provides guidance on servlet development using Tomcat and Glassfish, including code examples and setup instructions.

Uploaded by

neerajgr2011
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
160 views

Advanced Java Module-4 Notes

This document introduces Servlets and Java Server Pages, explaining their role in handling web server requests and generating responses. It details the servlet architecture, lifecycle, and advantages over CGI, highlighting the importance of the Servlet API and its components. The document also provides guidance on servlet development using Tomcat and Glassfish, including code examples and setup instructions.

Uploaded by

neerajgr2011
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Module-4

Introducing Servlets and


Java Server Pages
By:-
Dr. Vani V
Assistant Professor
Dept. of ISE
BIT, Bangalore

Advanced Java (BIS402) 1

Introduction
• Servlets are the Java programs that run on the Java-enabled web server or application server.
They are used to handle the request obtained from the webserver, process the request,
produce the response, then send a response back to the webserver.
• Properties of Servlets are as follows:
1.Servlets work on the server-side.
2.Servlets are capable of handling complex requests obtained from the webserver.
• Servlet Architecture is can be depicted as follows:

Execution of Servlets basically involves six basic


steps:
1. The clients send the request to the webserver.
2. The web server receives the request.
3. The web server passes the request to the
corresponding servlet.
4. The servlet processes the request and generates
the response in the form of output.
5. The servlet sends the response back to the
webserver.
6. The web server sends the response back to the
client and the client browser displays it on the
screen.

Advanced Java (BIS402) Dr. Vani V 2


SwingGateway
Common Is Built on the AWT
Interface (CGI)
• The server-side extensions are nothing but the technologies that are used to create dynamic Web
pages. Actually, to provide the facility of dynamic Web pages, Web pages need a container or Web
server. To meet this requirement, independent Web server providers offer some proprietary
solutions in the form of APIs(Application Programming Interface).
• These APIs allow us to build programs that can run with a Web server. In this case, Java Servlet is
also one of the component APIs of Java Platform Enterprise Edition which sets standards for
creating dynamic Web applications in Java.
• The Servlet technology is similar to other Web server extensions such as Common Gateway
Interface(CGI) scripts and Hypertext Preprocessor (PHP). However, Java Servlets are more
acceptable since they solve the limitations of CGI such as low performance and low degree
scalability.

What is CGI?
• CGI is actually an external application that is written by using any of the programming languages
like C or C++ and this is responsible for processing client requests and generating dynamic content.
• In CGI application, when a client makes a request to access dynamic Web pages, the Web server
performs the following operations :
1. It first locates the requested web page i.e the required CGI application using URL.
2. It then creates a new process to service the client’s request.
3. Invokes the CGI application within the process and passes the request information to the
application.
4. Collects the response from the CGI application.
5.Destroys the process, prepares the HTTP response, and sends it to the client.
Advanced Java (BIS402) Dr. Vani V 3

So, in CGI server has to create and destroy the process for every request. It’s easy to
understand that this approach is applicable for handling few clients but as the number of clients
increases, the workload on the server increases and so the time is taken to process requests
increases.

Advanced Java (BIS402) Dr. Vani V 4


Swing Is Builtof
Advantages onServlets
the AWT
• Servlet is faster than CGI as it doesn’t involve the creation of a new process for every
new request received. Removes the overhead of creating a new process for each
request as Servlet doesn’t run in a separate process. There is only a single instance that
handles all requests concurrently. This also saves the memory and allows a Servlet to
easily manage the client state.
• Servlets, as written in Java, are platform-independent. The API designed for Java
Servlet automatically acquires the advantages of the Java platforms such as platform-
independent and portability. In addition, it obviously can use the wide range of APIs
created on Java platforms such as JDBC to access the database.
• It is a server-side component, so Servlet inherits the security provided by the Web
server.
• Many Web servers that are suitable for personal use or low-traffic websites are offered
for free or at extremely cheap costs eg. Java servlet. However, the majority of
commercial-grade Web servers are rather expensive, with the notable exception of
Apache, which is free.

Advanced Java (BIS402) Dr. Vani V 5

Swing Is Built
The Life Cycleon
ofthe AWT
a Servlet
`As displayed in the diagram, there are three states of a servlet: new, ready and end. The
servlet is in new state if servlet instance is created. After invoking the init() method,
Servlet comes in the ready state. In the ready state, servlet performs all the tasks. When
the web container invokes the destroy() method, it shifts to the end state.
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 javax.servlet.Servlet interface. Syntax of the init method
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 invoke : 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() Dr. Vani V 6
The Life Cycle of a Servlet
• Three methods are central to the life cycle of a servlet. These are init( ), service( ), and destroy( ). They are
implemented by every servlet and are invoked at specific times by the server. Let us consider a typical user
scenario to understand when these methods are called.
1. First, a user enters a Uniform Resource Locator (URL) to a web browser. The browser then generates an
HTTP request for this URL. This request is then sent to the appropriate server.
2. Second, this HTTP request is received by the web server. The server maps this request to a particular
servlet. The servlet is dynamically retrieved and loaded into the address space of the server.
3. Third, the server invokes the init( ) method of the servlet. This method is invoked only when the servlet is
first loaded into memory. It is possible to pass initialization parameters to the servlet so it may configure
itself.
4. Fourth, the server invokes the service( ) method of the servlet. This method is called to process the HTTP
request. You will see that it is possible for the servlet to read data that has been provided in the HTTP
request. It may also formulate an HTTP response for the client. The servlet remains in the server’s address
space and is available to process any other HTTP requests received from clients. The service( ) method is
called for each HTTP request.
5. Finally, the server may decide to unload the servlet from its memory. The server calls the destroy( )
method to relinquish any resources such as file handles that are allocated for the servlet. The memory
allocated for the servlet and its objects can then be garbage collected.

Dr. Vani V 7

Servlet Development Options


To create servlets, you will need access to a servlet container/server. Two popular ones are
Glassfish and Tomcat.
• Glassfish is from Oracle and is provided by the Java EE SDK. It is supported by NetBeans.
• Tomcat is an open-source product maintained by the Apache Software Foundation. It can
also be used by NetBeans.
Both Tomcat and Glassfish can also be used with other IDEs, such as Eclipse.
Tomcat is used because it is relatively easy to run the example servlets using only command-
line tools and a text editor. It is also widely available in various programming environments.
Furthermore, since only command-line tools are used, we don’t need to download and install an
IDE just to experiment with servlets.

Dr. Vani V 8
Using Tomcat
• Tomcat contains the class libraries, documentation, and run-time support that we will need to create
and test servlets. Several versions of Tomcat are available.
• The instructions that follow use 7.0.47.
• You can download Tomcat from tomcat.apache.org. You should choose a version appropriate to
your environment. Assuming that a 64-bit version of Tomcat 7.0.47 was unpacked from the root
directly, the default location is
C:\apache-tomcat-7.0.47-windows-x64\apache-tomcat-7.0.47\
• If you load Tomcat in a different location (or use a different version of Tomcat), you will need to make
appropriate changes to the examples. You may need to set the environmental variable JAVA_HOME
to the top- level directory in which the Java Development Kit is installed.
• Once installed, you start Tomcat by selecting startup.bat from the bin directly under the apache-
tomcat-7.0.47 directory. To stop Tomcat, execute shutdown.bat, also in the bin directory.
• The classes and interfaces needed to build servlets are contained in servlet-api.jar, which is in the
following directory:
C:\apache-tomcat-7.0.47-windows-x64\apache-tomcat-7.0.47\lib
• To make servlet-api.jar accessible, update your CLASSPATH environment variable so that it includes
C:\apache-tomcat-7.0.47-windows-x64\apache-tomcat-7.0.47\lib\servlet-api.jar
• Alternatively, you can specify this file when you compile the servlets. For example, the following
command compiles the first servlet example:
javac HelloServlet.java -classpath "C:\apache-tomcat-7.0.47-windows- x64\apache-tomcat-
7.0.47\lib\servlet-api.jar"

Dr. Vani V 9

• Once you have compiled a servlet, you must enable Tomcat to find it. For our purposes, this means
putting it into a directory under Tomcat’s webapps directory and entering its name into a web.xml
file. Here is the procedure that you will follow.
• First, copy the servlet’s class file into the following directory:
C:\apache-tomcat-7.0.47-windows-x64\apache-tomcat-7.0.47\webapps\examples\WEB-
INF\classes
• Next, add the servlet’s name and mapping to the web.xml file in the following directory:
C:\apache-tomcat-7.0.47-windows-x64\apache-tomcat-7.0.47\webapps\examples\WEB-INF
For instance, assuming the first example, called HelloServlet, you will add the following lines in the
section that defines the servlets:

Advanced Java (BIS402) Dr. Vani V 10


A Simple Servlet
The basic steps are the following:
1. Create and compile the servlet source code. Then, copy the servlet’s class file to the proper directory, and
add the servlet’s name and mappings to the proper web.xml file
2. Start Tomcat.
3. Start a web browser and request the servlet. Create and Compile the Servlet Source Code

1. To begin, create a file named HelloServlet.java that contains the following program:

import java.io.*;
import javax.servlet.*;
public class HelloServlet extends GenericServlet {
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>Hello!");
pw.close();
}
}

2. Start Tomcat : Tomcat must be running before you try to execute a servlet.
3. Start a Web Browser and Request the Servlet: Start a web browser and enter the URL shown here:
http://localhost:8080/examples/servlets/servlet/HelloServlet
Alternatively, you may enter the URL shown here:
http://127.0.0.1:8080/examples/servlets/servlet/HelloServlet

Advanced Java (BIS402) Dr. Vani V 11

The Servlet API


• javax.servlet and javax.servlet.http are the two packages that contain the classes and interfaces that are
required to build the servlets
• They constitute the core of the Servlet API but these packages are not part of the Java core packages.
Therefore, they are not included with Java SE. Instead, they are provided by Tomcat. They are also
provided by Java EE.
• The Servlet API has been in a process of ongoing development and enhancement. The current servlet
specification is version 3.1. However, because changes happen fast in the world of Java, you will want to
check for any additions or alterations.

Advanced Java (BIS402) Dr. Vani V 12


The javax.servlet Package
The javax.servlet package contains a number of interfaces and classes that establish the framework in which
servlets operate. The most significant of these is Servlet. All servlets must implement this interface or extend a
class that implements the interface. The ServletRequest and ServletResponse interfaces are also very
important.

Advanced Java (BIS402) Dr. Vani V 13

The Servlet Interface


• All servlets must implement the Servlet interface. The init( ), service( ), and destroy( ) methods are the
life cycle methods of the servlet. These are invoked by the server.
• The getServletConfig( ) method is called by the servlet to obtain initialization parameters. A servlet
developer overrides the getServletInfo( ) method to provide a string with useful information (for
example, the version number). This method is also invoked by the server.

The ServletConfig Interface


• The ServletConfig interface allows a servlet to obtain configuration data when it is loaded..

Dr. Vani V 14
The ServletContext Interface
• The ServletContext interface enables
servlets to obtain information about
their environment.

The ServletRequest Interface


• The ServletRequest interface enables a
servlet to obtain information about a
client request.

Advanced Java (BIS402) Dr. Vani V 15

The ServletResponse Interface


• The ServletResponse interface enables a
servlet to formulate a response for a client

The GenericServlet Class


• The GenericServlet class provides implementations of the basic life cycle methods for a servlet. GenericServlet
implements the Servlet and ServletConfig interfaces. In addition, a method to append a string to the server log file
is available.
void log(String s)
void log(String s, Throwable e)
• Here, s is the string to be appended to the log, and e is an exception that occurred.
The ServletInputStream Class
The ServletInputStream class extends InputStream. It is implemented by the servlet container and provides an input
stream that a servlet developer can use to read the data from a client request. In addition to the input methods
inherited from InputStream, a method is provided to read bytes from the stream. It is shown here:
int readLine(byte[ ] buffer, int offset, int size) throws IOException
Here, buffer is the array into which size bytes are placed starting at offset. The method returns the actual number of
bytes read or –1 if an end-of-stream condition is encountered.
The ServletOutputStream Class
The ServletOutputStream class extends OutputStream. It is implemented by the servlet container and provides an
output stream that a servlet developer can use to write data to a client response. In addition to the output methods
provided by OutputStream, it also defines the print( ) and println( ) methods, which output data to the stream.
The Servlet Exception Classes
javax.servlet defines two exceptions. The first is ServletException, which indicates that a servlet problem has
occurred. The second is UnavailableException, which extends ServletException. It indicates that a servlet is
unavailable. Dr. Vani V 16
Reading Servlet Parameters
• The ServletRequest interface includes methods that allow us to read the names and values of parameters that are
included in a client request.
• The servlet example contains two files. A web page is defined in PostParameters.html, and a servlet is defined in
PostParametersServlet.java. The HTML source code defines a table that contains two labels and two text fields. One of
the labels is Employee and the other is Phone. There is also a submit button. Notice that the action parameter of the
form tag specifies a URL. The URL identifies the servlet to process the HTTP POST request.
• The source code for PostParametersServlet.java has service( ) method that is overridden to process client requests.
The getParameterNames( ) method returns an enumeration of the parameter names. These are processed in a
loop.The parameter name and value are output to the client. The parameter value is obtained via the getParameter( )
method

Advanced Java (BIS402) Dr. Vani V 17

Compile the servlet. Next, copy it to the appropriate directory, and update the web.xml
File. Then, perform these steps to test this example:
1. Start Tomcat (if it is not already running).
2. Display the web page in a browser.
3. Enter an employee name and phone number in the text fields.
4. Submit the web page.
After following these steps, the browser will display a response that is dynamically
generated by the servlet.

Advanced Java (BIS402) Dr. Vani V 18


The javax.servlet.http Package

The HttpServletRequest Interface

Advanced Java (BIS402) Dr. Vani V 19

The HttpServletResponse
Interface

The HttpSession Interface

Advanced Java (BIS402) Dr. Vani V 20


The Cookie Class
The Cookie class encapsulates a cookie. A cookie is stored on a client and contains state information. Cookies
are valuable for tracking user activities. For example, assume that a user visits an online store. A cookie can
save the user’s name, address, and other information. The user does not need to enter this data each time he or
she visits the store.
A servlet can write a cookie to a user’s machine via the addCookie( ) method of the HttpServletResponse
interface. The data for that cookie is then included in the header of the HTTP response that is sent to the
browser. The names and values of cookies are stored on the user’s machine.
Some of the information that can be saved for each cookie includes the following:
• The name of the cookie
• The value of the cookie
• The expiration date of the cookie
• The domain and path of the cookie
• The expiration date determines when this cookie is
deleted from the user’s machine. If an expiration
date is not explicitly assigned to a cookie, it is
deleted when the current browser session ends.
• The domain and path of the cookie determine
when it is included in the header of an HTTP
request. If the user enters a URL whose domain
and path match these values, the cookie is then
supplied to the web server. Otherwise, it is not.
• There is one constructor for Cookie. It has the
signature shown here:
Cookie(String name, String value)
• Here, the name and value of the cookie are
supplied as arguments to the constructor. The
methods of the Cookie class

Dr. Vani V

The HttpServlet Class


• The HttpServlet class extends GenericServlet. It is commonly used when developing servlets that receive and
process HTTP requests.

Advanced Java (BIS402) Dr. Vani V 22


Handling HTTP Requests and Responses
• The HttpServlet class provides specialized methods that handle the various types of HTTP requests. A servlet
developer typically overrides one of these methods. These methods are doDelete( ), doGet( ), doHead( ),
doOptions( ), doPost( ), doPut( ), and doTrace( ). The GET and POST requests are commonly used when
handling form input.

Handling HTTP GET Requests


• The servlet is invoked when a form on a web page is submitted. The example contains two files. A web page is
defined in ColorGet.html, and a servlet is defined in ColorGetServlet.java.

Advanced Java (BIS402) Dr. Vani V 23

Handling HTTP POST Requests


Here we will develop a servlet that handles an HTTP POST request. The servlet is invoked when a form on a web
page is submitted. The example contains two files. A web page is defined in ColorPost.html, and a servlet is
defined in ColorPostServlet.java.
It is identical to ColorGet.html except that the method parameter for the form tag explicitly specifies that the
POST method should be used, and the action parameter for the form tag specifies a different servlet.

Advanced Java (BIS402) Dr. Vani V 24


Using Cookies

Advanced Java (BIS402) Dr. Vani V 25

Session Tracking
• HTTP is a stateless protocol. Each request is
independent of the previous one. However, in some
applications, it is necessary to save state information
so that information can be collected from several
interactions between a browser and a server. Sessions
provide such a mechanism.
• A session can be created via the getSession( ) method
of HttpServletRequest. An HttpSession object is
returned. This object can store a set of bindings that
associate names with objects.
• The setAttribute( ), getAttribute( ), getAttributeNames(
), and removeAttribute( ) methods of HttpSession
manage these bindings. Session state is shared by all
servlets that are associated with a client.
• The following servlet illustrates how to use session
state. The getSession( ) method gets the current
session. A new session is created if one does not
already exist. The getAttribute( ) method is called to
obtain the object that is bound to the name "date".
That object is a Date object that encapsulates the date
and time when this page was last accessed. A Date
object encapsulating the current date and time is then
created.
• The setAttribute( ) method is called to bind the name
"date" to this object
Advanced Java (BIS402) Dr. Vani V 26
26
Java Server Pages (JSP)

• A JSP (Java Server Page) is a server-side technology which is used for creating web
applications. It is used to create dynamic web content. JSP consists of both HTML tags
and JSP tags. In this, JSP tags are used to insert JAVA code into HTML pages. It is an
advanced version of Servlet Technology i.e. a web-based technology that helps us to
create dynamic and platform-independent web pages.
• Java code can be inserted in HTML/ XML pages or both. JSP is first converted into a
servlet by the JSP container before processing the client’s request.
• A JSP is called by a client to provide web services, the nature of which depends on client
• application.
• There are three methods that are automatically called when JSP is requested and when
JSP terminates normally. These are the JSPInit() method , the JSPDestroy() method
and service() method.
• A JSPInit() is identical to init() method of java servlet. It is called when first time JSP is
called.
• A JSPDestroy() is identical to destroy() method of servlet. The destroy() method is
automatically called when JSP terminates normally. It is not called when JSP terminates
abruptly. It is used for placing clean up codes.
• The sevice() method is automatically called and retrieves a connection to HTTP.

Advanced Java (BIS402) Dr. Vani V 27

Features of Java Server Pages (JSP)


•Coding in JSP is easy : As it is just adding JAVA code to HTML/XML.
•Reduction in the length of Code : In JSP we use action tags, custom tags etc.
•Connection to Database is easier : It is easier to connect website to database and allows
to read or write data easily to the database.
•Make Interactive websites : In this we can create dynamic web pages which helps user to
interact in real time environment.
•Portable, Powerful, flexible and easy to maintain : as these are browser and server
independent.
•No Redeployment and No Re-Compilation : It is dynamic, secure and platform
independent so no need to re-compilation.
•Extension to Servlet : as it has all features of servlets, implicit objects and custom tags
• Declaration Tag : It is used to declare variables.
• Java Scriplets : It allows us to add any number of JAVA code, variables and
expressions.
• Expression Tag : It evaluates and convert the expression to a string.
• JAVA Comments : It contains the text that is added for information which has to
be ignored.
• It does not require advanced knowledge of JAVA
• It is capable of handling exceptions
• Easy to use and learn
• It contains tags which are easy to use and understand
• Implicit objects are there which reduces the length of code

Advanced Java (BIS402) Dr. Vani V 28


Advanced Java (BIS402) Dr. Vani V 29

JSP Tags
• A JSP tag consists of a combination of HTML tags and JSP tags. JSP tags define java code that is to be
executed before the output of JSP program is sent to the browser.
• A JSP tag begin with a <%, which is followed by java code , and ends with %>,
• There is an XML version of JSP tag <jsp:TagID> </jsp:TagID>
• A JSP tags are embedded into the HTML component of a JSP program and are processed by JSP virtual
engine such as Tomcat.
• Java code associated with JSP tag are executed and sent to browser by tomcat.

There are five types of JSP tags :


1. Comment tag :A comment tag opens with <%-- and close with --%> and is followed by a comment that
usually describes the functionality of statements that follow a comment tag.
2. Declaration statement tags: A declaration statement tag opens with <%! and is followed by declaration
statements that define the variables, object, and methods that are available to other component of JSP
program
3. Directive tags: A directive tag opens with <%@ and commands the jsp virtual engine to perform a
specific task, such as importing java package required by objects and methods used in a declaration
statement. The directive tag closes with %> . There are commonly used in directives import, include , and
taglib. The import tag is used to import java packages into the jsp program. Include tag inserts a specified
file into the JSP program replacing the include tag. Taglib is specifies a file that contains tag library.
Example:
<%@ page import=”import java.sql.*” ; %>
<%@ include file=”keogh\books.html” %>
<%@ taglib url=”myTags.tld” ; %>
4. Expression tags: An expression tag opens with <%= and is used for an expression statement whose
result replaces the expression tag when the jsp virtual engine resolves JSP tags. An expression tag
closes with %>
5. Scriptlet tag: A sciptlet tag opens with <% and contains commonly used java control statements and
loops. A Scriptlet tag closes with %> Dr. Vani V 30
Variables and Objects
WE can declare java variables and objects that are used in a JSP program by using the same
coding technique used to declare them in java. JSP declaration statements must appear as JSP
tag.
Example:
<html>
<head>
<title> JSP Programming </title>
<\head>
<body>
<%! int age=29; %><p> Your age is : <%=age%> </p>
</body>
</html>
<html>
<html> <head>
<head> <title> JSP Programming </title>
<title> JSP Programming </title> <\head>
<\head> <body>
<body> <%! String name;
<%! int age=29; String[] Telephone={“99778437434”,”987343434”};
float salary; String Company=new String();
int empNumber; %> int[] Grade={100,67,42}; %>
</body> </body>
</html> </html>
Advanced Java (BIS402) Dr. Vani V 31

Methods
Methods are defined same way as it is defined in java program, except these are placed in JSP
tag. Methods are declared in JSP declaration tag. The JSP calls method inside the expression
tag.
Example:
<html> <html>
<head> <head>
<title> JSP Programming </title> <title> JSP Programming </title>
<\head> <\head>
<body> <body>
<%! int add(int n1, int n2) <%! boolean curve(int grade)
{ {
int c; return 10+grade;
c=a+b; }
return c; boolean curve(int grade, int curveValue)
} {
%> return curveValue+grade;
<p> Addition of two numbers : <%= add(45,46)%> </p> }
</body>
</html> %>
</body>
</html>

Advanced Java (BIS402) Dr. Vani V 32


Control Statements
One of the most powerful features avilable in JSP is the ability to change the flow of the
program to truly create dynamic content for a web based on conditions received from the
browser.
There are two control statements used to change the flow of program are “if and “switch”
statement , both of which are also used to direct the flow of a java program.
Example: <%! int day = 3; %>
<html>
<html> <body>
<head> <%
<title> JSP Programming </title> switch(day) {
case 0:
<\head> out.println("It\'s Sunday.");
<body> break;
case 1:
<%! int age=29; %> out.println("It\'s Monday.");
<% if(grade >69) { %> break;
case 2:
<p> You Passed !</p> out.println("It\'s Tuesday.");
<% } else { %> break;
case 3:
<p> Better Luck Next Time</p> out.println("It\'s Wednesday.");
<% } %> break;
case 4:
</body> out.println("It\'s Thursday.");
</html> break;
case 5:
out.println("It\'s Friday.");
break;
default:
out.println("It's Saturday.");
}
%>
Dr. Vani V </body>
Advanced Java (BIS402) 33
</html>

Loops
• JSP loops are nearly identical to loops that we use in our java program except that we can
repeat the html tags and related information multiple times within the JSP program.
• There are three kind of JSP loop that are commonly used in JSP program. Ex: for loop ,
while loop , do while .
• Loop plays an important role in JSP database program because loops are used to populate
HTML tables with data in the result set.
Example:
<%! int[] grade = {100, 82, 93}; <%! int[] grade = {100, 82, 93};
<html> <%! int[] grade = {100, 82, 93};
int x=0;%> int x=0;%>
<head> int x=0;%>
<table> <table>
<title> For Loop Example</title> <table>
<tr> <tr>
<tr>
<\head> <td> First </td> <td> First </td>
<td> First </td>
<body> <td> Second </td> <td> Second </td>
<td> Second </td>
<td> Third </td> <td> Third </td>
<% <td> Third </td>
</tr> </tr>
for (int i = 0; i < 10;i++) { </tr>
<tr> <tr>
%> <tr>
<% while(x<3 { %> <% x=0;
<% for(int I;i<3;i++) { %>
<p> Hello World</p> <td> <%= grade[x] %> </td> do { %>
<td> <%= grade[i] %> </td>
<% } %> <% x++; <td> <%= grade[x] %> </td>
<% } %
</body> }% <% x++;
</tr>
</tr> } while(x<3) %
</html> </table>
</table> </tr>
</table>

Advanced Java (BIS402) Dr. Vani V 34


Tomcat
• JSP programs are executed by a JSP Virtual Machine that runs on a web server.
Alternatively we can use an integrated development environment such as Jbuilder that has a
built-in JSP Virtual Machine.
• One of the most popular virtual machine is Tomcat, and it is downloadable at no charge from
Apache website.
• Installation Steps:
1. Connect to Jakarta.apache.org.
2. Select download
3. Select Binaries to display the binary Download Page.
4. Create a folder from the root directory called tomcat.
5. Download latest release of Jakarta-tomcat.zip to the tomcat folder.
6. Unzip Jakarta-tomcat.zip.
7. The extraction process creates the following folder in the tomcat directory: bin, conf,
doc, lib, src, and webapps.
8. Use text editor such as notepad and edit JAVA_HOME variable in the tomcat.bat file,
which is located in the \tomcat\bin folder. Make sure the JAVA_HOME variable is
assigned the path where JDK is installed on your computer.
9. Open DOS window and type \tomcat\bin\tomcat to start Tomcat.
10. Open your browser. Enter http://localhost:8080. The Tomcat home page is displayed
on the screen verifying that Tomcat is running

Advanced Java (BIS402) Dr. Vani V 35

Request String

• A browser generate requst string whenever the submit button is selected. The user requests
the string consists of URL and the query the string.
• Example of request string:
http://www.jimkeogh.com/jsp/myprogram.jsp?fname=“Bob”&lname=“Smith”
• Your jsp program needs to parse the query string to extract the values of fields that are to be
processed by your program. You can parse the query string by using the methods of the
request object.
• getParameter(Name) method is used to parse a value of a specific field and it requires an
argument which is the name of the field whose value we want to retrieve.
<%! String FirstName =requst.getParameter(fname);
String LastName =requst.getParameter(lname); %>
• Copying from multivalued field such as selection list field can be tricky. The multivalued
fields are handled by using getParameterValues()
• Other than request string URL has protocols, port no, the host name etc.

Advanced Java (BIS402) Dr. Vani V 36


Passing other Information

• Example of request string:


http://www.jimkeogh.com/jsp/myprogram.jsp?fname=“Bob”&lname=“Smith”

• The request string sent to the JSP by the browser is divided into two general
components that are separated by question mark. The URL component appears to the
left of the question mark and the query string is to the right of the question mark.
The URL is divided into four parts: protocol, host, port and virtual path.
• The protocol defines the rules that are used to transfer the request string from the
browser to the JSP program. Three commonly used protocols are HTTP, HTTPS and
FTP.
• Next is the host and port combination. The host is Internet Protocol (IP) address or the
name of the server that contains JSP program. Port number is the port that the host
monitors. Usually port is excluded form request string whenever HTTP is used because
the assumption is the host is monitoring port 80.
• Following the host and port is the virtual path of the JSP program. The server maps the
virtual path to the physical path.
• In the above request string, the protocol is HTTP, the host is www.jimkeogh.com. There
is no port number and the virtual path is /jsp/myprogram.jsp

Advanced Java (BIS402) Dr. Vani V 37

User Sessions: Cookies


• A JSP program must be able to track a session as a client moves between HTML pages and JSP
program. Three commonly used methods to track a session are by using a hidden field, using a
cookie or by using JavaBean.
• A hidden field is a field in an HTML form whose value isn’t displayed on the HTML page. We can
assign a value to a hidden field in a JSP program before the program sends the dynamic HTML
page to the browser.
Cookie is small piece of information created b a JSP program that is stored on the client's hard disk by
the browser. Cookie is used to store various kind of information, such as user preference. The cookies
are created by using Cookie class. Reading Cookie
<html>
<head>
Create Cookie <title>reading cookie </title>
<html> </head>
<head> <body>
<title> Creating Cookie</title> </head> <% String myCookieName=”EMPID”;
<body> String myCookieValue;
String CName, CValue;
<%! String MyCookieName=” EMPID”;
int found=0;
String UserValue=”AN2536”; Cookie[] cookies=request.getCoookies();
%> for( int i=0;i<cookies.length;i++) {
</body> CName= cookies[i].getName();
</html> CValue =cookies[i].getValue();
If(myCookieName.equals(CName)) {
found=1;
myCookieValue=Cvalue; } }
If(found== 1) { %>
<p> Cookie Name = < %= CName %> </p>
<p> Cookie Value = < %= CValue %> </p>
<% } %> </body></html>
Advanced Java (BIS402) Dr. Vani V 38
Session Object
A JSP database system is able to share information among JSP programs within a session by using a
session object. Each time a session is created , a unique ID is assigned to the session and stored as a
cookie.
A unique ID enables JSP program to track multiple session simultaneously while maintaining data integrity of
each session. The session ID is used to prevent the intermingling of each session.
In addition to the session ID, a session object is also used to store other types of information, called
attributes. An attribute can be login information, preferences, or even purchases placed in an electronic
shopping cart.
Let's say that you built a Java database system that enables customers to purchase goods online. A JSP
program dynamically generates catalogue pages of available merchandise. A new catalogue page is
generated each time the JSP program executes.
The customer selects merchandise from a catalogue page, then jumps to another catalogue page where
additional merchandise is available for purchase. Your JSP database system must be able to temporarily
store purchases made from each catalogue page ; otherwise, the system is unable to execute the checkout
process. This means that purchases must be accessible each time the JSP program executes.
There are several ways in which you can share purchases . You might store merchandise temporally in a
table, but then you 'll need to access the DBMS several times during the session, which might cause
performance degradation .
A better approach is to use a session object and store information about purchases as session attributes.
Session attributes can be retrieved and modified each time the JSP program runs.

Dr. Vani V 39

Create session Object:


<html> <head><title> Jsp Session</title></head>
<body>
<% ! String AtName=“Product”;
String AtValue =“1234”;
Session.setAttributes(AtName, AtValue);
%></body>
</html>
In session object we can store information about purchases as session attributes can be
retrived and modified each time the jsp program runs. setAttributes() used for creating
attributes.

Read Session Object:


getAttributeNames() methos returns names of all the attributes as Enumeration , the
attributes are processed.
<html> <head><title> Jsp Session</title></head>
<body><% ! Enumaration purchases=session.getAttributeNames();
while(purchases.hasMoreElements() {
String AtName=(String) attributeNames.nextElement();
String AtValue=(String) session.getAttribute(AtName); %>
<p> Attirbute Name <%= AtName %> </p>
<p> Attribute Value <% = Atvalue %> </p>
<% } %>
</body></html>

Advanced Java (BIS402) Dr. Vani V 40


index.jsp
process.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"


<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<!DOCTYPE html>
<html>
<html>
<head>
<head>
<meta charset="UTF-8">
<meta charset="UTF-8">
<title>Student Details</title>
<title>Student Details</title>
</head>
</head>
<body>
<body>
<h2>Enter Student Details</h2>
<h2>Student Details</h2>
<form method="post" action="process.jsp">
<%-- Retrieve parameters from the form --%>
<label for="name">Name:</label>
<% String name = request.getParameter("name");
<input type="text" id="name" name="name" ><br><br>
String usn = request.getParameter("usn");
int subject1 = Integer.parseInt(request.getParameter("subject1"));
<label for="usn">USN:</label>
int subject2 = Integer.parseInt(request.getParameter("subject2"));
<input type="text" id="usn" name="usn" ><br><br>
int subject3 = Integer.parseInt(request.getParameter("subject3"));

<label for="subject1">Subject 1 Marks:</label>


// Calculate total marks
<input type="number" id="subject1" name="subject1" ><br><br>
int totalMarks = subject1 + subject2 + subject3;
%>
<label for="subject2">Subject 2 Marks:</label>
<input type="number" id="subject2" name="subject2" ><br><br>
<p><strong>Name:</strong> <%= name %></p>
<p><strong>USN:</strong> <%= usn %></p>
<label for="subject3">Subject 3 Marks:</label>
<p><strong>Total Marks:</strong> <%= totalMarks %></p>
<input type="number" id="subject3" name="subject3" ><br><br>
<p><a href="index.jsp">Back to Input Page</a></p>
<input type="submit" value="Submit">
</body>
</form>
</html>
</body>
</html>

Dr. Vani V 41

You might also like