MSP02
MSP02
MSP02
Page Nos.
Introduction
Objectives
How to install Servlet Engine/Web Server
Your First Servlet
Servlet Life Cycle
Http Servlet Request Interface
Http Servlet Response Interface
Session Tracking
Database Connectivity with Servlets
Inter-Servlet Communication
Summary
Solutions/Answers
Further Readings/References
5
5
6
7
9
12
13
14
19
21
25
26
32
1.0 INTRODUCTION
We have already learnt about core Java and how to compile and learn the Java
programs. In this unit we shall cover the basics of Java Servlet and different interfaces
of Servlet. Java Servlets are the small, platform-independent Java programs that runs
in a web server or application server and provides server-side processing such as
accessing a database and e-commerce transactions. Servlets are widely used for web
processing. Servlets are designed to handle HTTP requests (get, post, etc.) and are the
standard Java replacement for a variety of other methods, including CGI scripts,
Active Server Pages (ASPs). Servlets always run inside a Servlet Container. A Servlet
Container is nothing but a web Server, which handles user requests and generates
response. Servlet Container is different from Web Server because it is only meant for
Servlet and not for other files (like .html etc). In this unit, we shall also see how the
Servlet Container is responsible for maintaining lifecycle of the Servlet. Servlets
classes should always implement the javax.servlet.Servlet interface. This interface
contains five methods, which must be implemented. We shall learn how these
methods can be used in Servlet programming and how Servlet and JDBC combination
has proved a simple elegant way to connect to database.
1.1 OBJECTIVES
After going through this unit, you should be able to know:
Servlets and
JSP Programming
Servlet Programming
Servlets are basically developed for server side applications and designed to handle
http requests. The servlet-programming interface (Java Servlet API)
is a standard part of the J2EE platform and has the following advantages over other
common server extension mechanisms:
They are faster than other server extensions, like, CGI scripts because they use a
different process model.
Since Servlets are written in Java, Servlets are portable between servers and
operating systems. They have all of the advantages of the Java language,
including ease of development.
They can access the large set of APIs available for the Java platform.
Now, after installing the Tomcat Server, let us create our first Java Servlet. Create a
new text file and save it as HelloWorld.java in the
'C:\jakarta-tomcat-4.0-b5\webapps\saurabh\WEBINF\classes\com\stardeveloper\servlets folder. C:\jakarta-tomcat-4.0-b5\webapps\ is
the folder where web applications that we create should be kept in order for Tomcat to
find them. '\saurabh' is the name of our sample web application and we have created it
earlier in Installing Tomcat. '\WEB-INF\classes' is the folder to keep Servlet classes.
'\com\stardeveloper\servlets' is the package path to the Servlet class that we will
create. Now type the following text into the 'HelloWorld.java' file we created earlier:
// Your First Servlet program
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>Hello, Welcome to the World of Servlet
Programming</TITLE></HEAD>");
out.println("<BODY>");
out.println("<BIG>Hello World</BIG>");
out.println("</BODY></HTML>");
}
}
Servlets and
JSP Programming
Our HelloWorld program is extremely simple and displays Hello World in the
Browser. We override method doGet() of HttpServlet class.In the doGet() method we
set the content type to text/html ( telling the client browser that it is an HTML
document ). Then get hold of PrintWriter object and using it print our own HTML
content to the client. Once done we close() it.
Compiling and Running the Servlet
Now, we will compile this Servlet using the following command at the DOS prompt:
C:\jakarta-tomcat-4.0-b5\webapps\star\WEBINF\classes\com\stardeveloper\servlets>javac HelloWorld.java
If all goes well a 'HelloWorld.class' file will be created in that folder. Now, open your
browser and point to the following address:
http://localhost:8080/star/servlet/com.stardeveloper.servlets.HelloWorld
You should see response from the Servlet showing Helloworld
I have assumed here that you are running Tomcat at port 8080 ( which is the default
for Tomcat).
Just like an applet, a servlet does not have a main() method. Instead, certain methods
of a servlet are invoked by the server in the process of handling requests. Each time
the server dispatches a request to a servlet, it invokes the servlets service() method.
A generic servlet should override its service() method to handle requests as
appropriate for the servlet. The service() method accepts two parameters: a request
object and a response object. The request object tells the servlet about the request,
while the response object is used to return a response. Figure 1 shows how a generic
servlet handles requests.
In contrast, an HTTP servlet usually does not override the service() method. Instead, it
overrides doGet() to handle GET requests and doPost() to handle POST requests. An
HTTP servlet can override either or both of these methods, depending on the type of
requests it needs to handle. The service() method of HttpServlet handles the setup and
dispatching to all the doXXX() methods, which is why it usually should not be
overridden. Figure 2 shows how an HTTP servlet handles GET and POST requests.
Servlet Programming
An HTTP servlet can override the doPut() and doDelete() methods to handle PUT and
DELETE requests, respectively. However, HTTP servlets generally dont touch
doHead(), doTrace(), or doOptions(). For these, the default implementations are
almost always sufficient.
Destruction
Destroy () method
Servlet Class
Garbage Collection
The Server no longer has a
reference to the object
Figure 3: The Servlet Life Cycle
Servlets and
JSP Programming
There are three principal stages in the life of a Java servlet, namely:
1)
So you have created your Servlet class in above-mentioned example, by extending the
HttpServlet class and have placed it in /WEB-INF/classes/ directory of your
application. Now, when will Servlet Container create an instance of your Servlet?
There are a few situations:
When you have specifically told the Servlet Container to preload your Servlet
when the Servlet Container starts by setting the load-on-startup tag to a nonzero value e.g.
<web-app>
<servlet>
<servlet-name>test</servlet-name>
<servlet-class>com.stardeveloper.servlets.TestServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
</web-app>
So, when the Servlet Container starts it will preload your Servlet in the memory.
If your Servlet is not already loaded, its instance will be created as soon as a
request is received for it by the Servlet Container.
During the loading of the Servlet into the memory, Servlet Container will call
your Servlet's init() method.
2)
Servlet Execution: Once your Servlet is initialised and its init() method called,
any request that the Servlet Container receives will be forwarded to your
Servlets service() method. HttpServlet class breakes this service() method into
more useful doGet(), doPost(), doDelete(), doOptions(), doPut() and doTrace()
methods depending on the type of HTTP request it receives. So in order to
generate response you should override the doGet() or doPost() method as per
your requirement.
At this moment all the requests will be forwarded to the appropriate doGet() or
doPost() or whatever method as required. No new instance will be created for
your Servlet.
When a Servlet request is made to the Servlet engine, the Servlet engine
receives all the request parameters (such as the IP address of client), user
information and user data and constructs a Servlet request object, which
encapsulates all this information.
Another object, a Servlet response object is also created that contains all the
information the Servlet needs to return output to the requesting client.
3)
10
Point to remember: init() and destroy() methods will be called only once during
the life time of the Servlet while service() and its broken down methods (doGet(),
doPost() etc ) will be called as many times as requests are received for them by the
Servlet Container.
Servlet Programming
Let us understand all the phases of Servlet Life Cycle with the help of an example:
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.*;
import javax.servlet.http.*;
public class TestServlet extends HttpServlet {
private String name = "saurabh Shukla";
public void init() throws ServletException
{
System.out.println("Calling the method TestServlet : init");
}
public void destroy()
{
System.out.println("Calling the method TestServlet : destroy");
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
// print content
out.println("<html><head>");
out.println("<title>TestServlet ( by ");
out.println( name );
out.println(" )</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>TestServlet ( by ");
out.println( name );
out.println(" ) :</p>");
out.println("</body></html>");
out.close();
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
doGet(req, res);
}
}
Our TestServlet is extremely simple to demonstrate the life cycle of a Servlet, which
is displaying the name of the author to the user. We override four methods of
HttpServlet class. init() is called by the Servlet Container only once during the
initialization of the Servlet. Similarly destroy() is called once when removing the
Servlet instance. We can thus put initialisation code in init() method. doGet() is called
when a GET client request is received and doPost() is called when POST client
request is received. In the doGet() method we set the content type to text/html
(telling the client browser that it is an HTML document). Then get hold of PrintWriter
object and using it print our own HTML content to the client. Once done we close() it.
Now, we will compile this Servlet in the same manner as we have compiled earlier:
C:\jakarta-tomcat-4.0-b5\webapps\star\WEB-INF\classes\
com\stardeveloper\servlets>javac TestServlet.java
11
Servlets and
JSP Programming
If all goes well a 'TestServlet.class' file will be created in that folder. Now, open your
browser and point to the following address:
http://localhost:8080/star/servlet/com.stardeveloper.servlets.TestServlet
You should see response from the Servlet showing TestServlet.
c) init() and destroy() methods will be called only once during the life time of
the Servlet.
T
F
2)
What are the advantages of servlets over other common server extension
mechanisms?
....
3)
4)
5)
a) getCookies
Servlet Programming
Servlets and
JSP Programming
a) addCookie
public void addCookie(Cookie cookie);
It is used to add the specified cookie to the header of response. This method can be
called multiple times to set more than one cookie. This method must be called before
the response is committed so that the appropriate headers can be set. The cookies
maximum age and whether the client allows Cookies to be saved determine whether
or not Cookies will be stored on the client.
b) sendError
public void sendError(int statusCode) throws IOException;
public void sendError(int statusCode, String message) throws IOException;
It sends an error response to the client using the specified status code. If a message is
provided to this method, it is emitted as the response body, otherwise the server
should return a standard message body for the error code given. This is a convenience
method that immediately commits the response. No further output should be made by
the servlet after calling this method.
c) getWriter
public Printwriter getWriter()
It obtains a character-based output stream that enables text data to be sent to the client.
d) getOutputStream()
public ServletOutputStream getOutputStream()
It obtains a byte-based output stream that enables binary data to sent to the client.
e) sendRedirect
public void sendRedirect(String location) throws IOException;
It sends a temporary redirect response to the client (SC_MOVED_TEMPORARILY)
using the specified location. The given location must be an absolute URL. Relative
URLs are not permitted and throw an IllegalArgumentException.
This method must be called before the response is committed. This is a convenience
method that immediately commits the response. No further output is be made by the
servlet after calling this method.
shopping cart application is another classic examplea client can put items in his
virtual cart, accumulating them until he checks out several page requests later.
Servlet Programming
Obviously the server must distinguish between clients so the company can determine
the proper items and charge the proper amount for each client.
Another purpose of customizing on a client-by-client basis is marketing. Companies
often track the pages you visit throughout a site so they display advertisements that
are targeted to users browsing needs.
To help the server distinguish between clients, each client must identify itself to the
server. There are a number of popular techniques for distinguishing between clients.
In this unit, we introduce one of the techniques called as Session Tracking.
Session tracking is wonderfully elegant. Every user of a site is associated with a
javax.servlet.http.HttpSession object that servlets can use to store or retrieve
information about that user. You can save any set of arbitrary Java objects in a session
object. For example, a users session object provides a convenient location for a
servlet to store the users shopping cart contents.
A servlet uses its request objects getSession() method to retrieve the current
HttpSession object:
public HttpSession HttpServletRequest.getSession(boolean create)
This method returns the current session associated with the user making the request. If
the user has no current valid session, this method creates one if create is true or returns
null if create is false. To ensure the session is properly maintained, this method must
be called at least once before any output is written to the response.
You can add data to an HttpSession object with the putValue() method:
public void HttpSession.putValue(String name, Object value)
This method binds the specified object value under the specified name. Any existing
binding with the same name is replaced. To retrieve an object from a session, use
getValue():
public Object HttpSession.getValue(String name)
This methods returns the object bound under the specified name or null if there is no
binding. You can also get the names of all of the objects bound to a session with
getValueNames():
public String[] HttpSession.getValueNames()
This method returns an array that contains the names of all objects bound to this
session or an empty (zero length) array if there are no bindings. Finally, you can
remove an object from a session with removeValue():
public void HttpSession.removeValue(String name)
This method removes the object bound to the specified name or does nothing if there
is no binding. Each of these methods can throw a java.lang.IllegalStateException if
the session being accessed is invalid.
A Hit Count Using Session Tracking
Let us understand session tracking with a simple servlet to count the number of times
a client has accessed it, as shown in example below. The servlet also displays all the
bindings for the current session, just because it can.
15
Servlets and
JSP Programming
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SessionTracker extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
// Get the current session object, create one if necessary
HttpSession session = req.getSession(true);
// Increment the hit count for this page. The value is saved
// in this client's session under the name "tracker.count".
Integer count = (Integer)session.getValue("tracker.count");
if (count == null)
count = new Integer(1);
else
count = new Integer(count.intValue() + 1);
session.putValue("tracker.count", count);
out.println("<HTML><HEAD><TITLE>SessionTracker</TITLE></HEAD>");
out.println("<BODY><H1>Session Tracking Demo</H1>");
// Display the hit count for this page
out.println("You've visited this page " + count +((count.intValue() == 1) ? " time." : "
times."));
out.println("<P>");
out.println("<H2>Here is your session data:</H2>");
String[] names = session.getValueNames();
for (int i = 0; i < names.length; i++) {
out.println(names[i] + ": " + session.getValue(names[i]) + "<BR>");
}
out.println("</BODY></HTML>");
}}
The output will appear as:
Session Tracking Demo
Youve visited this page 12 times
Here is your session Data
movie.level : beginner
movie.zip : 50677
tracker.count : 12
This servlet first gets the HttpSession object associated with the current client. By
passing true to getSession(), it asks for a session to be created if necessary. The servlet
then gets the Integer object bound to the name tracker.count. If there is no such
object, the servlet starts a new count. Otherwise, it replaces the Integer with a new
Integer whose value has been incremented by one. Finally, the servlet displays the
current count and all the current name/value pairs in the session.
Session Tracking using persistent Cookies
Another technique to perform session tracking involves persistent cookies. A cookie
is a bit of information sent by a web server to a browser is stored it on a client
machine that can later be read back from that browser. Persistent cookies offer an
elegant, efficient, easy way to implement session tracking. Cookies provide as
automatic introduction for each request as you could hope for. For each request, a
cookie can automatically provide a clients session ID or perhaps a list of the clients
preferences. In addition, the ability to customize cookies gives them extra power and
16
versatility. When a browser receives a cookie, it saves the cookie and thereafter sends
the cookie back to the server each time it accesses a page on that server, subject to
certain rules. Because a cookies value can uniquely identify a client, cookies are
often used for session tracking.
Servlet Programming
Note: Cookies were first introduced in Netscape Navigator. Although they were not
part of the official HTTP specification, cookies quickly became a de facto
standard supported in all the popular browsers including Netscape 0.94 Beta
and up and Microsoft Internet Explorer 2 and up.
Problem: The biggest problem with cookies is that all the browsers dont always
accept cookies. Sometimes this is because the browser doesnt support cookies.
Version 2.0 of the Servlet API provides the javax.servlet.http.Cookie class for
working with cookies. The HTTP header details for the cookies are handled by the
Servlet API. You create a cookie with the Cookie() constructor:
public Cookie(String name, String value)
This creates a new cookie with an initial name and value..
A servlet can send a cookie to the client by passing a Cookie object to the
addCookie() method of HttpServletResponse:
public void HttpServletResponse.addCookie(Cookie cookie)
This method adds the specified cookie to the response. Additional cookies can be
added with subsequent calls to addCookie(). Because cookies are sent using HTTP
headers, they should be added to the response before you send any content. Browsers
are only required to accept 20 cookies per site, 300 total per user, and they can limit
each cookies size to 4096 bytes.
The code to set a cookie looks like this:
Cookie cookie = new Cookie(ID, 123);
res.addCookie(cookie);
A servlet retrieves cookies by calling the getCookies() method of HttpServletRequest:
public Cookie[] HttpServletRequest.getCookies()
This method returns an array of Cookie objects that contains all the cookies sent by
the browser as part of the request or null if no cookies were sent. The code to fetch
cookies looks like this:
Cookie[] cookies = req.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
String name = cookies[i].getName();
String value = cookies[i].getValue();
}
}
You can set a number of attributes for a cookie in addition to its name and value. The
following methods are used to set these attributes. As you will see, there is a
corresponding get method for each set method. The get methods are rarely used,
however, because when a cookie is sent to the server, it contains only its name, value,
and version.
Here some of the methods of cookies are listed below which are used for session
tracking:
public void Cookie.setMaxAge(int expiry)
Specifies the maximum age of the cookie in seconds before it expires. A negative
value indicates the default, that the cookie should expire when the browser exits. A
zero value tells the browser to delete the cookie immediately.
17
Servlets and
JSP Programming
18
Servlet Programming
This servlet first tries to fetch the clients session ID by iterating through the cookies it
received as part of the request. If no cookie contains a session ID, the servlet generates
a new one using generateSessionId() and adds a cookie containing the new session ID
to the response.
Servlets and
JSP Programming
The advantage of servlets over CGI and many other technologies is that JDBC is
database-independent. A servlet written to access a Sybase database can, with a twoline modification or a change in a properties file, begin accessing an Oracle database.
One common place for servlets, especially servlets that access a database, is in whats
called the middle tier. A middle tier is something that helps connect one endpoint to
another (a servlet or applet to a database, for example) and along the way adds a little
something of its own. The middle tier is used between a client and our ultimate data
source (commonly referred to as middleware) to include the business logic.
Let us understand the database connectivity of servlet with table with the help of an
example. The following example shows a very simple servlet that uses the MSAccess JDBC driver to perform a simple query, printing names and phone numbers
for all employees listed in a database table. We assume that the database contains a
table named CUSTOMER, with at least two fields, NAME and ADDRESS.
/* Example to demonstrate how JDBC is used with Servlet to connect to a customer
table and to display its records*/
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DBPhoneLookup extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
res.setContentType("text/html");
PrintWriter out = res.getWriter();
try {
// Load (and therefore register) the Oracle Driver
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
// Get a Connection to the database
Connection con = DriverManager.getConnection (jdbc:odbc:Access);
// Create a Statement object
stmt = con.createStatement();
// Execute an SQL query, get a ResultSet
rs = stmt.executeQuery("SELECT NAME, ADDRESS FROM CUSTOMER");
// Display the result set as a list
out.println("<HTML><HEAD><TITLE>Phonebook</TITLE></HEAD>");
out.println("<BODY>");
out.println("<UL>");
while(rs.next()) {
out.println("<LI>" + rs.getString("name") + " " + rs.getString("address"));
}
out.println("</UL>");
out.println("</BODY></HTML>");
}
catch(ClassNotFoundException e) {
out.println("Couldn't load database driver: " + e.getMessage());
}
catch(SQLException e) {
out.println("SQLException caught: " + e.getMessage());
}
finally {
// Always close the database connection.
try {
if (con != null) con.close();
}
20
Servlet Programming
In the above example a simple servlet program is written to connect to the database,
and which executes a query that retrieves the names and phone numbers of everyone
in the employees table, and display the list to the user.
Servlets and
JSP Programming
22
The Properties class is intended to be String based, meaning that each key and value is
supposed to be a String.
Servlet Programming
2)
3)
Explain the various purposes for which we use Session tracking. Also, Explain
in brief the two ways to handle Session Tracking in Servlets.
....
4)
5)
6)
23
Servlets and
JSP Programming
7)
8)
9)
10)
11)
12)
13)
What are two different types of servlets ? Explain the differences between these
two.
....
14)
15)
16)
24
17)
What is the difference between Context init parameter and Servlet init
parameter?
....
Servlet Programming
18)
19)
1.10 SUMMARY
Java servlets are the small, platform-independent Java programs that run in a web
server or application server and provide server-side processing such as accessing a
database and e-commerce transactions. Servlets are widely used for web processing.
Servlets dynamically extend the functionality of a web server. A servlet engine can
only execute servlet which is contained in the web-servers like, JWS or JIGSAW.
Servlets are basically developed for the server side applications and designed to
handle http requests. They are better than other common server extensions like, CGI
as they are faster, have all the advantages of Java language and supported by many of
the browsers.
A Java Servlet has a lifecycle that defines how the servlet is loaded and initialised,
how it receives and responds to requests, and how it is taken out of service. Servlets
run within a Servlet Container, creation and destruction of servlets is the duty of
Servlet Container. There are three principal stages in the life of a Java Servlet,
namely: Servlet Initialisation, Servlet Execution and Servlet Destruction. In this first
stage, the servlet's constructor is called together with the servlet method init( ) - this is
called automatically once during the servlets execution life cycle. Once your servlet
is initialised, any request that the Servlet Container receives will be forwarded to your
Servlets service() method. HttpServlet class breaks this service() method into more
useful doGet(), doPost(), doDelete(), doOptions(), doPut() and doTrace() methods
depending on the type of HTTP request it receives. When the application is stopped or
Servlet Container shuts down, your Servlets destroy() method will be called to clean
up any resources allocated during initialisation and to shutdown gracefully.
There are two important interfaces included in the servlet API. They are
HttpServletRequest and HttpServletResponse. HttpServletRequest encapsulates the
functionality for a request object that is passed to an HTTP Servlet. It provides access
to an input stream and so allows the servlet to read data from the client and it has
methods like, getCookies(), getQueryString() & getSession etc. HttpServletResponse
encapsulates the functionality for a response object that is returned to the client from
an HTTP Servlet. It provides access to an output stream and so allows the servlet to
send data to the client and it has methods like, addCookie(), sendError() and
getWriter() etc.
Session tracking is another important feature of servlet. Every user of a site is
associated with a javax.servlet.http.HttpSession object that servlets can use to store or
retrieve information about that user. A servlet uses its request objects getSession()
25
Servlets and
JSP Programming
method to retrieve the current HttpSession object and can add data to an HttpSession
object with the putValue() method. Another technique to perform session tracking
involves persistent cookies. A cookie is a bit of information sent by a web server to a
browser and stores it on a client machine that can later be read back from that
browser. For each request, a cookie can automatically provide a clients session ID or
perhaps a list of the clients preferences.
Servlet along JDBC API can be used to connect to the different databases like,
Sybase, Oracle etc. A servlet written to access a Sybase database can, with a two-line
modification or a change in a properties file, begin accessing an Oracle database. It
again uses the objects and methods of java.sql.* package.
Servlets, which are running together in the same server, have several ways to
communicate with each other. There are three reasons to use InterServlet
communication. First is Direct Servlet manipulation handling in which servlet can
gain access to the other currently loaded servlets and perform some task on each.
Second is Servlet Reuse that allows one servlet to reuse the abilities (the public
methods) of another servlet. Third is Servlet colloboration that allows servlets to
cooperate, usually by sharing some information.
1.11 SOLUTIONS/ANSWERS
Check Your Progress 1
1)
True/ False
a) False
2)
c) True
3)
b) True
They are faster than other server extensions like, CGI scripts because they
use a different process model.
They use a standard API that is supported by many web servers.
It executes within the address space of a web server.
Since servlets are written in Java, servlets are portable between servers and
operating systems. They have all of the advantages of the Java language,
including ease of development and platform independence.
It does not require creation of a separate process for each client request.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<HTML>");
26
Servlet Programming
out.println("<BODY>");
out.println("<B>Welcome to Fifth Semester of MCA</B>");
out.println("</BODY></HTML>");
}
}
4)
Servlets are the Java classes which are created when needed and destroyed
when not needed. Since servlets run within a Servlet Container, creation and
destruction of servlets is the duty of Servlet Container. There are three principal
stages in the life of a Java Servlet Life Cycle, namely:
i) Servlet Initialisation: In this first stage, the servlet's constructor is called
together with the servlet method init( ) - this is called automatically once
during the servlet's execution life cycle and can be used to place any one-off
initialisation such as opening a connection to a database.
ii) Servlet Execution: Once your servlet is initialized and its init() method
called, any request that the Servlet Container receives will be forwarded to
your Servlet's service() method. HttpServlet class breaks this service() method
into more useful doGet(), doPost(), doDelete(), doOptions(), doPut() and
doTrace() methods depending on the type of HTTP request it receives. So in
order to generate response, the doGet() or doPost() method should be
overridden as per the requirement.
When a servlet request is made to the Servlet engine, the Servlet engine
receives all the request parameters (such as the IP address of client), user
information and user data and constructs a Servlet request object, which
encapsulates all this information.
iii) Servlet Destruction: When the application is stopped or Servlet Container
shuts down, Servlets destroy() method will be called to clean up any
resources allocated during initialisation and to shutdown gracefully. Hence, it
acts as a place to deallocate resources such as an open file or open database
connection.
5)
Destruction
Destroy () method
Servlet Class
Garbage Collection
The Server no longer has a
reference to the object
Figure 4: The servlet life cycle
27
Servlets and
JSP Programming
getCookies is the method which is used to obtain cookies from the request
object and following is the its syntax:
public Cookie[] getCookies();
It returns an array containing all the cookies present in this request. Cookies can
be used to uniquely identify clients to servlet. If there are no cookies in the
request, then an empty array is returned.
GetQueryString is the method used to obtain the querystring from the request
object. The syntax used is
public String getQueryString();
It returns query string present in the request URL if any. A query string is
defined as any information following a ? character in the URL. If there is no
query string, this Method returns null.
2)
addCookie is the method which is used to add cookies to the response object.
Syntax is
public void addCookie(Cookie cookie);
It is used to add the specified cookie to the header of response. This method can
be called multiple times to set more than one cookie. This method must be
called before the response is committed so that the appropriate headers can be
set.
sendError is the method used to send an error response. Syntax is :
public void sendError(int statusCode) throws IOException;
28
Servlet Programming
It sends an error response to the client using the specified status code. If a
message is provided to this method, it is emitted as the response body,
otherwise the server should return a standard message body for the error code
given.
3)
To customize the website like shopping cart as per the user requirement or
preference.
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DBPhoneLookup extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
res.setContentType("text/html");
PrintWriter out = res.getWriter();
try {
// Load (and therefore register) the Oracle Driver
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
// Get a Connection to the database
Connection con = DriverManager.getConnection (jdbc:odbc:Access);
// Create a Statement object
stmt = con.createStatement();
// Execute an SQL query, get a ResultSet
rs = stmt.executeQuery("SELECT Product_id, Prod_name, Price, Qty FROM
PRODUCT");
// Display the result set as a list
29
out.println("<HTML><HEAD><TITLE>Phonebook</TITLE></HEAD>");
out.println("<BODY>");
out.println("<Table>");
while(rs.next()) {
out.println("<TR>");
out.println("<TD>" + rs.getString("Product_id") + "</TD><TD>" +
rs.getString("Prod_name") + "</TD><TD> " + rs.getString("Price") +
"</TD><TD> " + rs.getString("Qty") + </TD>);
out.println("</TR>");
Servlets and
JSP Programming
}
out.println("</Table>");
out.println("</BODY></HTML>");
}
catch(ClassNotFoundException e) {
out.println("Couldn't load database driver: " + e.getMessage());
}
catch(SQLException e) {
out.println("SQLException caught: " + e.getMessage());
}
finally {
// Always close the database connection.
try {
if (con != null) con.close();
}
catch (SQLException e1) { }
}}}
5)
The two ways used for servlet collaboration are the following:
a) Colloboration using system property list: One simple way for servlets to
share information is by using Javas system-wide Properties list, found in the
java.lang.System class. This Properties list holds the standard system
properties, such as java.version and path. separator, but it can also hold
application-specific properties. Servlets can use the properties list to hold the
information they need to share. A servlet can add(or change) a property by
calling:
System.getProperties().put(key, value);
b) Collaboration through a shared object : Another way for servlets to
share information is through a shared object. A shared object can hold the pool
of shared information and make it available to each servlet as needed, the
system Properties list is a special case example of a shared object. The shared
object may incorporate the business logic or rules for manipulating the objects
data.
6)
The usual format of a servlet parameter is a name=value pair that comes after a
question-mark (?) at the end of the URL. To access these parameters, call the
getParameter() method on the HttpServletRequest object, then write code to test
the strings. For example, if your URL parameters are func=topic, where your
URL appears as:
7)
8)
The Java Servlet API Specification v2.3 allows you to declaratively restrict
access to specific servlets and JSPs using the Web Application deployment
descriptor. You can also specify roles for EJBs and Web applications through
the Administration Console.
9)
JSP is used mainly for presentation only. A JSP can only be HttpServlet that
means the only supported protocol in JSP is HTTP. But a servlet can support
any protocol like, HTTP, FTP, SMTP etc.
10)
Servlet Programming
In POST data is submitted inside body of the HTTP request. The data is not
visible on the URL and it is more secure.
11)
Yes. But you will not get the servlet specific things from constructor. The
original reason for init() was that ancient versions of Java couldnt dynamically
invoke constructors with arguments, so there was no way to give the
constructor a ServletConfig. That no longer applies, but servlet containers still
will only call your no-arg constructor. So you wont have access to a
ServletConfig or ServletContext.
12)
The servlet context is an object that contains information about the web
application and container. Using the context, a servlet can log events, obtain
URL references to resources, and set and store attributes that other servlets in
the context can use.
13)
14)
15)
Session is stored in server but cookie stored in client. Session should work
regardless of the settings on the client browser. There is no limit on the amount
of data that can be stored on session. But it is limited in cookie. Session can
store objects and cookies can store only strings. Cookies are faster than
session.
16)
Servlets and
JSP Programming
17)
Servlet init parameters are for a single servlet only. No body outside that
servlet can access that. It is declared inside the <servlet> tag inside
Deployment Descriptor, whereas context init parameter is for the entire web
application. Any servlet or JSP in that web application can access context init
parameter. Context parameters are declared in a tag <context-param> directly
inside the <web-app> tag. The methods for accessing context init parameter is
getServletContext ().getInitParamter (name) whereas method for accessing
servlet init parameter is getServletConfig ().getInitParamter (name);
18)
19)
Dietel and Dietel, Internet & World wide Web Programming, Prentice Hall
Inderjeet Singh & Bet Stearns, Designing Enterprise Application with j2EE,
Second Edition platform, Addison Wesley
Budi Kurniawan, Java for the Web with Servlets, JSP, and EJB: A Developer's
Guide to J2EE Solutions, New Riders Publishing.
Justin Couch and Daniel H. Steinberg, Java 2 Enterprise Edition Bible, Hungry
Minds
Marty Hall, Core Servlets and JavaServer Pages (JSP), Prentice Hall.
Reference websites:
32
www.apl.jhu.edu
www.java.sun.com
www.novocode.com
www.javaskyline.com
www.stardeveloper.com
Servlet Programming
33
JAVA Database
Connectivity
Page Nos.
Introduction
Objectives
JDBC Vs ODBC
How Does JDBC Work?
JDBC API
Types of JDBC Drivers
Steps to connect to a Database
Using JDBC to Query a Database
Using JDBC to Modify a Database
Summary
Solutions/Answers
Further Readings/References
33
33
33
34
35
36
39
41
43
45
46
51
2.0 INTRODUCTION
In previous blocks of this course we have learnt the basics of Java Servlets. In this
UNIT we shall cover the database connectivity with Java using JDBC. JDBC (the
Java Database Connectivity) is a standard SQL database access interface that provides
uniform access to a wide range of relational databases like MS-Access, Oracle or
Sybase. It also provides a common base on which higher-level tools and interfaces can
be built. It includes ODBC Bridge. The Bridge is a library that implements JDBC in
terms of the ODBC standard C API. In this unit we will first go through the different
types of JDBC drivers and then JDBC API and its different objects like connection,
statement and ResultSet. We shall also learn how to query and update the database
using JDBC API.
2.1 OBJECTIVES
After going through this unit, you should be able to:
understand the different Types of JDBC drivers & their advantages and
disadvantages;
Servlets and
JSP Programming
driver, between an application and the DBMS. The purpose of this layer is to translate
the application's data queries into commands that the DBMS understands.
Microsoft ODBC API offers connectivity to almost all databases on almost all
platforms and is the most widely used programming interface for accessing relational
databases. But ODBC cannot be used directly with Java Programs due to various
reasons described below.
1) ODBC cannot be used directly with Java because, it uses a C interface. This will
have drawbacks in the security, implementation, and robustness.
2) ODBC makes use of Pointers, which have been removed from Java.
3) ODBC mixes simple and advanced features together and has complex structure.
Hence, JDBC came into existence. If you had done Database Programming with
Visual Basic, then you will be familiar with ODBC. You can connect a VB
Application to MS-Access Database or an Oracle Table directly via ODBC. Since
Java is a product of Sun Microsystems, you have to make use of JDBC with ODBC in
order to develop Java Database Applications.
JDBC is an API (Application Programming Interface) which consists of a set of Java
classes, interfaces and exceptions With the help of JDBC programming interface, Java
programmers can request a connection with a database, then send query statements
using SQL and receive the results for processing.
According to Sun, specialised JDBC drivers are available for all major databases
including relational databases from Oracle Corp., IBM, Microsoft Corp., Informix
Corp. and Sybase Inc. as well as for any data source that uses Microsoft's Open
Database Connectivity system.
The combination of Java with JDBC is very useful because it lets the programmer run
his/ her program on different platforms. Some of the advantages of using Java with
JDBC are:
34
The Java application calls JDBC classes and interfaces to submit SQL statements and
retrieve results.
JAVA Database
Connectivity
java.sql DriverManager
java. sql .Connection
java. sql. Statement
java.sql.Resultset
In addition to these, the following support interfaces are also available to the
developer:
java.sql.Callablestatement
java. sql. DatabaseMetaData
java.sql.Driver
java. sql. PreparedStatement
java. sql .ResultSetMetaData
java. sql. DriverPropertymfo
java.sql.Date
java.sql.Time
java. sql. Timestamp
java.sql.Types
java. sql. Numeric
35
Servlets and
JSP Programming
Disadvantage: For this, User needs to make sure the JDBC driver of the database
vendor is loaded onto each client machine. Must have compiled code for every
operating system that the application will run on. Best use is for controlled
environments, such as an intranet.
JAVA Database
Connectivity
37
Servlets and
JSP Programming
Figure2:ComparisonofdifferentJDBCdrivers
ODBC make use of pointers which have been removed from java.
3)
4)
38
5)
JAVA Database
Connectivity
Use new to explicitly load the Driver class. This hard codes the driver and
(indirectly) the name of the database into your program and is not recommended
as changing the driver or the database or even the name or location of the
database will usually require recompiling the program.
2.
Class.forName takes a string class name and loads the necessary class
dynamically at runtime as specified in the above example. This is a safe method
that works well in all Java environments although it still requires extra coding to
avoid hard coding the class name into the program.
3.
The System class has a static Property list. If this has a Property jdbc.drivers set
to a ':' separated list of driver class names, then all of these drivers will be
loaded and registered automatically. Since there is support for loading property
lists from files easily in Java, this is a convenient mechanism to set up a whole
set of drivers. When a connection is requested, all loaded drivers are checked to
see which one can handle the request and an appropriate one is chosen.
Unfortunately, support for using this approach in servlet servers is patchy so we
will stay with method 2 above but use the properties file method to load the
database url and the driver name at runtime:
Properties props = new Properties() ;
FileInputStream in = new FileInputStream(Database.Properties) ;
props.load(in);
39
Servlets and
JSP Programming
40
JAVA Database
Connectivity
After performing all the above steps, you must close the Connection, statement and
Resultset Objects appropriately by calling the close() method. For example, in our
above code we will close the object as:
ResultSet object with
rs.close();
and statement object with
stmt.close();
Connection object with
conn.close();
Servlets and
JSP Programming
results.getString(1) +
Note that if the field is an Integer, you should use the getInt() method in ResultSet
instead of getString().You can use either an ordinal position (as shown in the above
example) which starts from 1 for the first field or name of field to access the values
from the ResultSet like result.getString(CustomerID);
Compiling JdbcExample1.java
To compile the JdbcExample1.java program to its class file and place it according to
its package statements, open command prompt and cd (change directory) into the
folder containing JdbcExample2.java, then execute this command:
javac -d . JdbcExample2.java
If the program gets compiled successfully then you should get a new Java class under
the current folder with a directory structure JdbcExample2.class in your current
working directory.
Running JdbcExample1.java
To run and to see the output of this program execute following command from the
command prompt from the same folder where JdbcExample2.java is residing:
java JdbcExample2
42
JAVA Database
Connectivity
Servlets and
JSP Programming
}
} // end of main method
} // end of class
As you can see, there is not much to it. Add, modify and delete are all handled by the
executeUpdate() method or executeUpdate(String str) where str is a SQL Insert,
Update or Delete Statement.
..
2)
3)
Assume that there is a table named as Student in MS-Access with the following
fields : Std_id, name, course, ph_no.Write a Java program to insert and then
display the records of this table using JDBC.
4)
5)
6)
7)
44
8)
How should one start debugging problems related to the JDBC API?
....
JAVA Database
Connectivity
9)
10)
How can one retrieve a whole row of data at once, instead of calling an
individual ResultSet.getXXX method for each column?
....
11)
2.9 SUMMARY
JDBC is an API, which stands for Java Database connectivity, provides an interface
through which one can have a uniform access to a wide range of relational databases
like MS-Access, Oracle or Sybase. It also provides bridging to ODBC (Open
Database Connectivity) by JDBC-ODBC Bridge, which implements JDBC in terms of
ODBC standard C API. With the help of JDBC programming interface, Java
programmers can request a connection with a database, then send query statements
using SQL and receive the results for processing. The combination of Java with JDBC
is very useful because it helps the programmer to run the program on different
platforms in an easy and economical way. It also helps in implementing the version
control.
JDBC API mainly consists of 4 main interfaces i.e. java.sql DriverManager, java. sql
.Connection, java. sql. Statement, java.sql.Resultset. The main objects of JDBC are
Datasource, Connection and statement. A DataSource object is used to establish
connections. A Connection object controls the connection to the database. Statement
object is used for executing SQL queries. Statement Object is further divided into
three categories, which are statement, Prepared Statement and callable statement.
Prepared Statement object is used to execute parameterized SQL queries and Callable
statement is used to execute stored procedures within a RDBMS.
JDBC requires drivers to connect any of the databases. There are four types of drivers
available in Java for database connectivity. First two drivers Type1 and Type 2 are
impure Java drivers whereas Type 3 and Type 4 are pure Java drivers. Type 1 drivers
act as a JDBC-ODBC bridge. It is useful for the companies that already have ODBC
drivers installed on each client machine. Type2 driver is Native-API partly Java
technology-enabled driver. It converts the calls that a developer writes to the JDBC
application-programming interface into calls that connect to the client machine's
application programming interface for a specific database like Oracle. Type-3 driver is
A net-protocol fully Java technology-enabled driver and is written in 100% Java. . It
45
Servlets and
JSP Programming
translates JDBC calls into the middleware vendor's protocol, which is then converted
to a database-specific protocol by the middleware server software. Type 4 is a nativeprotocol fully Java technology-enabled driver. It is Direct-to-database pure Java
driver. It converts JDBC technology calls into the network protocol used by different
DBMSs directly.
To connect a database we should follow certain steps. First step is to load an
appropriate driver from any of the four drivers. We can also register the driver by
registerMethod(). Second step is to make the connection with the database using a
getConnection() method of the Driver Manager class which can be with DSN OR
DSN-less connection. Third step is create appropriate JDBC statement to send the
SQL query. Fourth step is to execute the query using executeQuery() method and to
store the data returned by the query in the Resultset object. Then we can navigate the
ResultSet using the next() method and getXXX() to retrieve the integer fields. Last
step is to close the connection and statement objects by calling the close() method. In
this way we can query the database, modify the database, delete the records in the
database using the appropriate query.
True or False
a) True
b) True
2)
JDBC is a standard SQL database access interface that provides uniform access
to a wide range of relational databases. It also provides a common base on
which higher level tools and interfaces can be built. The advantages of using
Java with JDBC are:
3)
There are basically 4 types of drivers available in Java of which 2 are partly
pure and 2 are pure java drivers.
the JDBC application programming interface into calls that connect to the client
machines application programming interface for a specific database, such as IBM,
Informix, Oracle or Sybase
JAVA Database
Connectivity
Advantage: It has a better performance than that of Type 1, in part because the Type
2 driver contains compiled code thats optimized for the back-end database servers
operating system.
Disadvantage: In this, user needs to make sure the JDBC driver of the database
vendor is loaded onto each client machine. It must have compiled code for every
operating system that the application will run on.
Type 3: A net-protocol fully Java technology-enabled driver
They are written in 100% Java and use vendor independent Net-protocol to access a
vendor independent remote listener. This listener in turn maps the vendor independent
calls to vender dependent ones.
Advantage: It has better performance than Types 1 and 2. It can be used when a
company has multiple databases and wants to use a single JDBC driver to connect to
all of them. Since, it is server-based, so there is no requirement for JDBC driver code
on client machine.
Disadvantage: It needs some database-specific code on the middleware server. If the
middleware is to run on different platforms, then Type 4 driver might be more
effective.
Type 4: A native-protocol fully Java technology-enabled driver
It is Direct-to-database pure Java driver. It converts JDBC technology calls into the
network protocol used by different DBMSs directly. It allows a direct call from the
client machine to the database.
Advantage: It again has better performance than Types 1 and 2 and there is no need
to install special software on client or server. It can be downloaded dynamically.
Disadvantage: It is not optimized for server operating system, so the driver can't take
advantage of operating system features. For this, user needs a different driver for each
different database.
4)
OBDC (Open Database Connectivity) cannot be used directly with java due to
the following reasons:
a) ODBC cannot be used directly with Java because it uses a C interface. This
will have drawbacks in the Security, implementation, and robustness.
b) ODBC makes use of Pointers, which have been removed from Java.
c) ODBC mixes simple and advanced features together and has complex
structure.
5)
Statement object is one of the main objects of JDBC API, which is used for
executing the SQL queries. There are 3 different types of JDBC SQL
Statements are available in Java:
a) java.sql.Statement: It is the topmost interface which provides basic methods
useful for executing SELECT, INSERT, UPDATE and DELETE SQL
statements.
47
Servlets and
JSP Programming
2)
After importing the java.sql.* package the next step in database connectivity is
load the appropriate driver. There are various ways to load these drivers:
1. Class.forName takes a string class name and loads the necessary class
dynamically at runtime as specified in the example To load the JDBC-ODBC
driver following syntax may be used :
Class.ForName("sun.jdbc.odbc.JdbcOdbcDriver");
2. To register the third party driver one can use the method registerMethod()
whose syntax is as follows :
DriverManager.registerDriver(Driver dr);
3. Use new to explicitly load the Driver class. This hard codes the driver and
(indirectly) the name of the database into your program
4. The System class has a static Property list. If this has a Property jdbc.drivers
set to a ':' separated list of driver class names, then all of these drivers will be
loaded and registered automatically.
3)
import java.sql.*;
public class Student_JDBC {
public static void main(String args[])
{
Connection con = null;
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
Connection Conn = DriverManager.getConnection (jdbc:odbc:Access);
Statement Stmt = Conn.createStatement();
Statement Stmt2 = Conn.createStatement();
String sql1 = "INSERT INTO STUDENT + " (Std_id, name, course, ph_no)" +
" VALUES (004, 'Sahil', 'MCA' " + "'[email protected]')";
// Now submit the SQL....
try
{
Stmt.executeUpdate(sql);
String sql2 = "SELECT * FROM STUDENT";
ResultSet results = Stmt2.executeQuery(sql);
while (results.next())
{
System.our.println("Std_id: " + results.getString(1) + " Name: " +
results.getString(2) + ", course: " + results.getString(3) + , ph_no: +
results.getString(4));
}
}
// If there was a problem sending the SQL, we will get this error.
48
catch (Exception e)
{
System.out.println("Problem with Sending Query: " + e);
}
finally
{
result.close();
stmt.close();
stmt2.close();
Conn.close();
}
} // end of main method
} // end of class
JAVA Database
Connectivity
Compile and execute this program to see the output of this program. The assumption
is made that table named as STUDENT with the required columns are already existing
in the MS-Access.
4)
Type 4 (JDBC Net pure Java Driver) is the fastest JDBC driver. Type 1 and
Type 3 drivers will be slower than Type 2 drivers (the database calls are make
at least three translations versus two), and Type 4 drivers are the fastest (only
one translation).
5)
No. The JDBC-ODBC Bridge does not support multi threading. The JDBCODBC Bridge uses synchronized methods to serialize all of the calls that it
makes to ODBC. Multi-threaded Java programs may use the Bridge, but they
won't get the advantages of multi-threading.
6)
The JDBC 3.0 API is the latest update of the JDBC API. It contains many
features, including scrollable result sets and the SQL:1999 data types.
7)
We are not allowed to use of the JDBC-ODBC bridge from an untrusted applet
running in a browser, such as Netscape Navigator. The JDBC-ODBC bridge
doesn't allow untrusted code to call it for security reasons. This is good because
it means that an untrusted applet that is downloaded by the browser can't
circumvent Java security by calling ODBC. As we know that ODBC is native
code, so once ODBC is called the Java programming language can't guarantee
that a security violation won't occur. On the other hand, Pure Java JDBC drivers
work well with applets. They are fully downloadable and do not require any
client-side configuration.
Finally, we would like to note that it is possible to use the JDBC-ODBC bridge
with applets that will be run in appletviewer since appletviewer assumes that
applets are trusted. In general, it is dangerous to turn applet security off, but it
may be appropriate in certain controlled situations, such as for applets that will
only be used in a secure intranet environment. Remember to exercise caution if
you choose this option, and use an all-Java JDBC driver whenever possible to
avoid security problems.
8)
There is one facility available to find out what JDBC calls are doing is to enable
JDBC tracing. The JDBC trace contains a detailed listing of the activity
occurring in the system that is related to JDBC operations.
If you use the DriverManager facility to establish your database connection, you
use the DriverManager.setLogWriter method to enable tracing of JDBC
operations. If you use a DataSource object to get a connection, you use the
DataSource.setLogWriter method to enable tracing. (For pooled connections,
you use the ConnectionPoolDataSource.setLogWriter method, and for
49
Servlets and
JSP Programming
9)
10)
The ResultSet.getXXX methods are the only way to retrieve data from a
ResultSet object, which means that you have to make a method call for each
column of a row. There is very little chance that it can cause performance
problem. However, because it is difficult to see how a column could be fetched
without at least the cost of a function call in any scenario.
11)
The classpath may be incorrect and Java cannot find the driver you want to use.
To set the class Path:
The CLASSPATH environment variable is used by Java to determine where to
look for classes referenced by a program. If, for example, you have an import
statement for my.package.mca, the compiler and JVM need to know where to
find the my/package/mca class.
In the CLASSPATH, you do not need to specify the location of normal J2SE
packages and classes such as java.util or java.io.IOException.
You also do not need an entry in the CLASSPATH for packages and classes
that you place in the ext directory (normally found in a directory such as
C:\j2sdk\jre\lib\ext). Java will automatically look in that directory. So, if you
drop your JAR files into the ext directory or build your directory structure off
the ext directory, you will not need to do anything with setting the
CLASSPATH.
Note that the CLASSPATH environment variable can specify the location of
classes in directories and in JAR files (and even in ZIP files).
If you are trying to locate a jar file, then specify the entire path and jar file name
in the CLASSPATH. (Example: CLASSPATH=C:\myfile\myjars\myjar.jar).
If you are trying to locate classes in a directory, then specify the path up to but
not including the name of the package the classes are in. (If the classes are in a
package called my.package and they are located in a directory called
50
JAVA Database
Connectivity
Reference websites:
http://www.developers.sun.com
www.javaworld.com
www.jdbc.postgresql.org
www.jtds.sourceforge.net
www.en.wikipedia.org
www.apl.jhu.edu
http://www.learnxpress.com
http://www.developer.com
51
Servlets and
JSP Programming
Introduction
Objectives
Overview of JSP
Relation of Applets and Servlets with JSP
Scripting Elements
JSP Expressions
JSP Scriplets
JSP Declarations
Predefined Variables
Creating Custom JSP Tag Libraries using Nested Tags
Summary
Solutions/Answers
Further Readings/References
Page Nos.
52
53
53
56
58
59
59
60
61
65
69
70
73
3.0 INTRODUCTION
Nowadays web sites are becoming very popular. These web sites are either static or
dynamic. With a static web page, the client requests a web page from the server and
the server responds by sending back the requested file to the client. Therefore with a
static web page receives an exact replica of the page that exists on the server.
But these days web site requires a lot more than static content. Therefore, these days
dynamic data is becoming very important to everything on the Web, from online
banking to playing games. Dynamic web pages are created at the time they are
requested and their content gets based on specified criteria. For example, a Web page
that displays the current time is dynamic because its content changes to reflect the
current time. Dynamic pages are generated by an application on the server, receiving
input from the client, and responding appropriately.
Therefore, we can conclude that in todays environment, dynamic content is critical to
the success of any Web site. In this unit we will learn about Java Server Pages (JSP)
i.e., an exciting new technology that provides powerful and efficient creation of
dynamic contents. It is a presentation layer technology that allows static Web content
to be mixed with Java code. JSP allows the use of standard HTML, but adds the
power and flexibility of the Java programming language. JSP does not modify static
data, so page layout and look-and-feel can continue to be designed with current
methods. This allows for a clear separation between the page design and the
application. JSP also enables Web applications to be broken down into separate
components. This allows HTML and design to be done without much knowledge of
the Java code that is generating the dynamic data. As the name implies, JSP uses the
Java programming language for creating dynamic content. Javas object-oriented
design, platform independence, and protected-memory model allow for rapid
application development. Built-in networking and enterprise Application
Programming Interfaces (APIs) make Java an ideal language for designing clientserver applications. In addition, Java allows for extremely efficient code reuse by
supporting the Java Bean and Enterprise Java Bean component models.
52
3.1 OBJECTIVES
After going through this unit, you should be able to:
Servlets and
JSP Programming
Figure1. In this Figure, the client requests a server page; the server replaces some
sections of a template with new data, and sends this newly modified page to the
client.
Business logic
It is the portion of the application that solves the business need, e.g., the logic to look
into the users account, draw money and invest it in a certain stock. Implementing the
business logic often requires a great deal of coding and debugging, and is the task of
the programmer.
Presentation layer
Presentation layer takes the results from the business logic execution and displays
them to the user. The goal of the presentation layer is to create dynamic content and
return it to the users browser, which means that those responsible for the
presentation layer are graphics designers and HTML developers.
Now, the question arises that if, applications are composed of a presentation layer
and a business logic layer, what separates them, and why would we want to keep
them apart? Clearly, there needs to be interaction between the presentation layer and
the business logic, since, the presentation layer presents the business logics results.
But how much interaction should there be, and where do we place the various parts?
At one extreme, the presentation and the business logic are implemented in the same
set of files in a tightly coupled manner, so there is no separation between the two.
At the other extreme, the presentation resides in a module totally separate from the
one implementing the business logic, and the interaction between the two is defined
by a set of well-known interfaces. This type of application provides the necessary
54
separation between the presentation and the business logic. But this separation is so
crucial. Reason is explained here:
In most cases the developers of the presentation layer and the business logic are
different people with different sets of skills. Usually, the developers of the
presentation layer are graphics designers and HTML developers who are not
necessarily skilled programmers. Their main goal is to create an easy-to-use,
attractive web page. The goal of programmers who develop the business logic is to
create a stable and scalable application that can feed the presentation layer with data.
These two developers differ in the tools they use, their skill sets, their training, and
their knowledge. When the layers arent separated, the HTML and program code
reside in the same place, as in CGI. Many sites built with those techniques have code
that executes during a page request and returns HTML. Imagine how difficult it is to
modify the User Interface if the presentation logic, for example HTML, is embedded
directly in a script or compiled code. Though developers can overcome this difficulty
by building template frameworks that break the presentation away from the code, this
requires extra work for the developer since the extension mechanisms dont natively
support such templating. Server pages technologies are not any more helpful with
this problem. Many developers simply place Java, VBScript, or other scripting code
directly into the same page as the HTML content. Obviously, this implies
maintenance challenges as the server pages now contain content requiring the skills
of both content developers and programmers. They must check that each updating of
content to a specific server goes through without breaking the scripts inside the
server page. This check is necessary because the server page is cluttered with code
that only the business developer understands. This leaves the presentation developer
walking on eggshells out of concern for preserving the work of the business logic
developer. Worse, this arrangement can often cause situations in which both
developers need to modify a single file, leaving them the tedious task of managing
file ownership. This scenario can make maintaining a server pages-based application
an expensive effort.
Separating these two layers is a problem in the other extension mechanisms, but the
page-centric nature associated with server pages applications makes the problem
much more pronounced. JSP separates the presentation layer (i.e., web interface
logic) from the business logic (i.e. back-end content generation logic) so that web
designers and web developers can work on the same web page without getting in
each other's way.
Static and Dynamic contents in a JSP page
JSP pages usually contain a mixture of both static data and dynamic elements. Static
data is never changed in the server page, and dynamic elements will always be
interpreted and replaced before reaching the client.
JSP uses HTML or XML to incorporate static elements in a web page. Therefore,
format and layout of the page in JSP is built using HTML or XML.
As well as these static elements a JSP page also contains some elements that will be
interpreted and replaced by the server before reaching the client. In order to replace
sections of a page, the server needs to be able to recognise the sections it needs to
change. For this purpose a JSP page usually has a special set of tags to identify a
portion of the page that should be modified by the server. JSP uses the <% tag to
note the start of a JSP section, and the %> tag to note the end of a JSP section. JSP
will interpret anything within these tags as a special section. These tags are known as
scriptlets.
When the client requests a JSP page, the server translates the server page and client
receives a document as HTML. This translation process used at server is displayed in
55
Servlets and
JSP Programming
Figure 2. Since, the processing occurs on the server, the client receives what appears
to be static data. As far as the client is concerned there is no difference between a
server page and a standard web page. This creates a solution for dynamic pages that
does not consume client resources and is completely browser neutral.
Resulting HTML
Server Page
Template
<! DOCTYPE HTML PUBLIC -//W3C//DTD
<HTML>
<HTML>
<HEAD>
<HEAD>
</HEAD>
</HEAD>
<BODY COLOR=#ffffff>
<BODY COLOR=#ffffff>
Scriplets
Figure 2: A Server Page into HTML Data
56
But main problem with applet is its long setup time over modems. Applets need to be
downloaded over the Internet. Instead of just downloading the information to be
displayed, a browser must download the whole application to execute it. The more
functionality the applet provides, the longer it will take to download. Therefore,
applets are best suited for applications that either run on an Intranet, or are small
enough to download quickly and don't require special security access.
Next, Servlet is a Java program that runs in conjunction with a Web Server. A servlet
is executed in response to an HTTP request from a client browser. The servlet
executes and then returns an HTML page back to the browser.
Some major advantages of servlets are:
Major problem with servlets is their limited functionality. Since they deliver HTML
pages to their clients, the user interface available through a servlet is limited by what
the HTML specification supports.
Next, as you know, a JSP is text document that describes how a server should handle
specific requests. A JSP is run by a JSP Server, which interprets the JSP and performs
the actions the page describes. Frequently, the JSP server compiles the JSP into a
servlet to enhance performance. The server would then periodically check the JSP for
changes and if there is any change in JSP, the server will recompile it into a servlet.
JSPs have the same advantages and disadvantages as servlets when compared to
applets.
To the developer, JSPs look very similar to static HTML pages, except that they
contain special tags used to identify and define areas that contain Java functionality.
Because of the close relationship between JSPs and the resulting HTML page, JSPs
are easier to develop than a servlet that performs similar operations. Because they do
not need to be compiled, JSPs are easier to maintain and enhance than servlets.
JSP uses server-side scripting that is actually translated into ------- and
compiled before they are run
a) Applet
b) Servlets
c) HTML
2)
Servlets and
JSP Programming
Scriptlets :The Scriptlet element allows Java code to be embedded directly into
a JSP page.
2.
3.
4.
Actions: Action elements provide information for the translation phase of the
JSP page, and consist of a set of standard, built-in methods. Custom actions can
also be created in the form of custom tags. This is a new feature of the JSP 1.1
specification.
5.
JSP Syntax
The first type of format is called the JSP syntax. It is based on the syntax of other
Server Pages, so it might seem very familiar. It is symbolized by: <% script %>. The
JSP specification refers to this format as the friendly syntax, as it is meant for handauthoring.
JSP Syntax: <% code %>
The second format is an XML standard format for creating JSP pages. This format is
symbolized by: <jsp:element />.
XML syntax would produce the same results, but JSP syntax is recommended for
authoring.
58
Expression element
</HTML>
Servlets and
JSP Programming
A simple use of these scriptlet tags is shown in Example 3.2. In this example you
need to notice the two types of data in the page, i.e., static data and dynamic data.
Here, you need not to worry too much about what the JSP page is doing; that will be
covered in later chapters.
Example 3.2 simpleDate.jsp
<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Final//EN">
<HTML>
<HEAD>
<TITLE>A simple date example</TITLE>
</HEAD>
<BODY COLOR=#ffffff>
The time on the server is
<%= new java.util.Date() %>
</BODY>
Scriplets
</HTML>
When the client requests this JSP page, the client will receive a document as HTML.
The translation process used at server is displayed in Figure 2.
<%!
private ClasJsp Obj;
public void jspInit()
{
...
}
public void jspDestroy()
{
...
}
%>
60
2)
Actions elements
Directive elements
Declarations elements
Scriptlets elements
Actions elements
Directive elements
Declarations elements
Scriptlets elements
6.
7.
8.
9.
The major function of JSP is to describe data being sent to an output stream in
response to a client request. This output stream is exposed to the JSP author through
the implicit out object. The out object is an instantiation of a
javax.servlet.jsp.JspWriter object. This object may represent a direct reference to the
output stream, a filtered stream, or a nested JspWriter from another JSP. Output
should never be sent directly to the output stream, because there may be several output
streams during the lifecycle of the JSP.
The initial JspWriter object is instantiated differently depending on whether the page
is buffered or not. By default, every JSP page has buffering turned on, which almost
61
Servlets and
JSP Programming
always improves performance. Buffering be easily turned off by using the buffered=
false attribute of the page directive.
A buffered out object collects and sends data in blocks, typically providing the best
total throughput. With buffering the PrintWriter is created when the first block is sent,
actually the first time that flush() is called.
With unbuffered output the PrintWriter object will be immediately created and
referenced to the out object. In this situation, data sent to the out object is immediately
sent to the output stream. The PrintWriter will be created using the default settings
and header information determined by the server.
In the case of a buffered out object the OutputStream is not established until the first
time that the buffer is flushed. When the buffer gets flushed depends largely on the
autoFlush and bufferSize attributes of the page directive. It is usually best to set the
header information before anything is sent to the out object It is very difficult to set
page headers with an unbuffered out object. When an unbuffered page is created the
OutputStream is established almost immediately.
The sending headers after the OutputStream has been established can result in a
number of unexpected behaviours. Some headers will simply be ignored, others may
generate exceptions such as IllegalStateException.
The JspWriter object contains most of the same methods as the java.io.PrintWriter
class. However, JspWriter has some additional methods designed to deal with
buffering. Unlike the PrintWriter object, JspWriter throws IOExceptions. In JSP these
exceptions need to be explicitly caught and dealt with. More about the out object is
covered in Chapter 6.
Setting the autoFlush= false attribute of the page directives will cause a buffer
overflow to throw an exception.
Each time a client requests a page the JSP engine creates a new object to represent
that request. This new object is an instance of javax.servlet.http.HttpServletRequest
and is given parameters describing the request. This object is exposed to the JSP
author through the request object.
Through the request object the JSP page is able to react to input received from the
client. Request parameters are stored in special name/value pairs that can be retrieved
using the request.getParameter(name) method.
The request object also provides methods to retrieve header information and cookie
data. It provides means to identify both the client and the server, e.g., it uses
request.getRequestURI() and request.getServerName() to identify the server.
The request object is inherently limited to the request scope. Regardless of how the
page directives have set the scope of the page, this object will always be recreated
with each request. For each separate request from a client there will be a
corresponding request object.
Just as the server creates the request object, it also creates an object to represent the
response to the client.
62
The response object deals with the stream of data back to the client. The out object is
very closely related to the response object. The response object also defines the
interfaces that deal with creating new HTTP headers. Through this object the JSP
author can add new cookies or date stamps, change the MIME content type of the
page, or start server-push ethods. The response object also contains enough
information on the HTTP to be able to return HTTP status codes, such as forcing page
redirects.
The pageContext object is used to represent the entire JSP page. It is intended as a
means to access information about the page while avoiding most of the
implementation details.
This object stores references to the request and response objects for each request.
The application, config, session, and out objects are derived by accessing attributes of
this object. The pageContext object also contains information about the directives
issued to the JSP page, including the buffering information, the errorPageURL, and
page scope. The pageContext object does more than just act as a data repository. It is
this object that manages nested JSP pages, performing most of the work involved with
the forward and include actions. The pageContext object also handles uncaught
exceptions.
From the perspective of the JSP author this object is useful in deriving information
about the current JSP page's environment. This can be particularly useful in creating
components where behavior may be different based on the JSP page directives.
The session object is used to track information about a particular client while using
stateless connection protocols, such as HTTP. Sessions can be used to store arbitrary
information between client requests.
Each session should correspond to only one client and can exist throughout multiple
requests. Sessions are often tracked by URL rewriting or cookies, but the method for
tracking of the requesting client is not important to the session object.
The session object is an instance of javax.servlet.http.HttpSession and behaves exactly
the same way that session objects behave under Java Servlets.
The application object is direct wrapper around the ServletContext object for the
generated Servlet. It has the same methods and interfaces that the ServletContext
object does in programming Java Servlets.
This object is a representation of the JSP page through its entire lifecycle. This object
is created when the JSP page is initialized and will be removed when the JSP page is
removed by the jspDestroy() method, the JSP page is recompiled, or the JVM crashes.
Information stored in this object remains available to any object used within the JSP
page.
The application object also provides a means for a JSP to communicate back to the
server in a way that does not involve requests. This can be useful for finding out
information about the MIME type of a file, sending log information directly out to the
servers log, or communicating with other servers.
63
Servlets and
JSP Programming
This object is an actual reference to the instance of the page. It can be thought of as an
object that represents the entire JSP page. When the JSP page is first instantiated the
page object is created by obtaining a reference to this object. So, the page object is
really a direct synonym for this object.
However, during the JSP lifecycle, this object may not refer to the page itself. Within
the context of the JSP page, the page object will remain constant and will always
represent the entire JSP page.
The error handling method utilises this object. It is available only when the previous
JSP page throws an uncaught exception and the <%@ pageerrorPage= ... %> tag
was used. The exception object is a wrapper containing the exception thrown from the
previous page. It is typically used to generate an appropriate response to the error
condition.
A summarized picture of these predefined variables (implicit objects) is given in
Table 4.
Table 4: Implicit Objects in JSP
64
Variable
Class
Description
out
javax.servlet.jsp.JspWriter
request
Subtype of
javax.servlet.ServletRequest
response
Subtype of
javax.servlet.ServletResponse
pageContext javax.servlet.jsp.PageContext
Session
javax.servlet.http.HttpSession
application
javax.servlet.ServletContext
config
javax.servlet.ServletConfig
page
java.lang.Object
exception
java.lang.Throwable
Servlets and
JSP Programming
Now in the following section, we will read an overview of each of these components,
and learn how to build these components for various styles of tags.
To define a new tag, first you have to define a Java class that tells the system what to
do when it sees the tag. This class must implement the javax.servlet.jsp.tagext.Tag
interface. This is usually accomplished by extending the TagSupport or
BodyTagSupport class. Example 3.4 is an example of a simple tag that just inserts
Custom tag example (coreservlets.tags.ExampleTag) into the JSP page wherever the
corresponding tag is used.
Dont worry about understanding the exact behavior of this class. For now, just note
that it is in the coreservlets.tags class and is called ExampleTag. Thus, with Tomcat
3.1, the class file would be in install_dir/webapps/ROOT/WEBINF/classes/coreservlets/tags/ExampleTag.class.
Example 3.4 ExampleTag.java
package coreservlets.tags;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
/** Very simple JSP tag that just inserts a string
* (Custom tag example...) into the output.
* The actual name of the tag is not defined here;
* that is given by the Tag Library Descriptor (TLD)
* file that is referenced by the taglib directive
* in the JSP file.
*/
public class ExampleTag extends TagSupport {
public int doStartTag() {
try {
JspWriter out = pageContext.getOut();
out.print(Custom tag example +
(coreservlets.tags.ExampleTag));
} catch(IOException ioe) {
System.out.println(Error in ExampleTag: + ioe);
}
return(SKIP_BODY);
}
}
After defining a tag handler, your next task is to identify the class to the server and to
associate it with a particular XML tag name. This task is accomplished by means of a
tag library descriptor file (in XML format) like the one shown in Example 3.5. This
66
file contains some fixed information, an arbitrary short name for your library, a short
description, and a series of tag descriptions. The bold part of the example is the same
in virtually all tag library descriptors.
Dont worry about the format of tag descriptions. For now, just note that the tag
element defines the main name of the tag (really tag suffix, as will be seen shortly)
and identifies the class that handles the tag. Since, the tag handler class is in the
coreservlets.tags package, the fully qualified class name of
coreservlets.tags.ExampleTag is used. Note that this is a class name, not a URL or
relative path name. The class can be installed anywhere on the server that beans or
other supporting classes can be put. With Tomcat 3.1, the standard base location is
install_dir/webapps/ROOT/WEB-INF/classes, so ExampleTag would be in
install_dir/webapps/ROOT/WEB-INF/classes/coreservlets/tags. Although it is always
a good idea to put your servlet classes in packages, a surprising feature of Tomcat 3.1
is that tag handlers are required to be in packages.
Example 3.5 csajsp-taglib.tld
<?xml version= 1.0 encoding= ISO-8859-1 ?>
<!DOCTYPE taglib
PUBLIC -//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN
http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd>
67
Servlets and
JSP Programming
Once, you have a tag handler implementation and a tag library description, you are
ready to write a JSP file that makes use of the tag. Example 3.6 shows a JSP file.
Somewhere before the first use of your tag, you need to use the taglib directive. This
directive has the following form:
<%@ taglib uri= ... prefix= ... %>
The required uri attribute can be either an absolute or relative URL referring to a tag
library descriptor file like the one shown in Example 3.5. To complicate matters a
little, however, Tomcat 3.1 uses a web.xml file that maps an absolute URL for a tag
library descriptor to a file on the local system. I don't recommend that you use this
approach.
The prefix attribute, also required, specifies a prefix that will be used in front of
whatever tag name the tag library descriptor defined. For example, if the TLD file
defines a tag named tag1 and the prefix attribute has a value of test, the actual tag
name would be test:tag1. This tag could be used in either of the following two ways,
depending on whether it is defined to be a container that makes use of the tag body:
<test:tag1>
Arbitrary JSP
</test:tag1>
or just
<test:tag1 />
To illustrate, the descriptor file of Example 3.5 is called csajsp-taglib.tld, and resides
in the same directory as the JSP file shown in Example 3.6. Thus, the taglib directive
in the JSP file uses a simple relative URL giving just the filename, as shown below.
<%@ taglib uri= csajsp-taglib.tld prefix= csajsp %>
Furthermore, since the prefix attribute is csajsp (for Core Servlets and JavaServer
Pages), the rest of the JSP page uses csajsp:example to refer to the example tag
defined in the descriptor file.
Example 3.6 SimpleExample.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<%@ taglib uri="csajsp-taglib.tld" prefix="csajsp" %>
<TITLE><csajsp:example /></TITLE>
<LINK REL=STYLESHEET
HREF="JSP-Styles.css"
TYPE="text/css">
</HEAD>
<BODY>
<H1><csajsp:example /></H1>
<csajsp:example />
</BODY>
</HTML>
68
2)
4)
What is a custom tags. in JSP? What are the components that make up a tag
library in JSP?
....
3.10 SUMMARY
In this unit, we first studied the static and dynamic web pages. With a static web page,
the client requests a web page from the server and the server responds by sending
back the requested file to the client, server doesnt process the requested page at its
69
Servlets and
JSP Programming
end. But dynamic web pages are created at the time they are requested and their
content gets based on specified criteria. These pages are generated by an application
on the server, receiving input from the client, and responding appropriately. For
creation of these dynamic web pages, we can use JSP; it is a technology using serverside scripting that is actually translated into servlets and compiled before they are run.
It separates the presentation layer (i.e., web interface logic) from the business logic
(i.e., back-end content generation logic) so that web designers and web developers can
work on the same web page without getting in each other's way.
There are five basic types of elements in JSP. These are scriptlets, expressions,
declarations, actions and directives. Among these elements the first three elements,
i.e., scriptlets, expressions, and declarations, are collectively called scripting elements.
Here scriptlet (<%%>) element allows Java code to be embedded directly into a
JSP page, expression element (<%=%>) is used to print the output of a Java
fragment and declaration element (<%! code %>) is used to initialise variables and
methods and make them available to other declarations, scriptlets, and expressions.
Next, we discussed about the implicit objects of JSP. Various implicit objects of JSP
are out, request, response, pageContext, session, application, config, page and
exception object. Here, out object refers to the output stream, request object contains
parameters describing the request made by a client to JSP engine, response object
deals with the stream of data back to the client, pageContext object is used to
represent the entire JSP page, session object is used to track information about a
particular client while using stateless connection protocols such as HTTP, application
object is a representation of the JSP page through its entire lifecycle, config object
allows the JSP author access to the initialisation parameters for the servlet or JSP
engine, page object is an actual reference to the instance of the page and exception
object is a wrapper containing the exception thrown from the previous page.
Finally we studied about the custom tags. These are user-defined JSP language
elements. Unlike HTML, these custom tags (JSP tags) are interpreted on the server
side not client side. To use custom JSP tags, you need to define three separate
components, i.e., tag handler class, tag library descriptor file and the JSP file. Here,
tag handler class defines the tags behaviour, tag library descriptor file maps the XML
element names to the tag implementations and the JSP file uses the tag library.
3.11 SOLUTIONS/ANSWERS
Check Your Progress 1
1)
2)
3)
JSP is an exciting new technology that provides powerful and efficient creation
of dynamic contents. It allows static web content to be mixed with Java code. It
is a technology using server-side scripting that is actually translated into servlets
and compiled before they are run. This gives developers a scripting interface to
create powerful Java Servlets.
Role of JSP in the development of websites:
In today's environment, dynamic content is critical to the success of any web
site. There are a number of technologies available for incorporating the dynamic
contents in a site. But most of these technologies have some problems. Servlets
offer several improvements over other server extension methods, but still suffer
from a lack of presentation and business logic separation. Therefore the Java
community worked to define a standard for a servlet-based server pages
environment and the outcome was what we now know as JSP. JSP separates the
70
presentation layer (i.e., web interface logic) from the business logic (i.e., backend content generation logic) so that web designers and web developers can
work on the same web page without getting in each other's way.
2)
3)
There are five basic types of elements used in JSP. These are:
(i) Scriptlets
JSP Syntax: <% code %>
XML Syntax: <jsp: scriptlet > code </jsp:scriptlet>
The Scriptlet element allows Java code to be embedded directly into a JSP page.
(ii) Expressions
JSP Syntax: <%= code %>
XML Syntax: <jsp:expression > code </jsp:expression>
An expression element is a Java language expression whose value is evaluated
and returned as a string to the page.
(iii) Declarations
JSP Syntax: <%! code %>
XML Syntax: <jsp:declaration> code </jsp:declaration>
A declaration element is used to declare methods and variables that are
initialized with the page.
(iv) Actions
Action elements provide information for the translation phase of the JSP page,
and consist of a set of standard, built-in methods. Custom actions can also be
created in the form of custom tags. This is a new feature of the JSP 1.1
specification.
(v) Directives
Directive elements contain global information that is applicable to the whole
page.
The first three elements Scriptlets, Expressions, and Declarations are
collectively called scripting elements.
2)
3)
Servlets and
JSP Programming
ii) The request object: It contains parameters describing the request made by
a client to JSP engine.
iii) The response object: This object deals with the stream of data back to the
client.
iv) The pageContext object: This object is used to represent the entire JSP
page.
v) The session object: This object is used to track information about a
particular client while using stateless connection protocols such as HTTP.
vi) The application object: This object is a representation of the JSP page
through its entire lifecycle.
vii) The config object: This object allows the JSP author access to the
initialization parameters for the servlet or JSP engine.
viii) The page object: This object is an actual reference to the instance of the
page.
ix) The exception object: This object is a wrapper containing the exception
thrown from the previous page.
4)
A custom tag is a user-defined JSP language element. Custom JSP tags are also
interpreted by a program; but, unlike HTML, JSP tags are interpreted on the
server side not client side. The program that interprets custom JSP tags is the
runtime engine in the application server as Tomcat, JRun, WebLogic, etc. When
a JSP page containing a custom tag is translated into a servlet, the tag is
converted to operations on an object called a tag handler. The web container
then invokes those operations when the JSP pages servlet is executed.
Custom tags have a rich set of features. They can
72
Page Nos.
Introduction
Objectives
Database handling in JSP
Including Files and Applets in JSP Documents
Integrating Servlet and JSP
73
73
74
78
83
4.5
4.6
4.7
Summary
Solutions/Answers
Further Readings/References
89
89
90
4.0 INTRODUCTION
In the previous unit, we have discussed the importance of JSP. We also studied the
basic concepts of JSP. Now, in this unit, we will discuss some more interesting
features of JSP. As you know, JSP is mainly used for server side coding.
Therefore, database handling is the core aspect of JSP. In this unit, first you will
study about database handling through JSP. In that you will learn about
administratively register a database, connecting a JSP to an Access database, insert
records in a database using JSP, inserting data from HTML Form in a database using
JSP, delete Records from Database based on Criteria from HTML Form and retrieve
data from a database using JSP result sets.
Then you will learn about how to include files and applets in JSP documents. In this
topic you mainly learn about three main capabilities for including external pieces into
a JSP document, i.e., jsp:include action, include directive and jsp:plugin action.
Finally, you will learn about integration of servlet and JSP. In this topic you learn
about how to forward the requests, how to include static or dynamic content and how
to forward requests from JSP Pages.
4.1 OBJECTIVES
After going through this unit, you should be able to:
understand how to select, insert and delete records in database using JSP;
understand how to include the output of JSP, HTML or plain text pages at the
time the client requests the page;
understand how to include JSP files at the time the main page is translated into a
servlet;
understand how to include applets that use the Java Plug-In, and
Servlets and
JSP Programming
Java cannot talk to a database until, it is registered as a data source to your system.
The easiest way to administratively identify or registrar the database to your system so
your Java Server Page program can locate and communicate with it is to do the
following:
1)
2) Go to: Control panel > Admin tool > ODBC where you will identify the database
as a so-called data source.
3) Under the User DSN tab, un-highlight any previously selected name and then
click on the Add button.
4) On the window that then opens up, highlight MS Access Driver and click Finish.
5) On the ODBC Setup window that then opens, fill in the data source name. This is
the name that you will use to refer to the database in your Java program such as
Mimi.
6) Then click Select and navigate to the already created database in directory D.
Suppose the file name is testCase001.mdb. After highlighting the named file,
click OKs all the way back to the original window.
This completes the registration process. You could also use the create option to create
the Access database from scratch. But the create setup option destroys any existing
database copy. So, for an existing DB follow the procedure described above.
We will now describe the Java code required to connect to the database although at
this point we will not yet query it. To connect with database, the JSP program has to
do several things:
1. Identify the source files for Java to handle SQL.
2. Load a software driver program that lets Java connect to the database.
3. Execute the driver to establish the connection.
74
The safer and more conventional code to do the same thing would include the
database connection statements in a Java try/catch combination. This combination
acts like a safety net. If the statements in the try section fail, then the Exceptions that
they caused are caught in the catch section. The catch section can merely report the
nature of the Exception or error (in the string exc shown here) or do more extensive
backup processing, depending on the circumstances. The code looks like:
<%@ page import= java.sql.* %>
<%
Connection conn=null;
try
{ Class.forName (sun.jdbc.odbc.JdbcOdbcDriver);
conn = DriverManager.getConnection(jdbc:odbc:Mimi, ,
);
}
catch (Exception exc)
{ out.println(exc.toString() + <br>); }
75
Servlets and
JSP Programming
So far other than connecting to the database and then closing the connection to the
database we have not had any tangible impact on the database. This section
illustrates that we have actually communicated with the database by using simple SQL
insert examples. In general, SQL inserts in a JSP environment would depend on data
obtained from an HTML Form. But addressing that involves additional
complications, so we shall stick here to simple fixed inserts with hardwired data. To
do insert or indeed to use any kind of SQL queries we have to:
1. Create a Statement object - which has methods for handling SQL.
2. Define an SQL query - such as an insert query.
3. Execute the query.
Example testCase002. adds the following statements to insert an entry in the
database:
Statement stm = conn.createStatement ( );
String
stm.executeUpdate (s);
The Connection object conn that was previously created has methods that allow us to
in turn create a Statement object. The names for both these objects (in this case conn
and stm) are of course just user-defined and could be anything we choose. The
Statement object stm only has to be created once. The insert SQL is stored in a Java
String variable. The table managers we created in the database (off-line) has a single
text attribute (managerName) which is not indicated in the query. The value of a text
attribute must be enclosed in single quotes. Finally, the Statement objects
executeUpdate method is used to execute the insert query. If you run the
testCase002.jsp example and check the managers table contents afterwards, you will
see that the new record has been added to the table.
Generally, these statements are executed under try/catch control. Thus, the
executeUpdate ( s ) method is handled using:
try
catch (Exception exc) {
stm.executeUpdate(s);
out.println(exc.toString());
}
}
as in testCase002.jsp. If the update fails because there is an error in the query string
submitted (in s), then the catch clause takes over. The error or exception is set by the
system in exc. The body of the catch can output the error message as shown. It could
also do whatever other processing the programmer deemed appropriate.
The JSP acquires the data to be inserted into a database from an HTML Form. This
interaction involves several elements:
1. An HTML Form with named input fields.
76
2. JSP statements that access the data sent to the server by the form.
3. Construction of an insert query based on this data by the JSP program.
4. Execution of the query by the JSP program.
To demonstrate this process, we have to define the HTML page that will be accessed
by the JSP program. We will use testCase000.html which has three input fields:
mName, mAge, and mSalary. It identifies the requested JSP program as
testCase003.jsp. For simplicity, initially assume the Access table has a single text
attribute whose value is picked up from the Form. The example testCase003.jsp must
acquire the Form data, prep it for the query, build the query, then execute it. It also
sends a copy of the query to the browser so you can see the constructed query. The
relevant statements are:
String name
= request.getParameter (mName);
name
String
= + name + ;
s = INSERT INTO Managers VALUES ( ;
s += name ;
s += ) ;
stm.executeUpdate (s);
out.println (<br>+s+<br>);
In the above code, the first statement acquires the form data, the second preps it for
the database insert by attaching single quotes fore and aft, the next three statements
construct the SQL insert query, the next statement executes the query, and the final
statement displays it for review on the browser.
We can illustrate the application of an SQL delete query using the same HTML Form.
The difference between the insert and the delete is that the delete has a where clause
that determines which records are deleted from the database. Thus, to delete a record
where the attribute name has the text value Rahul, the fixed SQL is:
String
Rahul '
Retrieving data from a database is slightly more complicated than inserting or deleting
data. The retrieved data has to be put someplace and in Java that place is called a
ResultSet. A ResultSet object, which is essentially a table of the returned results as
done for any SQL Select, is returned by an executeQuery method, rather than the
executeUpdate method used for inserts and deletes. The steps involved in a select
retrieval are:
1. Construct a desired Select query as a Java string.
2. Execute the executeQuery method, saving the results in a ResultSet object r.
3. Process the ResultSet r using two of its methods which are used in tandem:
a) r.next ( ) method moves a pointer to the next row of the retrieved table.
77
Servlets and
JSP Programming
b) r.getString (attribute-name) method extracts the given attribute value from the
currently pointed to row of the table.
A simple example of a Select is given in testCase04 where a fixed query is defined.
The relevant code is:
String
ResultSet
= stm.executeQuery(s);
while ( r.next( ) )
{
out.print (<br>Name: + r.getString (name) );
out.println(
Age :
+ r.getString (age ) );
}
The query definition itself is the usual SQL Select. The results are retrieved from the
database using stm.executeQuery (s). The while loop (because of its repeated
invocation of r.next( ) advances through the rows of the table which was returned in
the ResultSet r. If this table is empty, the while test fails immediately and exits.
Otherwise, it points to the row currently available. The values of the attributes in that
row are then accessed using the getString method which returns the value of the
attribute name or age. If you refer to an attribute that is not there or misspell,
you'll get an error message Column not found. In this case, we have merely output
the retrieved data to the HTML page being constructed by the JSP. Once, the whole
table has been scanned, r.next( ) returns False and the while terminates. The entire
process can be included in a try/catch combination for safety.
3)
4)
78
Include directive includes dynamic page, i.e., JSP code. It is powerful, but poses
maintenance challenges.
iii) jsp:plugin action
This inserts applets that use the Java plug-in. It increases client side role in dialog.
Now, we will discuss in details about this capability of JSP.
You can include a file with JSP at the page translation time. In this case file will be
included in the main JSP document at the time the document is translated into a
servlet (which is typically the first time it is accessed).
To include file in this way, the syntax is:
<%@ include file= Relative URL %>
There are two consequences of the fact that the included file is inserted at page
translation time, not at request time as with jsp: include.
First, you include the actual file itself, unlike with jsp:include , where the server runs
the page and inserts its output. This approach means that the included file can contain
JSP constructs (such as field or method declarations) that affect the main page as a
whole.
Second, if the included file changes, all the JSP files that use it need to be updated.
As you studied, the include directive provides the facility to include documents that
contain JSP code into different pages. But this directive requires you to update the
modification date of the page whenever the included file changes, which is a
significant inconvenience.
Now, we will discuss about the jsp:include action. It includes files at the time of the
client request and thus does not require you to update the main file when an included
file changes. On the other hand, as the page has already been translated into a servlet
at request time, thus the included files cannot contain JSP.
Although the included files cannot contain JSP, they can be the result of resources that
use JSP to create the output. That is, the URL that refers to the included resource is
interpreted in the normal manner by the server and thus can be a servlet or JSP page.
This is precisely the behaviour of the include method of the RequestDispatcher class,
which is what servlets use if they want to do this type of file inclusion.
The jsp:include element has two required attributes (as shown in the sample below),
these elements are:
i)
ii)
Servlets and
JSP Programming
To include ordinary applets with JSP, you dont need any special syntax; you need to
just use the normal HTML APPLET tag. But, these applets must use JDK 1.1 or JDK
1.02, because neither Netscape 4.x nor Internet Explorer 5.x support the Java 2
platform (i.e., JDK 1.2). This lack of support imposes several restrictions on applets
these are:
In order to use Swing, you must send the Swing files over the network. This
process is time consuming and fails in Internet Explorer 3 and Netscape 3.x and
4.01-4.05 (which only support JDK 1.02), since Swing depends on JDK 1.1.
You cannot use Java 2D.
You cannot use the Java 2 collections package.
Your code runs more slowly, since most compilers for the Java 2 platform are
significantly improved over their 1.1 predecessors.
To solve this problem, Sun developed a browser plug-in for Netscape and Internet
Explorer that lets you use the Java 2 platform for applets in a variety of browsers. It is
a reasonable alternative for fast corporate intranets, especially since applets can
automatically prompt browsers that lack the plug-in to download it. But, since, the
plug-in is quite large (several megabytes), it is not reasonable to expect users on the
WWW at large to download and install it just to run your applets. As well as, the
normal APPLET tag will not work with the plug-in, since browsers are specifically
designed to use only their built-in virtual machine when they see APPLET. Instead,
you have to use a long and messy OBJECT tag for Internet Explorer and an equally
long EMBED tag for Netscape. Furthermore, since, you typically dont know which
browser type will be accessing your page, you have to either include both OBJECT
and EMBED (placing the EMBED within the COMMENT section of OBJECT) or
identify the browser type at the time of the request and conditionally build the right
tag. This process is straightforward but tedious and time consuming.
The jsp:plugin element instructs the server to build a tag appropriate for applets that
use the plug-in. Servers are permitted some leeway in exactly how they implement
this support, but most simply include both OBJECT and EMBED.
The simplest way to use jsp:plugin is to supply four attributes: type, code, width, and
height. You supply a value of applet for the type attribute and use the other three
attributes in exactly the same way as with the APPLET element, with two exceptions,
i.e., the attribute names are case sensitive and single or double quotes are always
required around the attribute values.
For example, you could replace
<APPLET CODE= MyApplet.class WIDTH=475 HEIGHT=350>
</APPLET>
with
<jsp:plugin type="applet" code="MyApplet.class" width="475"
height="350">
</jsp:plugin>
The jsp:plugin element has a number of other optional attributes. A list of these
attributes is:
type:
For applets, this attribute should have a value of applet. However, the Java Plug-In
also permits you to embed JavaBeans elements in Web pages. Use a value of bean in
such a case.
80
code :
This attribute is used identically to the CODE attribute of APPLET, specifying the
top-level applet class file that extends Applet or JApplet. Just remember that the name
code must be lower case with jsp:plugin (since, it follows XML syntax), whereas with
APPLET, case did not matter (since, HTML attribute names are never case sensitive).
width :
This attribute is used identically to the WIDTH attribute of APPLET, specifying the
width in pixels to be reserved for the applet. Just remember that you must enclose the
value in single or double quotes.
height :
This attribute is used identically to the HEIGHT attribute of APPLET, specifying the
height in pixels to be reserved for the applet. Just remember that you must enclose the
value in single or double quotes.
codebase :
align:
This attribute is used identically to the ALIGN attribute of APPLET and IMG,
specifying the alignment of the applet within the web page. Legal values are left,
right, top, bottom, and middle. With jsp:plugin, dont forget to include these values in
single or double quotes, even though quotes are optional for APPLET and IMG.
hspace :
vspace :
archive :
name :
Servlets and
JSP Programming
title :
This attribute is used identically to the very rarely used TITLE attribute of APPLET
(and virtually all other HTML elements in HTML 4.0), specifying a title that could be
used for a tool-tip or for indexing.
jreversion :
This attribute identifies the version of the Java Runtime Environment (JRE) that is
required. The default is 1.1.
iepluginurl :
This attribute designates a URL from which the plug-in for Internet Explorer can be
downloaded. Users who dont already have the plug-in installed will be prompted to
download it from this location. The default value will direct the user to the Sun site,
but for intranet use you might want to direct the user to a local copy.
nspluginurl :
This attribute designates a URL from which the plug-in for Netscape can be
downloaded. The default value will direct the user to the Sun site, but for intranet use
you might want to direct the user to a local copy.
The jsp:param and jsp:params Elements
The jsp:param element is used with jsp:plugin in a manner similar to the way that
PARAM is used with APPLET, specifying a name and value that are accessed from
within the applet by getParameter. There are two main differences between jsp:param
and param with applet, these are :
First, since jsp:param follows XML syntax, attribute names must be lower case,
attribute values must be enclosed in single or double quotes, and the element must end
with />, not just >.
Second, all jsp:param entries must be enclosed within a jsp:params element.
So, for example, you would replace
<APPLET CODE= MyApplet.class WIDTH=475 HEIGHT=350>
<PARAM NAME=PARAM1 VALUE= VALUE1>
<PARAM NAME= PARAM2 VALUE= VALUE2>
</APPLET>
with
<jsp:plugin type= applet code= MyApplet.class width= 475 height=350>
<jsp:params>
<jsp:param name=PARAM1 value= VALUE1 />
<jsp:param name= PARAM2 value=VALUE2 />
</jsp:params>
</jsp:plugin>
82
The jsp:fallback element provides alternative text to browsers that do not support
OBJECT or EMBED. You use this element in almost the same way as you would use
alternative text placed within an APPLET element.
So, for example, you would replace
<APPLET CODE=MyApplet.class WIDTH=475 HEIGHT=350>
<B>Error: this example requires Java.</B>
</APPLET>
with
<jsp:plugin type=applet code= MyApplet.class width=475 height=350>
<jsp:fallback>
<B>Error: this example requires Java.</B>
</jsp:fallback>
</jsp:plugin>
4.4.1
Forwarding Requests
The key to letting servlets forward requests or include external content is to use a
requestDispatcher. You obtain a RequestDispatcher by calling the
getRequestDispatcher method of ServletContext, supplying a URL relative to the
server root.
83
Servlets and
JSP Programming
84
In most cases, you forward requests to a JSP page or another servlet. In some cases,
however, you might want to send the request to a static HTML page. In an
e-commerce site, for example, requests that indicate that the user does not have a valid
account name might be forwarded to an account application page that uses HTML
forms togather the requisite information. With GET requests, forwarding requests to a
static HTML page is perfectly legal and requires no special syntax; just supply the
address of the HTML page as the argument to getRequestDispatcher. However, since,
forwarded requests use the same request method as the original request, POST
requests cannot be forwarded to normal HTML pages. The solution to this problem is
to simply rename the HTML page to have a .jsp extension. Renaming somefile.html to
somefile.jsp does not change its output for GET requests, but somefile.html cannot
handle POST requests, whereas somefile.jsp gives an identical response for both GET
and POST.
Supplying Information to the Destination Pages
To forward the request to a JSP page, a servlet merely needs to obtain a
RequestDispatcher by calling the getRequestDispatcher method of ServletContext,
then call forward on the result, supplying the Http- ServletRequest and
HttpServletResponse as arguments. Thats fine as far as it goes, but this approach
requires the destination page to read the information it needs out of the
HttpServletRequest. There are two reasons why it might not be a good idea to have
the destination page look up and process all the data itself. First, complicated
programming is easier in a servlet than in a JSP page. Second, multiple JSP pages may
require the same data, so it would be wasteful for each JSP page to have to set up the
same data. A better approach is for, the original servlet to set up the information that
the destination pages need, then store it somewhere that the destination pages can
easily access. There are two main places for the servlet to store the data that the JSP
pages will use: in the HttpServletRequest and as a bean in the location specific to the
scope attribute of jsp:useBean.
The originating servlet would store arbitrary objects in the HttpServlet-Request by
using
request.setAttribute(key1, value1);
The destination page would access the value by using a JSP scripting element to call
Type1 value1 = (Type1)request.getAttribute(key1);
For complex values, an even better approach is to represent the value as a bean and
store it in the location used by jsp:useBean for shared beans. For example, a scope of
application means that the value is stored in the ServletContext, and ServletContext
uses setAttribute to store values. Thus, to make a bean accessible to all servlets or JSP
pages in the server or Web application, the originating servlet would do the following:
Type1 value1 = computeValueFromRequest(request);
getServletContext().setAttribute(key1, value1);
The destination JSP page would normally access the previously stored value by using
jsp:useBean as follows:
<jsp:useBean id= key1 class= Type1 scope=application />
Alternatively, the destination page could use a scripting element to explicitly call
application.getAttribute(key1) and cast the result to Type1. For a servlet to make
85
Servlets and
JSP Programming
data specific to a user session rather than globally accessible, the servlet would store
the value in the HttpSession in the normal manner, as below:
Type1 value1 = computeValueFromRequest(request);
HttpSession session = request.getSession(true);
session.putValue(key1, value1);
The destination page would then access the value by means of
<jsp:useBean id= key1 class= Type1 scope= session />
The Servlet 2.2 specification adds a third way to send data to the destination page
when using GET requests: simply append the query data to the URL. For example,
String address = /path/resource.jsp?newParam=value;
RequestDispatcher dispatcher =getServletContext().getRequestDispatcher(address);
dispatcher.forward(request, response);
This technique results in an additional request parameter of newParam (with a value
of value) being added to whatever request parameters already existed. The new
parameter is added to the beginning of the query data so that it will replace existing
values if the destination page uses getParameter (use the first occurrence of the named
parameter) rather than get- ParameterValues (use all occurrences of the named
parameter).
Interpreting Relative URLs in the Destination Page
Although a servlet can forward the request to arbitrary locations on the same server,
the process is quite different from that of using the sendRedirect method of
HttpServletResponse.
First, sendRedirect requires the client to reconnect to the new resource, whereas the
forward method of RequestDispatcher is handled completely on the server.
Second, sendRedirect does not automatically preserve all of the request data; forward
does.
Third, sendRedirect results in a different final URL, whereas with forward, the URL
of the original servlet is maintained.
This final point means that, if the destination page uses relative URLs for images or
style sheets, it needs to make them relative to the server root, not to the destination
pages actual location. For example, consider the following style sheet entry:
<LINK REL=STYLESHEET HREF= my-styles.css TYPE= text/css>
If the JSP page containing this entry is accessed by means of a forwarded request, mystyles.css will be interpreted relative to the URL of the originating servlet, not relative
to the JSP page itself, almost certainly resulting in an error. The solution is to give the
full server path to the style sheet file, as follows:
<LINK REL=STYLESHEET HREF= /path/my-styles.css TYPE= text/css>
The same approach is required for addresses used in <IMG SRC=...> and
<A HREF=...>.
4.4.2
If a servlet uses the forward method of RequestDispatcher, it cannot actually send any
output to the clientit must leave that entirely to the destination page. If the servlet
wants to generate some of the content itself but use a JSP page or static HTML
86
document for other parts of the result, the servlet can use the include method of
RequestDispatcher instead. The process is very similar to that for forwarding requests:
Call the getRequestDispatcher method of ServletContext with an address relative to
the server root, then call include with the HttpServletRequest and
HttpServletResponse.
The two differences when include is used are that you can send content to the browser
before making the call and that control is returned to the servlet after the include call
finishes. Although the included pages (servlets, JSP pages, or even static HTML) can
send output to the client, they should not try to set HTTP response headers. Here is an
example:
response.setContentType(text/html);
PrintWriter out = response.getWriter();
out.println(...);
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(/path/resource);
dispatcher.include(request, response);
out.println(...);
The include method has many of the same features as the forward method. If the
original method uses POST, so does the forwarded request. Whatever request data
was associated with the original request is also associated with the auxiliary request,
and you can add new parameters (in version 2.2 only) by appending them to the URL
supplied to getRequestDispatcher. Version 2.2 also supports the ability to get a
RequestDispatcher by name (getNamedDispatcher) or by using a relative URL (use
the getRequestDispatcher method of the HttpServletRequest). However, include does
one thing that forward does not: it automatically sets up attributes in the HttpServletRequest object that describe the original request path in case, the included
servlet or JSP page needs that information. These attributes, available to the included
resource by calling getAttribute on the Http-ServletRequest, are listed below:
javax.servlet.include.request_uri
javax.servlet.include.context_path
javax.servlet.include.servlet_path
javax.servlet.include.path_info
javax.servlet.include.query_string
Note that this type of file inclusion is not the same as the nonstandard servlet chaining
supported as an extension by several early servlet engines. With servlet chaining, each
servlet in a series of requests can see (and modify) the output of the servlet before it.
With the include method of RequestDispatcher, the included resource cannot see the
output generated by the original servlet. In fact, there is no standard construct in the
servlet specification that reproduces the behaviour of servlet chaining.
Also note that this type of file inclusion differs from that supported by the JSP include
directive. There, the actual source code of JSP files was included in the page by use of
the include directive, whereas the include method of RequestDispatcher just includes
the result of the specified resource. On the other hand, the jsp:include action has
behavior similar to that of the include method, except that jsp:include is available only
from JSP pages, not from servlets.
87
Servlets and
JSP Programming
4.4.3
The most common request forwarding scenario is that the request first comes to a
servlet and the servlet forwards the request to a JSP page. The reason is a servlet
usually handles the original request is that checking request parameters and setting up
beans requires a lot of programming, and it is more convenient to do this
programming in a servlet than in a JSP document. The reason that the destination page
is usually a JSP document is that JSP simplifies the process of creating the HTML
content.
However, just because this is the usual approach doesnt mean that it is the only way
of doing things. It is certainly possible for the destination page to be a servlet.
Similarly, it is quite possible for a JSP page to forward requests elsewhere. For
example, a request might go to a JSP page that normally presents results of a certain
type and that forwards the request elsewhere only when it receives unexpected values.
Sending requests to servlets instead of JSP pages requires no changes whatsoever in
the use of the RequestDispatcher. However, there is special syntactic support for
forwarding requests from JSP pages. In JSP, the jsp:forward action is simpler and
easier to use than wrapping up Request-Dispatcher code in a scriptlet. This action
takes the following form:
<jsp:forward page= Relative URL />
The page attribute is allowed to contain JSP expressions so that the destination can be
computed at request time.
For example, the following sends about half the visitors to
http://host/examples/page1.jsp and the others to http://host/examples/page2.jsp.
<%
String destination;
if (Math.random() > 0.5) {
destination = /examples/page1.jsp;
}
else {
destination = /examples/page2.jsp;
}
%>
<jsp:forward page= <%= destination %> />
2)
88
Codebase
Archive
Iepluginurl
Nspluginurl
3)
a) ServletContext, getRequestDispatcher
b) HttpServletRequest, getRequestDispatcher
c) getRequestDispatcher, HttpServletRequest
d) getRequestDispatcher, ServletContext
Explain following questions in brief:
4)
4.5 SUMMARY
In this unit, we first studied about database handling in JSP. In this topic we saw that
to communicate with a database through JSP, first that database is needed to be
registered on your system. Then JSP makes a connection with the database. For this
purpose DriverManager.getConnection method is used. This method connects the
program to the database identified by the data source by creating a connection object.
This object is used to make SQL queries. For making SQL queries, a statement object
is used. This statement object is created by using connection objects createStatement
( ) method. Finally statement object's executeUpdate method is used to execute the
insert and delete query and executeQuery method is used to execute the SQL select
query.
Next, we studied about how to include files and applets in JSP documents. In this, we
studied that JSP has three main capabilities for including external pieces into a JSP
document. These are:
Finally we studied about integrating servlet and JSP. The key to let servlets forward
requests or include external content is to use a requestDispatcher. This
RequestDispatcher can be obtained by calling the getRequestDispatcher method of
ServletContext, supplying a URL relative to the server root. But if you want to
forward the request from JSP, jsp:forward action is used.
4.6 SOLUTIONS/ANSWERS
Check Your Progress 1
1)
DriverManager.getConnection
2)
3)
4)
ResultSet
89
Servlets and
JSP Programming
2)
3)
4)
For example,
<APPLET CODE=: MyApplet.class WIDTH=475 HEIGHT=350>
<B>Error: this example requires Java.</B>
</APPLET>
can be replaced with
<jsp:plugin type= applet code= MyApplet.class width= 475 height= 350>
<jsp:fallback>
<B>Error: this example requires Java.</B>
</jsp:fallback>
</jsp:plugin>
90