Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
A servlet is a JavaTM component that can be plugged into a Java-enabled web server to
provide custom services. These services can include:
• New features
• Runtime changes to content
• Runtime changes to presentation
• New standard protocols (such as FTP)
• New custom protocols
• Package javax.servlet
• Package javax.servlet.http
Servlets are a powerful addition to the Java environment. They are fast, safe, reliable,
and 100% pure Java. Because servlets plug into an existing server, they leverage a lot
of existing code and technology. The server handles the network connections, protocol
negotiation, class loading, and more; all of this work does not need to be replicated!
And, because servlets are located at the middle tier, they are positioned to add a lot of
value and flexibility to a system. In this course you will learn about the Servlet API and
you will get a brief tour of the types of features servlets can implement.
Because of their power and flexibility, servlets can play a significant role in a system
architecture. They can perform the application processing assigned to the middle tier, act as
a proxy for a client, and even augment the features of the middle tier by adding support for
new protocols or other features. A middle tier acts as the application server in so called three-
tier client/server systems, positioning itself between a lightweight client like a web browser
and a data source.
Middle-Tier Process
Page 1 of 159
In many systems a middle tier serves as a link between clients and back-end services. By
using a middle tier a lot of processing can be off-loaded from both clients (making them
lighter and faster) and servers (allowing them to focus on their mission). One advantage of
middle tier processing is simply connection management. A set of servlets could handle
connections with hundreds of clients, if not thousands, while recycling a pool of expensive
connections to database servers.
Proxy Servers
When used to support applets, servlets can act as their proxies. This can be important
because Java security allows applets only to make connections back to the server from
which they were loaded.
If an applet needs to connect to a database server located on a different machine, a servlet
can make this connection on behalf of the applet.
Protocol Support
The Servlet API provides a tight link between a server and servlets. This allows servlets to
add new protocol support to a server. (You will see how HTTP support is provided for you in
the API packages.) Essentially, any protocol that follows a request/response computing
model can be implemented by a servlet. This could include:
• SMTP
• POP
• FTP
Servlet support is currently available in several web servers, and will probably start
appearing in other types of application servers in the near future. You will use a web server to
host the servlets in this class and only deal with the HTTP protocol.
Because HTTP is one of the most common protocols, and because HTML can provide such
a rich presentation of information, servlets probably contribute the most to building HTTP
based systems.
HTML Support
HTML can provide a rich presentation of information because of its flexibility and the range of
content that it can support. Servlets can play a role in creating HTML content. In fact, servlet
support for HTML is so common, the javax.servlet.http package is dedicated to supporting
HTTP protocol and HTML generation.
Complex web sites often need to provide HTML pages that are tailored for each visitor, or
even for each hit. Servlets can be written to process HTML pages and customize them as
Page 2 of 159
they are sent to a client. This can be as simple as on the fly substitutions or it can be as
complex as compiling a grammar-based description of a page and generating custom HTML.
Some web servers, such as the Java Web ServerTM (JWS), allow servlet tags to be
embedded directly into HTML files. When the server encounters such a tag, it calls the
servlet while it is sending the HTML file to the client. This allows a servlet to insert its
contribution directly into the outgoing HTML stream.
Server-Side Includes
Another example is on the fly tag processing known as server-side includes (SSI). With SSI,
an HTML page can contain special commands that are processed each time a page is
requested. Usually a web server requires HTML files that incorporate SSI to use a unique
extension, such as .shtml. As an example, if an HTML page (with an .shtml extension)
includes the following: <!--#include virtual="/includes/page.html"-->
it would be detected by the web server as a request to perform an inline file include. While
server side includes are supported by most web servers, the SSI tags are not standardized.
Servlets are a great way to add server side include processing to a web server. With more
and more web servers supporting servlets, it would be possible to write a standard SSI
processing servlet and use it on different web servers.
An HTTP servlet is a direct replacement for Common Gateway Interface (CGI) scripts. HTTP
servlets are accessed by the user entering a URL in a browser or as the target of an HTML
form action. For example, if a user enters the following URL into a browser address field, the
browser requests a servlet to send an HTML page with the current time:
http://localhost/servlet/DateTimeServlet The DateTimeServlet responds to this request by
sending an HTML page to the browser.
Note that these servlets are not restricted to generating web pages; they can perform any
other function, such as storing and fetching database information, or opening a socket to
another machine.
Installing Servlets
Servlets are not run in the same sense as applets and applications. Servlets provide
functionality that extends a server. In order to test a servlet, two steps are required:
There are many web servers that support servlets. It is beyond the scope of this course to
cover the different ways to install servlets in each server. This course examines the JSDK's
servletrunner utility and the JWS.
Page 3 of 159
Temporary versus Permanent Servlets
Servlets can be started and stopped for each client request, or they can be started as the
web server is started and kept alive until the server is shut down. Temporary servlets are
loaded on demand and offer a good way to conserve resources in the server for less-used
functions.
Permanent servlets are loaded when the server is started, and live until the server is
shutdown. Servlets are installed as permanent extensions to a server when their start-up
costs are very high (such as establishing a connection with a DBMS), when they offer
permanent server-side functionality (such as an RMI service), or when they must respond as
fast as possible to client requests.
Because servlets can be loaded when a web server starts, they can use this auto-loading
mechanism to provide easier loading of server-side Java programs. These programs can
then provide functionality that is totally unique and independent of the web server. For
example, a servlet could provide R-based services (rlogin, rsh, ...) through TCP/IP ports
while using the servlet request/response protocol to present and process HTML pages used
to manage the servlet.
Using servletrunner
For both JDK 1.1 and the Java 2 platform, you need to install the Java Servlet Development
Kit (JSDK). To use servletrunner, make sure your PATH environment variable points to its
directory. For the JSDK 2.0 installed with all default options, that location is: c:\jsdk2.0\bin on
a Windows platform.
To make sure that servletrunner has access to the Java servlet packages, check that your
CLASSPATH environment variable is pointing to the correct JAR file, c:\jsdk2.0\lib\jsdk.jar on
a Windows platform. With the Java 2 platform, instead of modifying the CLASSPATH, it is
easier to just copy the JAR file to the ext directory under the Java runtine environment. This
treats the servlet packages as standard extensions.
With the environment set up, run the servletrunner program from the command line. The
parameters are:
Page 4 of 159
The most common way to run this utility is to move to the directory that contains your servlets
and run servletrunner from that location. However, that doesn't automatically configure the
tool to load the servlets from the current directory.
Magercise
Sun's Java Web Server (JWS) is a full featured product. For servlet developers, a nice
feature is its ability to detect when a servlet has been updated. It detects when new class
files have been copied to the appropriate servlet directory and, if necessary, automatically
reloads any running servlets.
The JWS can be installed as a service under Windows NT. While this makes it convenient for
running a production server, it is not recommended for servlet development work. Under
Windows 95, there are no OS services, so the command line start-up is your only option.
To run JWS from the c:\JavaWebServer1.1\bin directory, type in the httpd command. This
starts the server in a console window. No further display is shown in the console unless a
servlet executes a System.out.println() statement.
To shut down the JWS, press <Control>+C in the command window. The server prints a
message to the console when it has finished shutting down.
Magercise
Servlet API
The Java Servlet API defines the interface between servlets and servers. This API is
packaged as a standard extension to the JDK under javax:
• Package javax.servlet
• Package javax.servlet.http
Page 5 of 159
The Servlet Life Cycle
Servlets run on the web server platform as part of the same process as the web server itself.
The web server is responsible for initializing, invoking, and destroying each servlet instance.
• init()
• service()
• destroy()
• getServletConfig()
• getServletInfo()
You may notice a similarity between this interface and that of Java applets. This is by design!
Servlets are to web servers what applets are to web browsers.An applet runs in a web
browser, performing actions it requests through a specific interface. A servlet does the same,
running in the web server.
When a servlet is first loaded, its init() method is invoked. This allows the servlet to per form
any setup processing such as opening files or establishing connections to their servers. If a
servlet has been permanently installed in a server, it loads when the server starts to run.
Otherwise, the server activates a servlet when it receives the first client request for the
services provided by the servlet.
The init() method is guaranteed to finish before any other calls are made to the servlet--such
as a call to the service() method. Note that init() will only be called once; it will not be called
again unless the servlet has been unloaded and then reloaded by the server.
The init() method takes one argument, a reference to a ServletConfig object which provides
initialization arguments for the servlet. This object has a method getServletContext() that
returns a ServletContext object containing information about the servlet's environment (see
the discussion on Servlet Initialization Context below).
The service() method is the heart of the servlet. Each request message from a client results
in a single call to the servlet's service() method. The service() method reads the request and
produces the response message from its two parameters:
• A ServletRequest object with data from the client. The data consists of name/value
pairs of parameters and an InputStream. Several methods are provided that return the
client's parameter information. The InputStream from the client can be obtained via
the getInputStream() method. This method returns a ServletInputStream, which can
be used to get additional data from the client. If you are interested in processing
Page 6 of 159
character-level data instead of byte-level data, you can get a BufferedReader instead
with getReader().
• A ServletResponse represents the servlet's reply back to the client. When preparing a
response, the method setContentType() is called first to set the MIME type of the
reply. Next, the method getOutputStream() or getWriter() can be used to obtain a
ServletOutputStream or PrintWriter, respectively, to send data back to the client.
As you can see, there are two ways for a client to send information to a servlet. The first is to
send parameter values and the second is to send information via the InputStream (or
Reader). Parameter values can be embedded into a URL. How this is done is discussed
below. How the parameter values are read by the servlet is discussed later.
The service() method's job is conceptually simple--it creates a response for each client
request sent to it from the host server. However, it is important to realize that there can be
multiple service requests being processed at once. If your service method requires any
outside resources, such as files, databases, or some external data, you must ensure that
resource access is thread-safe. Making your servlets thread-safe is discussed in a later
section of this course.
The destroy() method is called to allow your servlet to clean up any resources (such as open
files or database connections) before the servlet is unloaded. If you do not require any clean-
up operations, this can be an empty method.
The server waits to call the destroy() method until either all service calls are complete, or a
certain amount of time has passed. This means that the destroy() method can be called while
some longer-running service() methods are still running. It is important that you write your
destroy() method to avoid closing any necessary resources until all service() calls have
completed.
Sample Servlet
The code below implements a simple servlet that returns a static HTML page to a browser.
This example fully implements the Servlet interface.
import java.io.*;
import javax.servlet.*;
public SampleServlet implements Servlet {
private ServletConfig config;
Page 7 of 159
return "A Simple Servlet";
}
Servlet Context
A servlet lives and dies within the bounds of the server process. To understand its operating
environment, a servlet can get information about its environment at different times. Servlet
initialization information is available during servlet start-up; information about the hosting
server is available at any time; and each service request can contain specific contextual
information.
Initialization information is passed to the servlet via the ServletConfig parameter of the init()
method. Each web server provides its own way to pass initialization information to a servlet.
With the JWS, if a servlet class DatePrintServlet takes an initialization argument timezone,
you would define the following properties in a servlets.properties file:
servlet.dateprinter.code=DatePrinterServlet
servlet.dateprinter.timezone=PST
or this information could be supplied through a GUI administration tool.
The timezone information would be accessed by the servlet with the following code:
String timezone;
public void init(ServletConfig config) {
timeZone = config.getInitParameter("timezone");
}
Page 8 of 159
Server context information is available at any time through the ServletContext object. A
servlet can obtain this object by calling the getServletContext() method on the ServletConfig
object. Remember that this was passed to the servlet during the initialization phase. A well
written init() method saves the reference in a private variable.
The ServletContext interface defines several methods. These are outlined below.
The following example code shows how a servlet uses the host server to write a message to
a servlet log when it initializes:
Each service request can contain information in the form of name/value parameter pairs, as
a ServletInputStream, or a BufferedReader. This information is available from the
ServletRequest object that is passed to the service() method.
BufferedReader reader;
String param1;
String param2;
public void service (
ServletRequest req,
ServletResponse res) {
reader = req.getReader();
Page 9 of 159
param1 = req.getParameter("First");
param2 = req.getParameter("Second");
}
There are additional pieces of information available to the servlet through ServletRequest.
These are shown in the following table.
The following Magercise shows you how to extract parameters from a service request.
Magercise
Utility Classes
There are several utilities provided in the Servlet API. The first is the interface
javax.servlet.SingleThreadModel that can make it easier to write simple servlets. If a servlet
implements this marker interface, the hosting server knows that it should never call the
servlet's service() method while it is processing a request. That is, the server processes all
service requests within a single thread.
While this makes it easier to write a servlet, this can impede performance. A full discussion of
this issue is located later in this course.
Two exception classes are included in the Servlet API. The exception
javax.servlet.ServletException can be used when there is a general failure in the servlet. This
notifies the hosting server that there is a problem.
Page 10 of 159
The exception javax.servlet.UnavailableException indicates that a servlet is unavailable.
Servlets can report this exception at any time. There are two types of unavailability:
• Permanent. The servlet is unable to function until an administrator takes some action.
In this state, a servlet should write a log entry with a problem report and possible
resolutions.
• Temporary. The servlet encountered a (potentially) temporary problem, such as a full
disk, failed server, etc. The problem can correct itself with time or may require
operator intervention.
HTTP Support
Servlets that use the HTTP protocol are very common. It should not be a surprise that there
is specific help for servlet developers who write them. Support for handling the HTTP
protocol is provided in the package javax.servlet.http. Before looking at this package, take a
look at the HTTP protocol itself.
HTTP stands for the HyperText Transfer Protocol. It defines a protocol used by web browsers
and servers to communicate with each other. The protocol defines a set of text-based
request messages called HTTP methods. (Note: The HTTP specification calls these HTTP
methods; do not confuse this term with Java methods. Think of HTTP methods as messages
requesting a certain type of response). The HTTP methods include:
• GET
• HEAD
• POST
• PUT
• DELETE
• TRACE
• CONNECT
• OPTIONS
For this course, you will only need to look at only three of these methods: GET, HEAD, and
POST.
The HTTP GET method requests information from a web server. This information could be a
file, output from a device on the server, or output from a program (such as a servlet or CGI
script).
For example, the following HTTP GET message is requesting the home page from the
MageLang web site:
Page 11 of 159
GET / HTTP/1.1
Connection: Keep-Alive
User-Agent: Mozilla/4.0 (
compatible;
MSIE 4.01;
Windows NT)
Host: www.magelang.com
Accept: image/gif, image/x-xbitmap,
image/jpeg, image/pjpeg
On most web servers, servlets are accessed via URLs that start with /servlet/. The following
HTTP GET method is requesting the servlet MyServlet on the host www.magelang.com:
GET /servlet/MyServlet?name=Scott&
company=MageLang%20Institute HTTP/1.1
Connection: Keep-Alive
User-Agent: Mozilla/4.0 (
compatible;
MSIE 4.01;
Windows NT)
Host: www.magelang.com
Accept: image/gif, image/x-xbitmap,
image/jpeg, image/pjpeg
The URL in this GET request invokes the servlet called MyServlet and contains two
parameters, name and company. Each parameter is a name/value pair following the format
name=value. The parameters are specified by following the servlet name with a question
mark ('?'), with each parameter separated by an ampersand ('&').
Note the use of %20 in the company's value. A space would signal the end of the URL in the
GET request line, so it must be "URL encoded", or replaced with %20 instead. As you will
see later, servlet developers do not need to worry about this encoding as it will be
automatically decoded by the HttpServletRequest class.
HTTP GET requests have an important limitation. Most web servers limit how much data can
be passed as part of the URL name (usually a few hundred bytes.) If more data must be
passed between the client and the server, the HTTP POST method should be used instead.
It is important to note that the server's handling of a GET method is expected to be safe and
idempotent. This means that a GET method will not cause any side effects and that it can be
executed repeatedly.
When a server replies to an HTTP GET request, it sends an HTTP response message back.
The header of an HTTP response looks like the following:
Page 12 of 159
Content-length: 4435
The HTTP HEAD method is very similar to the HTTP GET method. The request looks exactly
the same as the GET request (except the word HEAD is used instead of GET), but the server
only returns the header information.
An HTTP POST request allows a client to send data to the server. This can be used for
several purposes, such as
Pay special attention to the third bullet above. The HTTP GET request passes all its
arguments as part of the URL. Many web servers have a limit to how much data they can
accept as part of the URL. The POST method passes all of its parameter data in an input
stream, removing this limit.
name=Scott&company=MageLang%20Institute
Page 13 of 159
Note the blank line--this signals the end of the POST request header and the beginning of
the extended information.
Unlike the GET method, POST is not expected to be safe nor idempotent; it can perform
modifications to data, and it is not required to be repeatable.
Now that you have been introduced to the HTTP protocol, consider how the javax.servlet.http
package helps you write HTTP servlets. The abstract class javax.servlet.http.HttpServlet
provides an implementation of the javax.servlet.Servlet interface and includes a lot of helpful
default functionality. The easiest way to write an HTTP servlet is to extend HttpServlet and
add your own custom processing.
The class HttpServlet provides an implementation of the service() method that dispatches the
HTTP messages to one of several special methods. These methods are:
• doGet()
• doHead()
• doDelete()
• doOptions()
• doPost()
• doTrace()
As shown in the following diagram, the service() method interprets each HTTP method and
determines if it is an HTTP GET, HTTP POST, HTTP HEAD, or other HTTP protocol method:
Fig…………
The class HttpServlet is actually rather intelligent. Not only does it dispatch HTTP requests, it
detects which methods are overridden in a subclass and can report back to a client on the
capabilities of the server. (Simply by overriding the doGet() method causes the class to
respond to an HTTP OPTIONS method with information that GET, HEAD, TRACE, and
OPTIONS are all supported. These capabilities are in fact all supported by the class's code).
In another example of the support HttpServlet provides, if the doGet() method is overridden,
there is an automatic response generated for the HTTP HEAD method. (Since the response
to an HTTP HEAD method is identical to an HTTP GET method--minus the body of the
message--the HttpServlet class can generate an appropriate response to an HTTP HEAD
request from the reply sent back from the doGet() method). As you might expect, if you need
more precise control, you can always override the doHead() method and provide a custom
response.
When using the HTTP support classes, you generally create a new servlet that extends
HttpServlet and overrides either doGet() or doPost(), or possibly both. Other methods can be
overridden to get more fine-grained control.
Page 14 of 159
The HTTP processing methods are passed two parameters, an HttpServletRequest object
and an HttpServletResponse object. The HttpServletRequest class has several convenience
methods to help parse the request, or you can parse it yourself by simply reading the text of
the request.
It is important to note that the handling of a GET method is expected to be safe and
idempotent.
• Handing is considered safe if it does not have any side effects for which users are
held responsible, such as charging them for the access or storing data.
• Handling is considered idempotent if it can safely be repeated. This allows a client to
repeat a GET request without penalty.
Think of it this way: GET should be "looking without touching." If you require processing that
has side effects, you should use another HTTP method, such as POST.
A servlet's doPost() method should be overridden when you need to process an HTML form
posting or to handle a large amount of data being sent by a client. HTTP POST method
handling is discussed in detail later.
HEAD requests are processed by using the doGet() method of an HttpServlet. You could
simply implement doGet() and be done with it; any document data that you write to the
response output stream will not be returned to the client. A more efficient implementation,
however, would check to see if the request was a GET or HEAD request, and if a HEAD
request, not write the data to the response output stream.
Summary
The Java Servlet API is a standard extension. This means that there is an explicit definition of
servlet interfaces, but it is not part of the Java Development Kit (JDK) 1.1 or the Java 2
platform. Instead, the servlet classes are delivered with the Java Servlet Development Kit
(JSDK) version 2.0 from Sun (http://java.sun.com/products/servlet/). This JSDK version is
intended for use with both JDK 1.1 and the Java 2 platform. There are a few significant
differences between JSDK 2.0 and JSDK 1.0. See below for details. If you are using a
version of JSDK earlier than 2.0, it is recommended that you upgrade to JSDK 2.0.
Page 15 of 159
This is passed to the servlet when the web server calls its init()
method. Note that the servlet should save the reference to the
ServletConfig object, and define a getServletConfig() method to return
it when asked. This interface defines how to get the initialization
parameters for the servlet and the context under which the servlet is
running.
An interface that describes how a servlet can get information about
ServletContext the server in which it is running. It can be retrieved via the
getServletContext() method of the ServletConfig object.
An interface that describes how to get information about a client
ServletRequest
request.
ServletResponse An interface that describes how to pass information back to the client.
A base servlet implementation. It takes care of saving the
ServletConfig object reference, and provides several methods that
GenericServlet
delegate their functionality to the ServletConfig object. It also provides
a dummy implementation for init() and destroy().
A subclass of InputStream used for reading the data part of a client's
ServletInputStream
request. It adds a readLine() method for convenience.
ServletOutputStream An OutputStream to which responses for the client are written.
ServletException Should be thrown when a servlet problem is encountered.
UnavailableException Should be thrown when the servlet is unavailable for some reason.
Servlet Examples
Page 16 of 159
Sometimes a web page needs only a small piece of information that is customized at
runtime. The remainder of a page can be static information. To substitute only small amounts
of information, some web servers support a concept known as server-side includes, or SSI.
If it supports SSI, the web server designates a special file extension (usually .shtml) which
tells the server that it should look for SSI tags in the requested file. The JWS defines a
special SSI tag called the <servlet> tag, for example:
<servlet code="DatePrintServlet">
<param name=timezone value=pst>
</servlet>
This tag causes the invoking of a servlet named DatePrintServlet to generate some in-line
content.
SSI and servlets allow an HTML page designer to write a skeleton for a page, using servlets
to fill in sections of it, rather than require the servlet to generate the entire page. This is very
useful for features like page-hit counters and other small pieces of functionality.
The DatePrintServlet servlet works just like a regular servlet except that it is designed to
provide a very small response and not a complete HTML page. The output MIME type gets
set to "text/plain" and not "text/html".
Keep in mind that the syntax of server-side includes, if they are even supported, may vary
greatly from one web server to another.
In the following Magercise you create the DatePrintServlet and see how to use it in an HTML
page.
Magercise
HTTP POST method processing differs from HTTP GET method processing in several ways.
First, because POST is expected to modify data on the server, there can be a need to safely
handle updates coming from multiple clients at the same time. Second, because the size of
the information stream sent by the client can be very large, the doPost() method must open
an InputStream (or Reader) from the client to get any of the information. HTTP POST does
not support sending parameters encoded inside of the URL as does the HTTP GET method.
The problem of supporting simultaneous updates from multiple clients has been solved by
database systems (DBMSs); unfortunately the HTTP protocol does not work well with
database systems. This is because DBMSs need to maintain a persistent connection
between a client and the DBMS to determine which client is trying to update the data.
The HTTP protocol does not support this type of a connection as it is a message based,
stateless protocol. Solving this problem is not easy and never elegant! Fortunately, the
Servlet API defines a means to track client/server sessions. This is covered in the
Page 17 of 159
Maintaining Session Information section later in this course. Without session management
tracking, one can resort to several different strategies. They all involve writing data to the
client in hidden fields which is then sent back to the server. The simplest way to handle
updates is to use an optimistic locking scheme based on date/time stamps. One can use a
single date/time stamp for a whole form of data, or one could use separate date/time stamps
for each "row" of information.
Once the update strategy has been selected, capturing the data sent to the server via an
HTTP POST method is straightforward. Information from the HTML form is sent as a series
of parameters (name/value pairs) in the InputStream object. The HttpUtils class contains a
method parsePostData() that accepts the raw InputStream from the client and return a
Hashtable with the parameter information already processed. A really nice feature is that if a
parameter of a given name has multiple values (such is the case for a column name with
multiple rows), then this information can be retrieved from the Hashtable as an array of type
String.
In the following Magercise, you will be given skeleton code that implements a pair of servlets
that display data in a browser as an editable HTML form. The structure of the data is kept
separate from the actual data. This makes it easy to modify this code to run against arbitrary
tables from a JDBC-connected database.
Magercise
Using Cookies
For those unfamiliar with cookies, a cookie is a named piece of data maintained by a
browser, normally for session management. Since HTTP connections are stateless, you can
use a cookie to store persistent information accross multiple HTTP connections. The Cookie
class is where all the "magic" is done. The HttpSession class, described next, is actually
easier to use. However, it doesn't support retaining the information across multiple browser
sessions.
To save cookie information you need to create a Cookie, set the content type of the
HttpServletResponse response, add the cookie to the response, and then send the output.
You must add the cookie after setting the content type, but before sending the output, as the
cookie is sent back as part of the HTTP response header.
It is necessary to remember that all cookie data are strings. You must convert information like
int data to a String object. By default, the cookie lives for the life of the browser session. To
enable a cookie to live longer, you must call the setMaxAge(interval) method. When positive,
Page 18 of 159
this allows you to set the number of seconds a cookie exists. A negative setting is the default
and destroys the cookie when the browser exits. A zero setting immediately deletes the
cookie.
Retrieving cookie data is a little awkward. You cannot ask for the cookie with a specific key.
You must ask for all cookies and find the specific one you are interested in. And, it is possible
that multiple cookies could have the same name, so just finding the first setting is not always
sufficient. The following code finds the setting of a single-valued cookie:
int sum = 0;
Cookie theCookie = null;
Cookie cookies[] = request.getCookies();
if (cookies != null) {
for(int i=0, n=cookies.length; i < n; i++) {
theCookie = cookies[i];
if (theCookie.getName().equals(SUM_KEY)) {
try {
sum = Integer.parseInt(theCookie.getValue());
} catch (NumberFormatException ignored) {
sum = 0;
}
break;
}
}
}
A session is a continuous connection from the same browser over a fixed period of time.
(This time is usually configurable from the web server. For the JWS, the default is 30
minutes.) Through the implicit use of browser cookies, HTTP servlets allow you to maintain
session information with the HttpSession class. The HttpServletRequest provides the current
session with the getSession(boolean) method. If the boolean parameter is true, a new
session will be created when a new session is detected. This is, normally, the desired
behavior. In the event the parameter is false, then the method returns null if a new session is
detected.
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
// ...
Once you have access to an HttpSession, you can maintain a collection of key-value-paired
information, for storing any sort of session-specific data. You automatically have access to
the creation time of the session with getCreationTime() and the last accessed time with
getLastAccessedTime(), which describes the time the last servlet request was sent for this
session.
Page 19 of 159
To store session-specific information, you use the putValue(key, value) method. To retrieve
the information, you ask the session with getValue(key). The following example demonstrates
this, by continually summing up the integer value of the Addend parameter. In the event the
value is not an integer, the number of errors are also counted.
As with all servlets, once you've performed the necessary operations, you need to generate
some output. If you are using sessions, it is necessary to request the session with
HttpServletRequest.getSession() before generating any output.
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>" +
"<head><title>Session Information</title></head>" +
"<body bgcolor=\"#FFFFFF\">" +
"<h1>Session Information</h1><table>");
out.println ("<tr><td>Identifier</td>");
out.println ("<td>" + session.getId() + "</td></tr>");
out.println ("<tr><td>Created</td>");
out.println ("<td>" + new Date(
session.getCreationTime()) + "</td></tr>");
out.println ("<tr><td>Last Accessed</td>");
out.println ("<td>" + new Date(
session.getLastAccessedTime()) + "</td></tr>");
out.println ("<tr><td>New Session?</td>");
Page 20 of 159
out.println ("<td>" + session.isNew() + "</td></tr>");
String names[] = session.getValueNames();
for (int i=0, n=names.length; i<n; i++) {
out.println ("<tr><td>" + names[i] + "</td>");
out.println ("<td>" + session.getValue (names[i])
+ "</td></tr>");
}
out.println("</table></center></body></html>");
out.close();
The complete code example shown above is available for testing. One thing not
demonstrated in the example is the ability to end a session, where the next call to
request.getSession(true) returns a different session. This is done with a call to invalidate().
In the event a user has browser cookies disabled, you can encode the session ID within the
HttpServletResponse by calling its encodeUrl() method.
Connecting to Databases
It is very common to have servlets connect to databases through JDBC. This allows you to
better control access to the database by only permitting the middle-tier to communicate with
the database. If your database server includes sufficient simultanious connection licenses,
you can even setup database connections once, when the servlet is initialized, and pool the
connections between all the different service requests.
The following demonstrates sharing a single Connection between all service requests. To find
out how many simultaneous connections the driver supports, you can ask its
DatabaseMetaData and then create a pool of Connection objects to share between service
requests.
Page 21 of 159
• "Mon, 01 Jan 1990 00:00:00 GMT");
•
• Statement stmt = null;
• ResultSet result = null;
•
• try {
• // Submit query
• stmt = con.createStatement();
• result = stmt.executeQuery (
• "SELECT programmer, cups " +
• "FROM JoltData ORDER BY cups DESC;");
•
• // Create output
• PrintWriter out = response.getWriter();
• while(result.next()) {
• // Generate output from ResultSet
• }
• } finally {
• if (result != null) {
• result.close();
• }
• if (stmt != null) {
• stmt.close();
• }
• }
• out.flush();
• out.close();
• }
• In the destroy() method disconnect from the database.
• public void destroy() {
• super.destroy();
• con.close();
• }
It is not good practice to leave a database connection permanently open, so this servlet
should not be installed as a permanent servlet. Having it as a temporary servlet that closes
itself down after a predefined period of inactivity allows the sharing of the database
connection with requests that coincide, reducing the cost of each request.
You can also save some information in the HttpSession to possible page through the result
set.
Security Issues
As with Java applets, Java servlets have security issues to worry about, too.
Page 22 of 159
A servlet can originate from several sources. A webmaster may have written it; a user may
have written it; it may have been bought as part of a third-party package or downloaded from
another web site.
Based on the source of the servlet, a certain level of trust should be associated with that
servlet. Some web servers provide a means to associate different levels of trust with different
servlets. This concept is similar to how web browsers control applets, and is known as
"sandboxing".
A servlet sandbox is an area where servlets are given restricted authority on the server. They
may not have access to the file system or network, or they may have been granted a more
trusted status. It is up to the web server administrator to decide which servlets are granted
this status. Note that a fully trusted servlet has full access to the server's file system and
networking capabilities. It could even perform a System.exit(), stopping the web server...
Many web servers allow you to restrict access to certain web pages and servlets via access
control lists (ACLs). An ACL is a list of users who are allowed to perform a specific function in
the server. The list specifies:
Each web server has its own means of specifying an ACL, but in general, a list of users is
registered on the server, and those user names are used in an ACL. Some servers also allow
you to add users to logical groups, so you can grant access to a group of users without
specifying all of them explicitly in the ACL.
ACLs are extremely important, as some servlets can present or modify sensitive data and
should be tightly controlled, while others only present public knowledge and do not need to
be controlled.
Threading Issues
A web server can call a servlet's service() method for several requests at once. This brings
up the issue of thread safety in servlets.
But first consider what you do not need to worry about: a servlet's init() method. The init()
method will only be called once for the duration of the time that a servlet is loaded. The web
server calls init() when loading, and will not call it again unless the servlet has been unloaded
and reloaded. In addition, the service() method or destroy() method will not be called until the
init() method has completed its processing.
Things get more interesting when you consider the service() method. The service() method
can be called by the web server for multiple clients at the same time. (With the JSDK 2.0,
you can tag a servlet with the SingleThreadModel interface. This results in each call to
service() being handled serially. Shared resources, such as files and databases, can still
have concurrency issues to handle.)
Page 23 of 159
If your service() method uses outside resources, such as instance data from the servlet
object, files, or databases, you need to carefully examine what might happen if multiple calls
are made to service() at the same time. For example, suppose you had defined a counter in
your servlet class that keeps track of how many service() method invocations are currently
running:
Next, suppose that your service() method contained the following code:
counter = counter - 1;
What would happen if two service() methods were running at the same time, and both
executed line 1 before either executed line 2? Both would have the same value for
myNumber, and the counter would not be properly updated.
For this situation, the answer might be to synchronize the access to the counter variable:
synchronized(this) {
myNumber = counter + 1;
counter = myNumber;
}
synchronized(this) {
counter = counter - 1 ;
}
This ensures that the counter access code is executed only one thread at a time.
There are several issues that can arise with multi-threaded execution, such as deadlocks
and coordinated interactions. There are several good sources of information on threads,
including Doug Lea's book Concurrent Programming in Java.
The Java Servlet Development Kit (JSDK) provides servlet support for JDK 1.1 and Java 2
platform developers.
JSDK 1.0 was the initial release of the development kit. Everything worked fine, but there
were some minor areas that needed improvement. The JSDK 2.0 release incorporates these
improvements. The changes between JSDK 1.0 and JSDK 2.0 are primarily the addition of
new classes. In addition, there is also one deprecated methods. Because some web servers
Page 24 of 159
still provide servlet support that complies with the JSDK 1.0 API definitions, you need to be
careful about upgrading to the new JSDK.
• The interface SingleThreadModel indicates to the server that only one thread can call
the service() method at a time.
• Reader and Writer access from ServletRequest and ServletResponse
• Several HTTP session classes that can be used to provide state information that
persists over multiple connections and requests between an HTTP client and an HTTP
server.
• Cookie support is now part of the standard servlet extension.
• Several new HTTP response constants have been added to HttpServletResponse
• Delegation of DELETE, OPTIONS, PUT, and TRACE to appropriate methods in
HttpServlet
Page 25 of 159
Class javax.servlet.ServletInputStream
javax.servlet.ServletInputStream
Methods.
readLine
public int readLine(byte b[],
int off,
int len) throws IOException
Starting at the specified offset, reads into the given array of bytes until all requested
bytes have been read or a '\n' is encountered, in which case the '\n' is read into the
array as well.
Parameters:
b - the buffer into which the data is read
off - the start offset of the data
len - the maximum number of bytes to read
Returns:
the actual number of bytes read, or -1 if the end of the stream is reached
Throws: IOException
if an I/O error has occurred
By now, everyone has heard of Java applets. But every once in a while someone mentions
Java servlets. This article answers the question "What is a Java servlet?". It also compares
servlets to CGI and Java applets. More detailed information can be found at the Java Servlet
Home Page.
Page 26 of 159
Java Servlets
A Java servlet is a Java program that executes on the Web or HTTP server in response to
requests from a Web browser. The Web server software uses Java Virtual Machine to run the
servlet and generate an HTML page. The servlet takes input from a HTML page containing
HTML input tags, processes it, and returns a HTML page with the results.
Java Servlets can be thought of as CGI programs in some respects. Both servlets and CGI
execute on the server in response to HTML input. Thus both are limited to HTML and
JavaScript's capabilities. However, Java servlets are much more powerful that CGI programs
for these reasons.
• Servlets execute as a thread within the Web server. Threaded execution avoids the
overhead of creating separate processes for each CGI call.
• Servlets may retain data between executions. For example, a servlet could retain a
network connection or access counter between executions. However, cookies or
similar solutions are still needed to retain data about an individual browser that
accesses the servlet.
• A servlet may connect to any computer on the network or write files on the server.
While CGI programs may also do these things Java servlets allow a platform
independent implementation.
• A servlet can use business objects that are part of a larger distributed system. This is
difficult or impossible to accomplish with CGI.
To a Java servlet version in action, click here. A new window will appear with the servlet.
Java Applets
A Java Applet is a Java program that executes on the Web browser. Java Applets are limited
to certain operations on the browser. Java applets can also use JDBC connection or
distributed objects. The Java applet allows more complex user interface options than HTML
combined with either CGI or Java servlets. However, the Java applet requires a Java-
enabled Web browser. Applets have several advantages over HTML.
• Applets allow local validation of data entered by the user. Local validation of data is
possible using HTML combined with JavaScript but variances in JavaScript
implementations make JavaScript difficult to generally use.
• An applet can use the database to perform list of values lookups and data validation.
HTML (even if combined with JavaScript) can not do that without invoking a CGI or
servlet program and drawing a new HTML page.
• Once an applet is downloaded, the amount of data transferred between the Web
browser and the server is reduced. HTML requires that the server transfer the
presentation of the data (the HTML tags) along with the data itself. The HTML tags
can easily be 1/4 to 1/2 of the data transferred from the server to the client.
• Applets allow the designer to use complex GUI widgets such as grids, spin controls,
and scrollbars. These widgets are not available to HTML.
Page 27 of 159
Use Session Beans for Application logic
Use Session Beans as the only interface to the client
Expect little reuse of session beans
Use session beans to control the workflow of a group of entity beans
Use Entity Beans to develop a persistent object model (wrap all yr. JDBC code)
Use Entity Beans to enforce accuracy/integrity of your database
Insist on reuse of Entity Beans
Use Entity Beans to model domain objects with a unique identity shared by multiple clients
In general Session Beans are about a conversation with a client, and Entity Beans are about
records in the domain model.
Use entity beans for a persistant object model: eg. wrap up all your jdbc code etc. giving the
rest of your application an object-oriented interface to your data model. Session beans are for
application logic. For example, use session beans to model the layer that interfaces with your
object-model but normally should not go direct to your database. Thus a set of session beans
provide all the functionality for a particular application of which there could be several
communicating with the Entity based Object-Model. It will be session bean's EJBobjects that
communicate with the front-end GUI code (or servlets etc.). However, also be aware that entity
beans can have an object model behavior too. As always, there are no hard and fast rules.
Use Session Beans as the only interface to the client, providing a "coarse grained" facade to
the underlying model. You should use entity beans to enforce the accuracy/ integrity/
auditability of databases, not merely as an OO representation of data. Then use session
beans to run the processes that operate on the databases. This split reduces the pain of
introducing new/ changed processes because testing/ approval does not need to be so
stringent.
Insist on reuse of entity beans. They'll be hard to develop but over time they'll "define your
company".
Expect little reuse of session beans. Plan instead to discard them and create new ones quickly
by building a RAD capability around them as a means to competitiveness.
Elevate Entities to a much higher level. Entities are good candidates to model business
objects/ domain objects which have a unique identity and need to be shared by varoius clients
and be persisted over a longer time. They can also incorporate the business logic that goes on
with their responsibility. Session Beans can be used whenever a business method requires
services from two or more entities. It is a good idea to have all interfaces to the system
through Sessions beans.
Interview Questions
Servlets:
1. Servlet Life Cycle
A. The Servlet life cycle is as follows
• public void init() throws ServletException,
public void init(ServletConfig config) throws ServletException
Page 28 of 159
Executed once when the servlet is first loaded. Not called for each request. Use
getInitParameter to read initialization parameters.
• public void service(HttpServletRequest request,oid
ervice(HttpServletResponse response) throws ServletException, IOException
Called in a new thread by server for each request. Dispatches to doGet, doPost, etc.
Do not override this method!
• public void doGet(HttpServletRequest request, void
doGet(HttpServletResponse response) throws ServletException, IOException
Handles GET requests. Override to provide your behavior.
• public void doPost(HttpServletRequest request, void
oPost(HttpServletResponse response) throws ServletException, IOException
Handles POST requests. Override to provide your behavior. If you want GET and
POST to act identically, call doGet here.
• doPut, doTrace, doDelete, etc.
Handles the uncommon HTTP requests of PUT, TRACE, etc.
• public void destroy()
Called when server deletes servlet instance. Not called after each request.
• public long getLastModified(HttpServletRequest request)
Called by server when client sends conditional GET due to cached copy.
• SingleThreadModel
If this interface implemented, causes server to avoid concurrent invocations.
The init Method
The init method is called when the servlet is first created and is not called
again for each user request. So, it is used for one-time initializations, just as
with the init method of applets. The servlet can be created when a user first
invokes a URL corresponding to the servlet or when the server is first started,
depending on how you have registered the servlet with the Web server.
There are two versions of init: one that takes no arguments and one that
takes a ServletConfig object as an argument. The first version is used when
the servlet does not need to read any settings that vary from server to server.
The method definition looks like this:
public void init() throws ServletException {
// Initialization code...
}
The second version of init is used when the servlet needs to read
server-specific settings before it can complete the initialization. For example,
the servlet might need to know about database settings, password files,
server-specific performance parameters, hit count files, or serialized cookie
data from previous requests. The second version of init looks like this:
public void init(ServletConfig config) throws ServletException {
super.init(config);
// Initialization code...
}
Imp: If you write an init method that takes a ServletConfig as an argument, always call
super.init on the first line.
Page 29 of 159
etc., as appropriate. Now, if you have a servlet that needs to handle both POST and
GET requests identically, you may be tempted to override service directly as below,
rather than implementing both doGet and doPost.
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet Code
}
This is not a good idea. Instead, just have doPost call doGet (or vice
versa), as below.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet Code
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
Although this approach takes a couple of extra lines of code, it has five
advantages over directly overriding service:
1. You can add support for other services later by adding doPut, doTrace, etc.,
perhaps in a subclass. Overriding service directly precludes this possibility.
2. You can add support for modification dates by adding a getLastModified method. If
you use doGet, the standard service method uses the getLastModified method to set
Last-Modified headers and to respond properly to conditional
GET requests (those containing an If-Modified-Since header). See Section 2.8 (An
Example Using Servlet Initialization and Page Modification Dates) for an example.
3. You get automatic support for HEAD requests. The system just returns whatever
headers and status codes doGet sets, but omits the page body. HEAD is a useful
request method for custom HTTP clients. For example, link validators that check a
page for dead hypertext links often use HEAD instead of GET in order to reduce
server load.
4. You get automatic support for OPTIONS requests. If a doGet method exists, the
standard service method answers OPTIONS requests by returning an Allow header
indicating that GET, HEAD, OPTIONS, and TRACE are supported.
5. You get automatic support for TRACE requests. TRACE is a request method used
for client debugging: it just returns the HTTP request headers back to the client.
Imp: If your servlet needs to handle both GET and POST identically, have your
doPost method call doGet, or vice versa. Don’t override service directly.
Page 30 of 159
initialization parameters associated with the servlet.
IMP: What are the initialization parameters? Write some ex?
A. Remember that, although servlets read init parameters in a standard way,
developers set init parameters in a server-specific manner. Because the process of
setting init parameters is server-specific, it is a good idea to minimize the number of
separate initialization entries that have to be specified. This will limit the work you
need to do when moving servlets that use init parameters from one server to another.
If you need to read a large amount of data, I recommend that the init parameter itself
merely give the location of a parameter file, and that the real data go in that file.
Ex:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/** Example using servlet initialization. Here, the message to print and the
* number of times the message should be repeated is taken p from the init
* parameters.
*/
public class ShowMessage extends HttpServlet {
private String message;
private String defaultMessage = "No message.";
private int repeats = 1;
public void init(ServletConfig config) throws ServletException {
// Always call super.init
super.init(config);
message = config.getInitParameter("message");
if (message == null) {
message = defaultMessage;
}
try {
String repeatString = config.getInitParameter("repeats");
repeats = Integer.parseInt(repeatString);
} catch(NumberFormatException nfe) {
// NumberFormatException handles case where repeatString is null *and* //case
where it is something in an illegal format. Either way, do nothing in //catch, as
the previous value (1) for the repeats field will remain valid //because the
Integer.parseInt throws the exception *before* the value gets //assigned to
repeats.
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "The ShowMessage Servlet";
out.println(ServletUtilities.headWithTitle(title) +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=CENTER>" + title + "</H1>");
for(int i=0; i<repeats; i++) {
out.println(message + "<BR>");
Page 31 of 159
}
out.println("</BODY></HTML>");
}
}
3. Servlet Context
A. Servlets can also store persistent data in the Servlet-Context object that is
available through the getServletContext method. ServletContext has setAttribute and
getAttribute methods that let you store arbitrary data associated with specified keys.
The difference between storing data in instance variables and storing it in the Servlet-
Context is that the ServletContext is shared by all servlets in the servlet engine (or in
the Web application, if your server supports such a capability).
4. How you will create a session in a servlet? What are the various ways of
creating a session?
A. The Need for Session Tracking
HTTP is a “stateless” protocol: each time a client retrieves a Web page, it
opens a separate connection to the Web server, and the server does not automatically
maintain contextual information about a client. Even with servers
that support persistent (keep-alive) HTTP connections and keep a socket open for
multiple client requests that occur close together in time, there is no built-in support for
maintaining contextual information. This lack of context causes a number of
difficulties. For example, when clients at an on-line store add an item to their shopping
carts, how does the server know what’s already in them? Similarly, when clients
decide to proceed to checkout, how can the server determine which previously
created shopping carts are theirs?
There are three typical solutions to this problem: cookies, URL-rewriting,
and hidden form fields.
1. Typical Uses of Cookies
• Identifying a user during an e-commerce session
• Avoiding username and password
• Customizing a site
• Focusing advertising
Problems with Cookies
• It’s a privacy problem, not a security problem.
• Privacy problems include: servers can remember what you did in previous sessions;
if you give out personal information, servers can link that information to your previous
actions; servers can share cookie information through use of a cooperating third party
like doubleclick.net (by each loading image off the third-party site); poorly designed
sites could store sensitive information like credit card
numbers directly in the cookie.
General Usage
• Sending cookie to browser (standard approach):
Cookie c = new Cookie("name", "value");
c.setMaxAge(...);
// Set other attributes.
response.addCookie(c);
• Sending cookie to browser (simplified approach):
Use LongLivedCookie class (Section 8.5).
• Reading cookies from browser (standard approach):
Cookie[] cookies = response.getCookies();
Page 32 of 159
for(int i=0; i<cookies.length; i++) {
Cookie c = cookies[i];
if (c.getName().equals("someName")) {
doSomethingWith(c);
break;
}
}
• Reading cookies from browser (simplified approach):
Extract cookie or cookie value from cookie array by using
ServletUtilities.getCookie or
ServletUtilities.getCookieValue.
Cookie Methods
• getComment/setComment: gets/sets comment. Not supported in version 0 cookies
(which are what most browsers now support).
• getDomain/setDomain: lets you specify domain to which cookie applies. Current
host must be part of domain specified.
• getMaxAge/setMaxAge: gets/sets the cookie expiration time (in seconds). If you fail
to set this, cookie applies to current browsing session only. See LongLivedCookie
helper class (Section 8.5).
• getName/setName: gets/sets the cookie name. For new cookies, you supply name
to constructor, not to setName. For incoming cookie array, you use getName to find
the cookie of interest.
• getPath/setPath: gets/sets the path to which cookie applies. If unspecified, cookie
applies to URLs that are within or below directory containing current page.
• getSecure/setSecure: gets/sets flag indicating whether cookie should
apply only to SSL connections or to all connections.
• getValue/setValue: gets/sets value associated with cookie. For new cookies, you
supply value to constructor, not to setValue. For incoming cookie array, you use
getName to find the cookie of interest, then call getValue on the result.
• getVersion/setVersion: gets/sets the cookie protocol version. Version 0 is the
default; stick with that until browsers start supporting version 1.
2. Session Tracking
Looking Up Session Information: getValue
HttpSession session = request.getSession(true);
ShoppingCart cart = (ShoppingCart)session.getValue("shoppingCart");
if (cart == null) { // No cart already in session
cart = new ShoppingCart();
session.putValue("shoppingCart", cart);
}
doSomethingWith(cart);
Associating Information with a Session: putValue
HttpSession session = request.getSession(true);
session.putValue("referringPage", request.getHeader("Referer"));
ShoppingCart cart = (ShoppingCart)session.getValue("previousItems");
if (cart == null) { // No cart already in session
cart = new ShoppingCart();
session.putValue("previousItems", cart);
}
String itemID = request.getParameter("itemID");
Page 33 of 159
if (itemID != null) {
cart.addItem(Catalog.getItem(itemID));
}
HttpSession Methods
• public Object getValue(String name) [2.1]
public Object getAttribute(String name) [2.2]
Extracts a previously stored value from a session object. Returns null if no value is
associated with given name.
• public void putValue(String name, Object value) [2.1]
public void setAttribute(String name, Object value) [2.2]
Associates a value with a name. If value implements HttpSessionBindingListener, its
valueBound method is called. If previous value implements
HttpSessionBindingListener, its valueUnbound method is called.
• public void removeValue(String name) [2.1]
public void removeAttribute(String name) [2.2]
Removes any values associated with designated name. If value being removed
implements HttpSessionBindingListener, its valueUnbound method is called.
• public String[] getValueNames() [2.1]
public Enumeration getAttributeNames() [2.2]
Returns the names of all attributes in the session.
• public String getId()
Returns the unique identifier generated for each session.
• public boolean isNew()
Returns true if the client (browser) has never seen the session; false otherwise.
• public long getCreationTime()
Returns time at which session was first created (in milliseconds since 1970). To get a
value useful for printing, pass value to Date constructor or the setTimeInMillis method
of GregorianCalendar.
• public long getLastAccessedTime()
Returns time at which the session was last sent from the client.
• public int getMaxInactiveInterval()
public void setMaxInactiveInterval(int seconds)
Gets or sets the amount of time, in seconds, that a session should go without access
before being automatically invalidated. A negative value indicates that session should
never time out. Not the same as cookie expiration date.
• public void invalidate()
Invalidates the session and unbinds all objects associated with it.
3. Encoding URLs
In case servlet is using URL rewriting to implement session tracking, you
should give the system a chance to encode the URLs.
• Regular URLs
String originalURL = someRelativeOrAbsoluteURL;
String encodedURL = response.encodeURL(originalURL);
out.println("<A HREF=\"" + encodedURL + "\">...</A>");
• Redirect URLs
String originalURL = someURL; // Relative URL OK in 2.2
String encodedURL = response.encodeRedirectURL(originalURL);
response.sendRedirect(encodedURL);
Page 34 of 159
5. How will you get the Request dispatcher?
A. You obtain a RequestDispatcher by calling the getRequestDispatcher method of
ServletContext, supplying a URL relative to the server root. For example, to
obtain a RequestDispatcher associated with
http://yourhost/presentations/presentation1.jsp, you would do the following:
String url = "/presentations/presentation1.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
Page 35 of 159
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("...");
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher("/path/resource");
dispatcher.include(request, response);
out.println("...");
However, include does one thing that forward does not: it automatically sets up
attributes in the Http-ServletRequest 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
JSP
1. Difference between Servlets and JSP
A. JSP doesn’t provide any capabilities that couldn’t in principle be accomplished with a
servlet. In fact, JSP documents are automatically translated into servlets behind the
scenes. But it is more convenient to write (and to modify!) regular HTML than to have
a zillion println statements that generate the HTML. Plus, by separating the
presentation from the content, you can put different people on different tasks: your
Web page design experts can build the HTML using familiar tools and leave places for
your servlet programmers to insert the dynamic content.
Page 36 of 159
To simplify these expressions, you can use a number of predefined variables.
The most important ones are:
• request, the HttpServletRequest
• response, the HttpServletResponse
• session, the HttpSession associated with the request (unless
disabled with the session attribute of the page directive — see
Section 11.4)
• out, the PrintWriter (a buffered version called JspWriter)
used to send output to the client
Here is an example:
Your hostname: <%= request.getRemoteHost() %>
XML Syntax for Expressions :
<jsp:expression>
Java Expression
</jsp:expression>
Ex:
<BODY>
<H2>JSP Expressions</H2>
<UL>
<LI>Current time: <%= new java.util.Date() %>
<LI>Your hostname: <%= request.getRemoteHost() %>
<LI>Your session ID: <%= session.getId() %>
<LI>The <CODE>testParam</CODE> form parameter:
<%= request.getParameter("testParam") %>
</UL>
</BODY>
2. Scriptlets of the form <% code %>, which are inserted into the servlet’s
_jspService method (called by service). If you want to do something more complex
than insert a simple expression, JSP scriptlets let you insert arbitrary code into the
servlet’s _jspService method (which is called by service). Scriptlets have the following
form:
<% Java Code %>
Scriptlets have access to the same automatically defined variables as
expressions (request, response, session, out, etc.; see Section 10.5). So,
for example, if you want output to appear in the resultant page, you would
use the out variable, as in the following example.
Attached GET data: <%= request.getQueryString() %>
In general, however, scriptlets can perform a number of tasks that cannot
be accomplished with expressions alone. These tasks include setting response
headers and status codes, invoking side effects such as writing to the server
log or updating a database, or executing code that contains loops, conditionals,
or other complex constructs.
Ex:
<body>
<%
String bgColor = request.getParameter("bgColor");
boolean hasExplicitColor;
if (bgColor != null) {
hasExplicitColor = true;
Page 37 of 159
} else {
hasExplicitColor = false;
bgColor = "WHITE";
}
%>
<BODY BGCOLOR="<%= bgColor %>">
<H2 ALIGN="CENTER">Color Testing</H2>
<%
if (hasExplicitColor) {
out.println("You supplied an explicit background color of " +
bgColor + ".");
} else {
out.println("Using default background color of WHITE. " +
"Supply the bgColor request attribute to try " +
"a standard color, an RRGGBB value, or to see " +
"if your browser supports X11 color names.");
}
%>
</BODY>
3. Declarations of the form <%! code %>, which are inserted into the body of the
servlet class, outside of any existing methods. A JSP declaration lets you define
methods or fields that get inserted into the main body of the servlet class (outside of
the _jspService method that is called by service to process the request). A declaration
has the following form: <%! Java Code %> Since declarations do not generate any
output, they are normally used in conjunction with JSP expressions or scriptlets.
Ex:
<BODY>
<H1>JSP Declarations</H1>
<%! private int accessCount = 0; %>
<H2>Accesses to page since server reboot:
<%= ++accessCount %></H2>
</BODY>
Note: Check the page Comp’s-of-jsp in the same folder
Page 38 of 159
for the JSP page and takes the following form:
<%@ page extends="package.class" %>
Use this attribute with extreme caution since the server may be using a custom
superclass already.
Page 39 of 159
note that out is used almost exclusively in scriptlets, since JSP expressions are
automatically placed in the output stream and thus rarely need to refer to out explicitly.
session : This variable is the HttpSession object associated with the request. Recall
that sessions are created automatically, so this variable is bound even if there is no
incoming session reference. The one exception is if you use the session attribute of
the page directive to turn sessions off. In that case, attempts to reference the session
variable cause errors at the time the JSP page is translated into a servlet.
application : This variable is the ServletContext as obtained via
getServletConfig().getContext(). Servlets and JSP pages can store persistent data
in the ServletContext object rather than in instance variables. ServletContext has
setAttribute and getAttribute methods that let you store arbitrary data associated with
specified keys. The difference between storing data in instance variables and storing it
in the Servlet- Context is that the ServletContext is shared by all servlets in the servlet
engine (or in the Web application, if your server supports such a
capability).
config : This variable is the ServletConfig object for this page.
pageContext : JSP introduced a new class called PageContext to give a single point
of access to many of the page attributes and to provide a convenient place
to store shared data. The pageContext variable stores the value of the PageContext
object associated with the current page.
page : This variable is simply a synonym for this and is not very useful in the
Java programming language. It was created as a place holder for the time when the
scripting language could be something other than Java.
page
This variable is simply a synonym for this and is not very useful in the
Java programming language. It was created as a place holder for the
time when the scripting language could be something other than Java.
9. HTTP Headers
A. See the document Http Headers.
10. What is the difference between jsp static and dynamic include?
A. The JSP include directive is used to insert text and code into a JSP at translation
time. After the initial request is processed, the data included does not change until the
included file is changed and the server is restarted.The syntax of the include directive
is <%@ include file="relativeURLspec" %>
The file that the file attribute points to can reference a normal text HTML file or a
JSP file, which will be evaluated at translation time.
<jsp:include>
Page 40 of 159
The <jsp:include> action provides a mechanism for including additional static and
dynamic resources in the current JSP page. The syntax for this action is as follows:
<jsp:include page="urlSpec" flush="true" />
and
<jsp:include page="urlSpec" flush="true">
<jsp:param ... />
</jsp:include>
The first syntax description does a request-time inclusion, whereas the second
contains a list of param subelements that are used to argue the request for the
purpose of inclusion. Following contains the attributes and their descriptions for the
<jsp:include> action.
Attribute Definition
page This attribute represents the relative URL of the resource to be
included.
flush This attribute represents a mandatory Boolean value stating
whether or not the buffer should be flushed. Currently, true is
the only valid value for this attribute.
JDBC
1.Write a class
A.
import java.sql.*;
class Jdbc1 {
try {
class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con =DriverManger.getConnection(“jdbc:odbc:anil”,” “,” “);
Statement stmt = con.createStatement():
ResultSet rs = stmt.executeQuery(“Select * from Emp”);
While(rs.next()) {
String s = rs.getString(“Name”);
String c = rs.getString(“Empcode”):
System.out.println(s+” “+” “+c);
}
}catch(Exception c){
System.out.println(e);
}}
Page 41 of 159
table. In practice, executeUpdate is used far more often to update tables than it is to
create them because a table is created once but may be updated many times.
try {
Class.forName("myDriverClassName");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
There are actually three components, however, and to be complete, you can print
them all out. The following code fragment shows a catch block that is complete in two ways.
First, it prints out all three parts of an SQLException object: the message (a string that
describes the error), the SQL state (a string identifying the error according to the X/Open
SQLState conventions), and the vendor error code (a number that is the driver vendor's error
code number). The SQLException object ex is caught, and its three components are
accessed with the methods getMessage , getSQLState , and getErrorCode
Page 42 of 159
4. Native-protocol, pure Java driver
Each of these types meets a different application need, as we'll discuss in the following
sections.
Type 1: JDBC-ODBC Bridge, Plus ODBC Driver
The first type of JDBC driver is the JDBC-ODBC Bridge. This driver type is provided by Sun
with the JDK1.1 and later. It provides JDBC access to databases through ODBC drivers. The
ODBC driver must be configured on the client for the bridge to work. This driver type is
commonly used for prototyping or when there is no JDBC driver available for a particular
Database Management System (DBMS).
Type 2: Native-API Driver
The native-API driver converts JDBC commands into DBMS-specific native calls. This is
much like the restriction of Type 1 drivers. The client must have some binary code loaded on
its machine. These drivers do have an advantage over Type 1 drivers, because they interface
directly with the database.
Type 3: JDBC-Net, Pure Java Driver
The JDBC-Net drivers are a three-tier solution. This type of driver translates JDBC calls into
a database independent network protocol that is sent to a middleware server. This server
then translates this DBMS independent protocol into a DBMS-specific protocol, which is sent
to a particular database. The results are routed back through the middleware server and sent
back to the client. This type of solution makes it possible to implement a pure Java client. It
also makes it possible to swap databases without affecting the client. This is by far the most
flexible JDBC solution.
Type 4: Native-Protocol, Pure Java Driver
The Type 4 drivers are pure Java drivers that communicate directly with the vendor's
database. They do this by converting JDBC commands directly into the database engine's
native protocol. The Type 4 driver has a very distinct advantage over all the other driver
types. It has no additional translation or middleware layers, which improves performance
tremendously.
Page 43 of 159
to substitute for a question mark is a Java String , you call the method setString , and so on.
In general, there is a setXXX method for each type in the Java programming language.
Code Fragment 1:
String updateString = "UPDATE COFFEES SET SALES = 75 " +
"WHERE COF_NAME LIKE 'Colombian'";
stmt.executeUpdate(updateString);
Code Fragment 2:
PreparedStatement updateSales = con.prepareStatement(
"UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ? ");
updateSales.setInt(1, 75);
updateSales.setString(2, "Colombian");
updateSales.executeUpdate():
Page 44 of 159
and prices shown in the result set example above. In order to access the names and
prices, we will go to each row and retrieve the values according to their types. The
method next moves what is called a cursor to the next row and makes that row (called
the current row) the one upon which we can operate. Since the cursor is initially
positioned just above the first row of a ResultSet object, the first call to the method
next moves the cursor to the first row and makes it the current row. Successive
invocations of the method next move the cursor down one row at a time from top to
bottom.
Committing a Transaction:
Once auto-commit mode is disabled, no SQL statements will be committed until you
call the method commit explicitly. All statements executed after the previous call to the
method commit will be included in the current transaction and will be committed together as a
unit. The following code, in which con is an active connection, illustrates a transaction:
Ex: con.setAutoCommit(false);
PreparedStatement updateSales = con.prepareStatement(
"UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
updateSales.setInt(1, 50);
updateSales.setString(2, "Colombian");
updateSales.executeUpdate();
PreparedStatement updateTotal = con.prepareStatement(
"UPDATE COFFEES SET TOTAL = TOTAL + ? WHERE COF_NAME
LIKE ?");
updateTotal.setInt(1, 50);
updateTotal.setString(2, "Colombian");
updateTotal.executeUpdate();
con.commit();
con.setAutoCommit(true);
When to Call the Method rollback:
As mentioned earlier, calling the method rollback aborts a transaction and returns
any values that were modified to their previous values. If you are trying to execute one or
more statements in a transaction and get an SQLException , you should call the method
rollback to abort the transaction and start the transaction all over again. That is the only way
to be sure of what has been committed and what has not been committed. Catching an
SQLException tells you that something is wrong, but it does not tell you what was or was not
committed. Since you cannot count on the fact that nothing was committed, calling the
method rollback is the only way to be sure.
Page 45 of 159
15. How will you do paging?
A.
16.Scrolable resultset?
A. One of the new features in the JDBC 2.0 API is the ability to move a result set's cursor
backward as well as forward. There are also methods that let you move the cursor to a
particular row and check the position of the cursor. Scrollable result sets make it possible to
create a GUI (graphical user interface) tool for browsing result sets, which will probably be
one of the main uses for this feature. Another use is moving to a row in order to update it.
Before you can take advantage of these features, however, you need to create a
scrollable ResultSet object. The following line of code illustrates one way to create a
scrollable ResultSet object :
Synatx and Ex:
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet srs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");
Contents
When discussing how a Web server works, it is not enough to simply outline a diagram of
how low-level network packets go in and out of a Web server. To give such a nuts-and-bolts
explanation some sort of practical value, it must be placed in context. Thus, this tutorial will
discuss what a Web server does to enable a better understanding of how it does its work.
Years ago, when Web servers were first prototyped, they served simple HTML documents
and images. Today, as we shall go into later in this tutorial, they are frequently used for much
more.
The first step is to view the Web server as a black box and ask the questions: How does it
work; What can it achieve? It's a safe assumption that most Internet users believe a Web
site's success or failure is due to its content and functionality rather than the server used to
Page 46 of 159
power it. However, the choice of the correct server, and understanding its capabilities and
limitations is an important step on the road to success.
So what does a Web server do? As we mentioned earlier, it serves static content to a Web
browser at a basic level. This means that the Web server receives a request for a Web page
such as
http://www.Webcompare.com/index.html
and maps that Uniform Resource Locator (URL) to a local file on the host server.
In this case, the file
index.html
is somewhere on the host file system. The server then loads this file from disk and serves it
out across the network to the user's Web browser. This entire exchange is mediated by the
browser and server talking to each other using Hypertext Transfer Protocol (HTTP). This
workflow is shown in the figure below.
Page 47 of 159
The second important advance, and the one that makes e-commerce possible, was the
introduction of HyperText Transmission Protocol, Secure (HTTPS). This protocol allows
secure communication to go on between the browser and Web server.
In a nutshell, this means that it is safe for user and server to transmit sensitive data to each
another across what might be considered an insecure network. What happens when the data
arrives at either end is another matter, however, and should not be ignored. We will discuss
this a bit later.
The simplicity of the above arrangements is deceptive, and underestimating its complexities
often leads to bad decisions being made about the design of a Web-hosting infrastructure. It
is too easy to focus on the design of the Web pages themselves and the technologies used
to create dynamic content, such as Java, Javascript, Perl, C/C++, and ASP, and to
subsequently miss the fact that each of these technologies can be aided, or hindered, by the
platform on which they are to be run -- the Web server itself..
In other words, explaining how a Web server works involves discussing more than just how a
Web server serves documents. We will go over the following topics in our quest to finding out
what and how a modern Web server goes about doing its activities.
• What Is HTTP, and How Does It Work?
• How Does a Web Server Serve Content?
• How Does a Web Server Accept Connections?
• How Do You Choose a Web Server Platform?
• How Do You Organize Web Servers for Performance?
• How Do You Configure Web Servers for Performance?
Put simply, HTTP is the protocol that allows Web browsers and servers to communicate. It
forms the basis of what a Web server must do to perform its most basic operations.
HTTP started out as a very simple protocol, and even though it has had numerous
enhancements, it is still relatively simple. As with other standard Internet protocols, control
information is passed as plain text via a TCP connection.
In fact, HTTP connections can actually be made using standard "telnet" commands.
Page 48 of 159
For example:
/home/chughes > telnet www.extropia 80
GET /index.html HTTP/1.0
<- Extra char return needed
Note that port 80 is the default port a Web server "listens" on for connections.
In response to this HTTP GET command, the Web server returns to us the page "index.html"
across the telnet session, and then closes the connection to signify the end of the document.
The following is part of the sample response:
<HTML>
<HEAD>
<TITLE>eXtropia Homepage</TITLE>
[...]
</HEAD>
</HTML>
But this simple request/response protocol was quickly outgrown, and it wasn't long before
HTTP was refined into a more complex protocol (currently version 1.1). Perhaps the greatest
change in HTTP/1.1 is its support for persistent connections.
In HTTP/1.0, a connection must to be made to the Web server for each object the browser
wishes to download. Many Web pages are very graphic intensive, which means that in
addition to downloading the base HTML page (or frames), the browser must also retrieve a
number of images. Many of them may actually be quite small and merely sliced up to provide
some hard-coded formatting framework to the rest of the HTML page.
Establishing a connection for each one is wasteful, as several network packets have to be
exchanged between the Web browser and Web server before the image data can ever start
transmitting. In contrast, opening a single TCP connection that transmits the HTML document
and then each image one-by-one is more efficient, as the negotiation of starting new TCP
connections is eliminated.
text/xml xml
video/mpeg mpeg mpg mpe
video/quicktime qt mov
Page 49 of 159
From this, we can see that files containing MPEG video content end with file extensions such
as mpeg, mpg, or mpe. So a file with the name "southpark.mpeg" would be served up as
being an MPEG video file.
Page 50 of 159
administrator doesn't have to worry about starting and stopping the Web server; as long as
inetd is running, it will be automatically run each time an HTTP request is received on the
given port.
On the downside, having a Web server process run for each HTTP request is expensive on
the Web host, and is completely impractical for modern popular Web sites. These days, most
Web sites run a Web server that supports either multi-processing or multi-threading, and are
thus able to handle a much higher load.
Page 51 of 159
more than one IP address for the hostname or returning a different IP address for each DNS
request it receives.
Either way, what happens is a very basic distribution across the Web servers, although as far
as the Web browsers are concerned there is only one Web site. This balancing is very basic,
however, as it is difficult to determine to which IP address each client will resolve the site
name. Also, since DNS query answers are essentially cached by the clients and other DNS
servers, that single client will continue accessing the same Web server for the duration of the
user's visit.
It is possible then that through a luck of the draw, heavy Web site users may get one IP
address, and less-frequent Web site users tend to get another IP address. Thus, even with
this load-balancing technique in effect, it is possible that the Web server belonging to the first
IP address will be highly loaded, and the other one will be lightly loaded, rather than having
the load spread evenly between the two.
Unfortunately the problems with this sort of "poor-man's load balancing" does not stop there.
DNS Caches may not stay alive forever. So it is possible that a client, while using a Web site,
may end up receiving a different IP address for the Web site. This can cause problems with
dynamic sites, particularity ones that need to store data about the client.
As it is possible for a single client to hit more than one of the Web servers, this data needs.
Page 52 of 159
Finally, e-commerce servers have another bottleneck to contend with: encrypting SSL
transactions. It turns out that establishing SSL connections is very expensive in terms of CPU
power. This is another case where having a fast CPU will help you. However, there are better
solutions, like SSL acceleration.
Rather than spending money on the highest Mhz processor, enterprises can buy from one of
the third-party vendors that sell SSL acceleration cards and add-ons to Web servers. These
are processors that are inexpensive yet highly optimized to perform encryption extremely
rapidly.
Generally these cards offer another advantage in that the SSL keys for the Web server can
usually be stored in the card. A dip switch can then be flipped on the card to make that SSL
key irretrievable. This is important because if an SSL Web site is hacked into, it is possible
for an intruder to steal the SSL keys. With physically locked SSL encryption hardware, there
is no way an intruder can get to those keys.
Page 53 of 159
How Does a Web Server Differ From an Application Server?
We've already talked about what a Web server can do. But what about an application server?
The distinction used to be quite clear. A Web server only served up HTML and images for
viewing on a browser. And while an application could exist on the Web server, that
application was typically restricted to just generating HTML and image data.
Likewise, in the beginning, the definition of an application server was fairly concrete. An
application server merely contained raw business/application logic of an application and did
not contain database or user interface code.
In many cases, the application server served as the middle-tier of three-tier programming.
The figure below contains an illustration of the three-tier programming model.
In other words, an application server sits in the middle of other programs and serves to
process data for those other programs. Usually, in the case of three-tier programming, the
two layers that are separated by the application server is the User Interface layer and the
Database/Data Storage layer.
Note that the concept of an application server should not be confused with Web applications
sitting on a Web server itself. Web applications generally also contain application logic, but
since they primarily serve to generate HTML for a Web browser, they are also user interface
related and generally do not ever reside on a pure application server.
Data Marshalling
Data marshalling is a term used to refer to the way applications talk to each other. Similar to
how Web servers wrap human-readable content in HTML to make it palatable to the eye,
application servers wrap application-readable content inside other tags to allow the data to
be interpreted by the receiving application. These "tags" formed the standards around which
application servers were formed. For example, CORBA servers use a protocol called IIOP
(Internet Inter-Orb Protocol) to transfer data between application objects. More recently, XML
extensiblee Markup Language) has made data marshalling as easy as making up your own
tags that are similar in syntax to HTML except that they describe data rather than how
content should be displayed in a browser. More information about XML can be found in
Selena Sol's XML tutorial
In the past, most such application servers talked the language of data marshalling protocols
such as IIOP for CORBA, Java's object serialization for RMI, and DCOM for remotely
activating Microsoft ActiveX objects. However, the rise of XML (extensible markup language)
as an internet friendly data marshalling language has blurred the boundaries.
Web Servers are turning into application servers that serve XML data alongside HTML data.
Likewise, application servers are being marketed as being able to add value by having the
capability of acting as a simple Web server while still delivering on it's core application server
functionality.
Nearly all Java Enterprise Bean servers market the capability to simultaneously serve Java
Servlets and Java Server Pages -- traditionally the realm of Web servers. Likewise, new data
marshalling languages such as the Microsoft endorsed SOAP (Simple Object Access
Protocol) XML standard have implementations that run in conjunction with existing Web
servers.
So what should you use now that the distinction has become blurred? Web Server or
Application Server?
Page 54 of 159
The reality is that one size does not fit all. Typically, application servers are tuned for
processing data using objects or code that represents application logic. Likewise, Web
servers tend to be tuned to sending out data.
Web sitesic rule of thumb is that if you think of your Web site as, well, a Web site, then you
should probably be using a Web server. Even if the data you are serving is dynamic, the fact
that your site is Web centric means that all the configuration parameters of your Web server
are best served tuning how you display information to other people's browsers.
For example, although it is easy to find an application server that can serve Web pages, you
will be hard-pressed to provide one that supports Server-Side Includes (SSI) which is a
feature nearly every Web server supports out of the box. Of course, you can still add
application server components to a Web server if part of the data will be related to
applications.
However, If you find that you are using application server components as the primary reason
for your Web site, or that the Web server itself is being dragged down by all the resources
that the application components may be using, then you should consider moving the
application components to their own application server.
One thing we should mention is that breaking out application components of a Web site into
a separate application server can help you in several ways. In some cases, breaking out the
application components can increase both performance and stability of an application.
However, you should be wary of doing this too early because the addition of yet another
server in your environment can also add quite a bit of complexity to managing your
infrastructure.
As we just mentioned, breaking out application components in this way also usually aids in
performance. For example, Web servers are usually highly tuned to serve data from disk
such as HTML pages and images very efficiently. Such a server is tuned to speed up IO
operations. On the other hand, application objects are usually operating on pure logic alone
-- they take data in from a stream, process it, and send new data back out again. This is a
CPU rather than IO intensive activity. Thus, the application server is best served when it is
tuned for CPU usage.
In addition, breaking out components usually adds to the stability of an application.
Application servers are tested by their respective vendors to work in the context of executing
application logic and so they are thoroughly debugged in that context. Likewise, Web servers
are heavily tested within the context of serving documents either dynamically or statically.
Mixing the two into one server can cause unexpected bugs that neither vendor has tested for.
Note that I use the word vendor loosely here since Apache has no "vendor" but rather is a
community of open source developers who have arguably tested Apache beyond the scope
that many other Web server vendors test their own products. However, even an Open Source
community may have limits to the mix of environments that their products have been tested
in.
Of course, these benefits should be tempered by what we mentioned earlier. If your Web site
is mostly serving document data, it probably doesn't make much sense to rush out and
purchase an application server. Indeed, if your environment is simple, you could be adding
unnecessary complexity to the overall solution, thus maikng it harder to maintain and
administrate -- unless you have devoted human resources to such an endeavor. As a rule of
thumb, the more servers there, the more that must be maintained.
Page 55 of 159
How Does a Web Server Run Web Applications?
A discussion of application servers and Web servers would not be complete without a brief
introduction to some of the technologies used to allow a Web server to serve dynamic data.
In a way, these technologies are what led people to realize that Web servers can also serve
application data such as XML instead of merely serving up HTML documents.
Although these technologies may appear to be close in definition to an application server,
they are different. Web application technologies are primarily focused on delivering
dynamically generated HTML documents to a user's Web browser while they interact with a
Web site. The pure application servers do not format data for humans to read. Rather they
act as an engine that processes data for another program to read and interpret on behalf of
the user.
In this section we will provide a description of the following technologies:
• CGI
• Microsoft ASP
• Java Servlets
• PHP
• Mod_perl
The first such technology is Common Gateway Interface, commonly referred to as CGI. As
previously discussed in the section that focused on what a Web server does, CGI programs
serve HTML data dynamically based on input passed to them. Many people associate CGI
with a language called Perl because Perl has been used to create a majority of the CGI
scripts that currently in use.
However, CGI is not language specific -- it is merely a protocol for allowing the Web server to
communicate with a program. CGI can be written in any language, and common choices, in
addition to Perl, include C, Python, and TCL.
The disadvantage of CGI is that it tends to be slow because each request for a dynamic
document relies on a new program being launched. Starting new processes on a Web server
adds extra overhead. Soon after CGI came into being, other technologies quickly followed to
solve this performance issue.
Microsoft Active Server Pages (ASP) technology consists of embedding a VBScript
interpreter into the Microsoft Internet Information Server. On the Java front, Servlets and
Java Server Pages connects a perpetually running Java Virtual Machine to a Web Server.
Servlets have an additional advantage over ASPs in that they become cached in the Java
Virtual Machine after their first execution. VBScript pages are reinterpreted each time they
are hit.
In the Open Source community, PHP (http://www.php.net/). It is similar to JSP and ASP
technology in that PHP consists of a set of additional code tags placed inside of existing
HTML documents. The interesting part about PHP is that it is a language developed purely to
serve Web pages rather than being based off of an existing language such as Perl, Python,
Visual Basic, or Java. This makes PHP-written applications very succinct compared to
equivalent VBScript or JSP applications.
While all of this was going on, the Perl community did not rest on its laurels. All of today's
major Web servers have Perl acceleration solutions available to it. Apache has a free solution
called mod_perl, which embeds the Perl interpreter inside of Apache. Not only does this
speed up Perl scripts, but the scripts themselves are also cached by mod_perl, providing
further performance boosts.
Mod_perl also hooks tightly into Apache so a Perl developer can literally change the behavior
of how the Apache Web Server works. Previous to mod_perl, this type of control over a Web
server belonged solely to the realm of C programmers coding to the low-level Apache API.
Page 56 of 159
Commercial solutions from ActiveState and Binary Evolution also exist to accelerate Perl in a
similar way to mod_perl. ActiveState's product, PerlEx, accelerates CGI/Perl scripts for
Internet Information Server while Binary Evolution's product exists for Netscape, Apache, and
Internet Information Server on both Unix and NT platforms.
Phew! With all these fast solutions around, it may seem like it's a bit hard to choose a
language to in which to develop when making Web servers serve up dynamic pages.
Actually, it's quite easy. Unless you have a really large hit rate where squeezing every
performance bit out helps, you should go with whatever language is comfortable for you or
your organization to do its job effectively.
Wrapping Up
That's it! How a Web server works in a nutshell. Well, OK, so it's a pretty big nutshell. On the
surface, it is difficult to believe that there can be so much to a piece of software that
distributes HTML documents and images.
Seven years ago that was the case. Since then, the concept of content has evolved to
include application data, streaming multimedia, security models, and integration with other
data and content servers. Likewise, the mechanisms behind how the Web server integrates
with the rest of the world to provide this content has expanded as well.
In summary, this tutorial has gone over all the bits and pieces that make a Web server work.
We have covered everything from how the server works internally to how it works within an
existing infrastructure.
Page 57 of 159
(Download template source code -- click with the right mouse on the link or hold down SHIFT
while clicking on the link.)
To be a servlet, a class should extend HttpServlet and override doGet or doPost (or both),
depending on whether the data is being sent by GET or by POST. These methods take two
arguments: an HttpServletRequest and an HttpServletResponse. The HttpServletRequest has
methods that let you find out about incoming information such as FORM data, HTTP request
headers, and the like. The HttpServletResponse has methods that lets you specify the HTTP
response line (200, 404, etc.), response headers (Content-Type, Set-Cookie, etc.), and, most
importantly, lets you obtain a PrintWriter used to send output back to the client. For simple
servlets, most of the effort is spent in println statements that generate the desired page. Note
that doGet and doPost throw two exceptions, so you are required to include them in the
declaration. Also note that you have to import classes in java.io (for PrintWriter, etc.), javax.servlet
(for HttpServlet, etc.), and javax.servlet.http (for HttpServletRequest and HttpServletResponse). Finally,
note that doGet and doPost are called by the service method, and sometimes you may want to
override service directly, e.g. for a servlet that handles both GET and POST request.
2. A Simple Servlet Generating Plain Text
Here is a simple servlet that just generates plain text. The following section will show the
more usual case where HTML is generated.
2.1 HelloWorld.java
You can also download the source or try it on-line.
package hall;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Page 58 of 159
If you've never used packages before, there are two main ways to compile classes that are in
packages.
One way is to set your CLASSPATH to point to the directory above the one actually containing
your servlets. You can them compile normally from within the directory. For example, if your
base directory is C:\JavaWebServer\servlets and your package name (and thus subdirectory
name) is hall, and you were on Windows, you'd do:
DOS> set CLASSPATH=C:\JavaWebServer\servlets;%CLASSPATH%
DOS> cd C:\JavaWebServer\servlets\hall
DOS> javac YourServlet.java
The first part, setting the CLASSPATH, you probably want to do permanently, rather than each
time you start a new DOS window. On Windows 95/98 you'd typically put the "set
CLASSPATH=..." statement in your autoexec.bat file somewhere after the line that set the
CLASSPATH to point to servlet.jar and jsp.jar. On Windows NT, you'd go to the Start menu, select
Settings, select Control Panel, select System, select Environment, then enter the variable
and value. Note also that if your package were of the form name1.name2.name3 rather than
simply name1 as here, you'd still have the CLASSPATH point to the top-level directory of your
package hierarchy (the one containing name1).
A second way to compile classes that are in packages is to go to the directory above the one
containing your servlets, and then do "javac directory\YourServlet.java" (Windows; note the
backslash) or "javac directory/YourServlet.java" (Unix; note the forward slash). For example,
suppose again that your base directory is C:\JavaWebServer\servlets and your package name
(and thus subdirectory name) is hall, and you were on Windows. In that case, you'd do the
following:
DOS> cd C:\JavaWebServer\servlets
DOS> javac hall\YourServlet.java
Note that, on Windows, most JDK 1.1 versions of javac require a backslash, not a forward
slash, after the directory name. This is fixed in JDK 1.2, but since many Web servers are
configured to use JDK 1.1, many servlet authors stick with JDK 1.1 for portability.
Finally, another advanced option is to keep the source code in a location distinct from the
.class files, and use javac's "-d" option to install them in the location the Web server expects.
2.3 Running the Servlet
With the Java Web Server, servlets are placed in the servlets directory within the main JWS
installation directory, and are invoked via http://host/servlet/ServletName. Note that the directory is
servlets, plural, while the URL refers to servlet, singular. Since this example was placed in the
hall package, it would be invoked via http://host/servlet/hall.HelloWorld. Other Web servers may
have slightly different conventions on where to install servlets and how to invoke them. Most
servers also let you define aliases for servlets, so that a servlet can be invoked via
http://host/any-path/any-file.html. The process for doing this is completely server-specific; check
your server's documentation for details.
Page 59 of 159
3. A Servlet that Generates HTML
Most servlets generate HTML, not plain text as in the previous example. To do that, you need
two additional steps: tell the browser that you're sending back HTML, and modify the println
statements to build a legal Web page. The first step is done by setting the Content-Type
response header. In general, headers can be set via the setHeader method of
HttpServletResponse, but setting the content type is such a common task that there is also a
special setContentType method just for this purpose. Note that you need to set response
headers before actually returning any of the content via the PrintWriter. Here's an example:
3.1 HelloWWW.java
You can also download the source or try it on-line.
package hall;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Page 60 of 159
highly recommended both for static HTML pages and for pages generated via servlets, so
the use of DOCTYPE is well worth the effort, especially if it can be easily incorporated into a
servlet utilities class.
In many Web pages, the HEAD line contains nothing but the TITLE, although advanced
developers may want to include META tags and style sheets. But for the simple case, I'll
create a method that takes a title as input and returns the DOCTYPE, HEAD, and TITLE entries
as output. Here's the code:
4.1 ServletUtilities.java (Download source code)
package hall;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Page 61 of 159
already in your cart? Even if servers did retain contextual information, you'd still have
problems with e-commerce. When you move from the page where you specify what you want
to buy (hosted on the regular Web server) to the page that takes your credit card number and
shipping address (hosted on the secure server that uses SSL), how does the server
remember what you were buying?
There are three typical solutions to this problem.
1. Cookies. You can use HTTP cookies to store information about a shopping session,
and each subsequent connection can look up the current session and then extract
information about that session from some location on the server machine. This is an
excellent alternative, and is the most widely used approach. However, even though
servlets have a high-level and easy-to-use interface to cookies, there are still a
number of relatively tedious details that need to be handled:
• Extracting the cookie that stores the session identifier from the other cookies
(there may be many, after all),
• Setting an appropriate expiration time for the cookie (sessions interrupted by 24
hours probably should be reset), and
• Associating information on the server with the session identifier (there may be
far too much information to actually store it in the cookie, plus sensitive data
like credit card numbers should never go in cookies).
2. URL Rewriting. You can append some extra data on the end of each URL that
identifies the session, and the server can associate that session identifier with data it
has stored about that session. This is also an excellent solution, and even has the
advantage that it works with browsers that don't support cookies or where the user
has disabled cookies. However, it has most of the same problems as cookies, namely
that the server-side program has a lot of straightforward but tedious processing to do.
In addition, you have to be very careful that every URL returned to the user (even via
indirect means like Location fields in server redirects) has the extra information
appended. And, if the user leaves the session and comes back via a bookmark or link,
the session information can be lost.
3. Hidden form fields. HTML forms have an entry that looks like the following: <INPUT
TYPE="HIDDEN" NAME="session" VALUE="...">. This means that, when the form is
submitted, the specified name and value are included in the GET or POST data. This
can be used to store information about the session. However, it has the major
disadvantage that it only works if every page is dynamically generated, since the
whole point is that each session has a unique identifier.
Servlets provide an outstanding technical solution: the HttpSession API. This is a high-level
interface built on top of cookies or URL-rewriting. In fact, on many servers, they use cookies
if the browser supports them, but automatically revert to URL-rewriting when cookies are
unsupported or explicitly disabled. But the servlet author doesn't need to bother with many of
the details, doesn't have to explicitly manipulate cookies or information appended to the URL,
and is automatically given a convenient place to store data that is associated with each
session.
2. The Session Tracking API
Using sessions in servlets is quite straightforward, and involves looking up the session object
associated with the current request, creating a new session object when necessary, looking
up information associated with a session, storing information in a session, and discarding
completed or abandoned sessions.
Page 62 of 159
2.1 Looking up the HttpSession object associated with the current request.
This is done by calling the getSession method of HttpServletRequest. If this returns null, you can
create a new session, but this is so commonly done that there is an option to automatically
create a new session if there isn't one already. Just pass true to getSession. Thus, your first
step usually looks like this:
HttpSession session = request.getSession(true);
2.2 Looking up Information Associated with a Session.
HttpSession objects live on the server; they're just automatically associated with the requester
by a behind-the-scenes mechanism like cookies or URL-rewriting. These session objects
have a builtin data structure that let you store any number of keys and associated values. In
version 2.1 and earlier of the servlet API, you use getValue("key") to look up a previously stored
value. The return type is Object, so you have to do a typecast to whatever more specific type
of data was associated with that key in the session. The return value is null if there is no such
attribute. In version 2.2, getValue is deprecated in favor of getAttribute, both because of the
better naming match with setAttribute (the match for getValue is putValue, not setValue), and
because setAttribute lets you use an attached HttpSessionBindingListener to monitor values,
while putValue doesn't. Nevertheless, since few commercial servlet engines yet support
version 2.2, I'll use getValue in my examples. Here's one representative example, assuming
ShoppingCart is some class you've defined yourself that stores information on items being
purchased.
HttpSession session = request.getSession(true);
ShoppingCart previousItems =
(ShoppingCart)session.getValue("previousItems");
if (previousItems != null) {
doSomethingWith(previousItems);
} else {
previousItems = new ShoppingCart(...);
doSomethingElseWith(previousItems);
}
In most cases, you have a specific attribute name in mind, and want to find the value (if any)
already associated with it. However, you can also discover all the attribute names in a given
session by calling getValueNames, which returns a String array. In version 2.2, use
getAttributeNames, which has a better name and which is more consistent in that it returns an
Enumeration, just like the getHeaders and getParameterNames methods of HttpServletRequest.
Although the data that was explicitly associated with a session is the part you care most
about, there are some other pieces of information that are sometimes useful as well.
• getId. This method returns the unique identifier generated for each session. It is
sometimes used as the key name when there is only a single value associated with a
session, or when logging information about previous sessions.
• isNew. This returns true if the client (browser) has never seen the session, usually
because it was just created rather than being referenced by an incoming client
request. It returns false for preexisting sessions.
• getCreationTime. This returns the time, in milliseconds since the epoch, at which the
session was made. To get a value useful for printing out, pass the value to the Date
constructor or the setTimeInMillis method of GregorianCalendar.
• getLastAccessedTime. This returns the time, in milliseconds since the epoch, at
which the session was last sent from the client.
Page 63 of 159
• getMaxInactiveInterval. This returns the amount of time, in seconds, that a session
should go without access before being automatically invalidated. A negative value
indicates that the session should never timeout.
2.3 Associating Information with a Session
As discussed in the previous section, you read information associated with a session by
using getValue (or getAttribute in version 2.2 of the servlet spec). To specify information, you use
putValue (or setAttribute in version 2.2), supplying a key and a value. Note that putValue replaces
any previous values. Sometimes that's what you want (as with the referringPage entry in the
example below), but other times you want to retrieve a previous value and augment it (as
with the previousItems entry below). Here's an example:
HttpSession session = request.getSession(true);
session.putValue("referringPage", request.getHeader("Referer"));
ShoppingCart previousItems =
(ShoppingCart)session.getValue("previousItems");
if (previousItems == null) {
previousItems = new ShoppingCart(...);
}
String itemID = request.getParameter("itemID");
previousItems.addEntry(Catalog.getEntry(itemID));
// You still have to do putValue, not just modify the cart, since
// the cart may be new and thus not already stored in the session.
session.putValue("previousItems", previousItems);
3. Example: Showing Session Information
Here is a simple example that generates a Web page showing some information about the
current session. You can also download the source or try it on-line.
package hall;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.*;
import java.util.*;
Page 64 of 159
String title = "Searching the Web";
String heading;
Integer accessCount = new Integer(0);;
if (session.isNew()) {
heading = "Welcome, Newcomer";
} else {
heading = "Welcome Back";
Integer oldAccessCount =
// Use getAttribute, not getValue, in version
// 2.2 of servlet API.
(Integer)session.getValue("accessCount");
if (oldAccessCount != null) {
accessCount =
new Integer(oldAccessCount.intValue() + 1);
}
}
// Use putAttribute in version 2.2 of servlet API.
session.putValue("accessCount", accessCount);
out.println(ServletUtilities.headWithTitle(title) +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=\"CENTER\">" + heading + "</H1>\n" +
"<H2>Information on Your Session:</H2>\n" +
"<TABLE BORDER=1 ALIGN=CENTER>\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" +
" <TH>Info Type<TH>Value\n" +
"<TR>\n" +
" <TD>ID\n" +
" <TD>" + session.getId() + "\n" +
"<TR>\n" +
" <TD>Creation Time\n" +
" <TD>" + new Date(session.getCreationTime()) + "\n" +
"<TR>\n" +
" <TD>Time of Last Access\n" +
" <TD>" + new Date(session.getLastAccessedTime()) + "\n" +
"<TR>\n" +
" <TD>Number of Previous Accesses\n" +
" <TD>" + accessCount + "\n" +
"</TABLE>\n" +
"</BODY></HTML>");
Page 65 of 159
Here's a typical result, shown after visiting the page several without quitting the browser in
between:
Page 66 of 159
A. Cookies are little (up to 4k) pieces of text stored by the server on a client's machine. Cookies
are a standard way to store persistent session information (shopping cart, client's
preferences, etc.). Every Web server supports cookies, and more than 80% clients keep
cookies options turned on in their Internet browsers.
8. What will happen if my servlet attempts to write a cookie to the client's machine, and his
browser doesn't accept cookies?
A. Nothing will happen except you will be unable to read this cookie from a client.
1. What is a servlet?
Servlets are modules that extend request/response-oriented servers,such as Java-
enabled web servers. For example, a servlet might be responsible for taking data in
an HTML order-entry form and applying the business logic used to update a
company’s order database. Servlets are to servers what applets are to browsers.
Unlike applets, however, servlets have no graphical user interface.
2. Whats the advantages using servlets over using CGI?
Servlets provide a way to generate dynamic documents that is both easier to write and
faster to run. Servlets also address the problem of doing server-side programming
with platform-specific APIs: they are developed with the Java Servlet API, a standard
Java extension.
3. What are the general advantages and selling points of Servlets?
A servlet can handle multiple requests concurrently, and synchronize requests. This
allows servlets to support systems such as online
real-time conferencing. Servlets can forward requests to other servers and servlets.
Thus servlets can be used to balance load among several servers that mirror the
same content, and to partition a single logical service over several servers, according
to task type or organizational boundaries.
4. Which package provides interfaces and classes for writing servlets? javax
5. What’s the Servlet Interface?
The central abstraction in the Servlet API is the Servlet interface. All servlets
implement this interface, either directly or, more
commonly, by extending a class that implements it such as HttpServlet.Servlets >
Generic Servlet > HttpServlet > MyServlet.
The Servlet interface declares, but does not implement, methods that manage the
servlet and its communications with clients. Servlet writers provide some or all of
these methods when developing a servlet.
6. When a servlet accepts a call from a client, it receives two objects. What are
they?
ServletRequest (which encapsulates the communication from the client to the server)
and ServletResponse (which encapsulates the communication from the servlet back
Page 67 of 159
to the client). ServletRequest and ServletResponse are interfaces defined inside
javax.servlet package.
7. What information does ServletRequest allow access to?
Information such as the names of the parameters passed in by the client, the protocol
(scheme) being used by the client, and the names
of the remote host that made the request and the server that received it. Also the input
stream, as ServletInputStream.Servlets use the input stream to get data from clients
that use application protocols such as the HTTP POST and GET methods.
8. What type of constraints can ServletResponse interface set on the client?
It can set the content length and MIME type of the reply. It also provides an output
stream, ServletOutputStream and a Writer through
which the servlet can send the reply data.
9. Explain servlet lifecycle?
Each servlet has the same life cycle: first, the server loads and initializes the servlet
(init()), then the servlet handles zero or more client requests (service()), after that the
server removes the servlet (destroy()). Worth noting that the last step on some servers
is done when they shut down.
10. How does HTTP Servlet handle client requests?
An HTTP Servlet handles client requests through its service method. The service
method supports standard HTTP client requests by dispatching each request to a
method designed to handle that request.
Page 68 of 159
1. Overview
JavaServer Pages (JSP) lets you separate the dynamic part of your pages from the static
HTML. You simply write the regular HTML in the normal manner, using whatever Web-page-
building tools you normally use. You then enclose the code for the dynamic parts in special
tags, most of which start with "<%" and end with "%>". For example, here is a section of a JSP
page that results in something like "Thanks for ordering Core Web Programming" for a URL
of http://host/OrderConfirmation.jsp?title=Core+Web+Programming:
Thanks for ordering
<I><%= request.getParameter("title") %></I>
You normally give your file a .jsp extension, and typically install it in any place you could
place a normal Web page. Although what you write often looks more like a regular HTML file
than a servlet, behind the scenes, the JSP page just gets converted to a normal servlet, with
the static HTML simply being printed to the output stream associated with the servlet's service
method. This is normally done the first time the page is requested, and developers can
simply request the page themselves when first installing it if they want to be sure that the first
real user doesn't get a momentary delay when the JSP page is translated to a servlet and the
servlet is compiled and loaded. Note also that many Web servers let you define aliases that
so that a URL that appears to reference an HTML file really points to a servlet or JSP page.
Aside from the regular HTML, there are three main types of JSP constructs that you embed
in a page: scripting elements, directives, and actions. Scripting elements let you specify Java
code that will become part of the resultant servlet, directives let you control the overall
structure of the servlet, and actions let you specify existing components that should be used,
and otherwise control the behavior of the JSP engine. To simplify the scripting elements, you
have access to a number of predefined variables such as request in the snippet above.
Note that this tutorial covers version 1.0 of the JSP specification. JSP has changed
dramatically since version 0.92, and although these changes were almost entirely for the
better, you should note that version 1.0 JSP pages are almost totally incompatible with the
earlier JSP engines. Note that this JSP tutorial is part of a larger tutorial on servlets and JSP
at http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/.
2. Syntax Summary
JSP
Synta
Eleme Interpretation Notes
x
nt
XML equivalent is
<jsp:expression>
<%= expression
JSP
expre Expression is evaluated and </jsp:expression>. Predefined variables are
Expres
ssion placed in output. request, response, out, session, application,
sion
%> config, and pageContext (available in scriptlets
also).
JSP <% XML equivalent is
Code is inserted in service <jsp:scriptlet>
Scriptl code code
method.
et %> </jsp:scriptlet>.
JSP <%! Code is inserted in body of XML equivalent is
<jsp:declaration>
Declar code servlet class, outside of service code
ation %> method. </jsp:declaration>.
JSP <%@ Directions to the servlet XML equivalent is
Page 69 of 159
<jsp:directive.page att="val"\>.
Legal attributes,
with default values in bold, are:
• import="package.class"
• contentType="MIME-Type"
• isThreadSafe="true|false"
page page • session="true|false"
Directi att="v engine about general setup. • buffer="sizekb|none"
ve al" %> • autoflush="true|false"
• extends="package.class"
• info="message"
• errorPage="url"
• isErrorPage="true|false"
• language="java"
<%@ XML equivalent is
JSP <jsp:directive.include
includ A file on the local system to be file="url"\>.
include
Directi e included when the JSP page The URL must be a relative one. Use the
ve file="u is translated into a servlet. jsp:include action to include a file at request
rl" %> time instead of translation time.
<%--
JSP If you want a comment in the resultant
comm Comment; ignored when JSP
Comm HTML, use regular HTML comment syntax
ent -- page is translated into servlet.
ent of <-- comment -->.
%>
<jsp:in
clude If you want to include the file at the time the
pag page is translated, use the page directive
The e="rel with the include attribute instead. Warning:
jsp:inclu Includes a file at the time the
de
ative on some servers, the included file must be
page is requested.
Action URL" an HTML file or JSP file, as determined by
flus the server (usually based on the file
h="tru extension).
e"/>
<jsp:us
eBean Possible attributes are:
att=val* • id="name"
The /> or
• scope="page|request|session|
jsp:useB <jsp:us
eBean Find or build a Java Bean. application"
ean
Action >
att=val* • class="package.class"
...
• type="package.class"
</jsp:us • beanName="package.class"
eBean>
<jsp:s Legal attributes are
The Set bean properties, either • name="beanName"
etProp
jsp:setP explicitly or by designating
erty • property="propertyName|*"
roperty that value comes from a
Action att=valrequest parameter. • param="parameterName"
*/> • value="val"
The <jsp:g Retrieve and output bean
Page 70 of 159
etProp
erty
na
me="p
jsp:getP
roperty ropert properties.
Action yNam
e"
valu
e="val
"/>
<jsp:fo
rward
The pag
jsp:forw Forwards request to another
ard e="rel
page.
Action ative
URL"/
>
<jsp:pl
ugin
attri Generates OBJECT or EMBED
The bute=" tags, as appropriate to the
jsp:plugi
n value" browser type, asking that an
Action *> applet be run using the Java
... Plugin.
</jsp:p
lugin>
3. Template Text: Static HTML
In many cases, a large percent of your JSP page just consists of static HTML, known as
template text. In all respects except one, this HTML looks just like normal HTML, follows all
the same syntax rules, and is simply "passed through" to the client by the servlet created to
handle the page. Not only does the HTML look normal, it can be created by whatever tools
you already are using for building Web pages. For example, I used Allaire's HomeSite for
most of the JSP pages in this tutorial.
The one minor exception to the "template text is passed straight through" rule is that, if you
want to have "<%" in the output, you need to put "<\%" in the template text.
4. JSP Scripting Elements
JSP scripting elements let you insert Java code into the servlet that will be generated from
the current JSP page. There are three forms:
4. Expressions of the form <%= expression %> that are evaluated and inserted into the
output,
5. Scriptlets of the form <% code %> that are inserted into the servlet's service method, and
6. Declarations of the form <%! code %> that are inserted into the body of the servlet class,
outside of any existing methods.
Each of these is described in more detail below.
4.1 JSP Expressions
A JSP expression is used to insert Java values directly into the output. It has the following
form:
<%= Java Expression %>
Page 71 of 159
The Java expression is evaluated, converted to a string, and inserted in the page. This
evaluation is performed at run-time (when the page is requested), and thus has full access to
information about the request. For example, the following shows the date/time that the page
was requested:
Current time: <%= new java.util.Date() %>
To simplify these expressions, there are a number of predefined variables that you can use.
These implicit objects are discussed in more detail later, but for the purpose of expressions,
the most important ones are:
• request, the HttpServletRequest;
• response, the HttpServletResponse;
• session, the HttpSession associated with the request (if any); and
• out, the PrintWriter (a buffered version of type JspWriter) used to send output to the client.
Here's an example:
Your hostname: <%= request.getRemoteHost() %>
Finally, note that XML authors can use an alternative syntax for JSP expressions:
<jsp:expression>
Java Expression
</jsp:expression>
Remember that XML elements, unlike HTML ones, are case sensitive. So be sure to use
lowercase.
4.2 JSP Scriptlets
If you want to do something more complex than insert a simple expression, JSP scriptlets let
you insert arbitrary code into the servlet method that will be built to generate the page.
Scriptlets have the following form:
<% Java Code %>
Scriptlets have access to the same automatically defined variables as expressions. So, for
example, if you want output to appear in the resultant page, you would use the out variable.
<%
String queryData = request.getQueryString();
out.println("Attached GET data: " + queryData);
%>
Note that code inside a scriptlet gets inserted exactly as written, and any static HTML
(template text) before or after a scriptlet gets converted to print statements. This means that
scriptlets need not contain complete Java statements, and blocks left open can affect the
static HTML outside of the scriptlets. For example, the following JSP fragment, containing
mixed template text and scriptlets
<% if (Math.random() < 0.5) { %>
Have a <B>nice</B> day!
<% } else { %>
Have a <B>lousy</B> day!
<% } %>
will get converted to something like:
if (Math.random() < 0.5) {
out.println("Have a <B>nice</B> day!");
} else {
out.println("Have a <B>lousy</B> day!");
}
If you want to use the characters "%>" inside a scriptlet, enter "%\>" instead. Finally, note that
the XML equivalent of <% Code %> is
Page 72 of 159
<jsp:scriptlet>
Code
</jsp:scriptlet>
4.3 JSP Declarations
A JSP declaration lets you define methods or fields that get inserted into the main body of the
servlet class (outside of the service method processing the request). It has the following form:
<%! Java Code %>
Since declarations do not generate any output, they are normally used in conjunction with
JSP expressions or scriptlets. For example, here is a JSP fragment that prints out the
number of times the current page has been requested since the server booted (or the servlet
class was changed and reloaded):
<%! private int accessCount = 0; %>
Accesses to page since server reboot:
<%= ++accessCount %>
As with scriptlets, if you want to use the characters "%>", enter "%\>" instead. Finally, note that
the XML equivalent of <%! Code %> is
<jsp:declaration>
Code
</jsp:declaration>
5. JSP Directives
A JSP directive affects the overall structure of the servlet class. It usually has the following
form:
<%@ directive attribute="value" %>
However, you can also combine multiple attribute settings for a single directive, as follows:
<%@ directive attribute1="value1"
attribute2="value2"
...
attributeN="valueN" %>
There are two main types of directive: page, which lets you do things like import classes,
customize the servlet superclass, and the like; and include, which lets you insert a file into the
servlet class at the time the JSP file is translated into a servlet. The specification also
mentions the taglib directive, which is not supported in JSP version 1.0, but is intended to let
JSP authors define their own tags. It is expected that this will be the main new contribution of
JSP 1.1.
5.1 The JSP page Directive
The page directive lets you define one or more of the following case-sensitive attributes:
• import="package.class" or import="package.class1,...,package.classN". This lets you specify what
packages should be imported. For example:
<%@ page import="java.util.*" %>
The import attribute is the only one that is allowed to appear multiple times.
• contentType="MIME-Type" or
contentType="MIME-Type; charset=Character-Set"
This specifies the MIME type of the output. The default is text/html. For example, the
directive
<%@ page contentType="text/plain" %>
has the same effect as the scriptlet
<% response.setContentType("text/plain"); %>
Page 73 of 159
• isThreadSafe="true|false". A value of true (the default) indicates normal servlet processing,
where multiple requests can be processed simultaneously with a single servlet
instance, under the assumption that the author synchronized access to instance
variables. A value of false indicates that the servlet should implement SingleThreadModel,
with requests either delivered serially or with simultaneous requests being given
separate servlet instances.
• session="true|false". A value of true (the default) indicates that the predefined variable
session (of type HttpSession) should be bound to the existing session if one exists,
otherwise a new session should be created and bound to it. A value of false indicates
that no sessions will be used, and attempts to access the variable session will result in
errors at the time the JSP page is translated into a servlet.
• buffer="sizekb|none". This specifies the buffer size for the JspWriter out. The default is
server-specific, but must be at least 8kb.
• autoflush="true|false". A value of true, the default, indicates that the buffer should be
flushed when it is full. A value of false, rarely used, indicates that an exception should
be thrown when the buffer overflows. A value of false is illegal when also using
buffer="none".
• extends="package.class". This indicates the superclass of servlet that will be generated.
Use this with extreme caution, since the server may be using a custom superclass
already.
• info="message". This defines a string that can be retrieved via the getServletInfo method.
• errorPage="url". This specifies a JSP page that should process any Throwables thrown but
not caught in the current page.
• isErrorPage="true|false". This indicates whether or not the current page can act as the
error page for another JSP page. The default is false.
• language="java". At some point, this is intended to specify the underlying language being
used. For now, don't bother with this since java is both the default and the only legal
choice.
The XML syntax for defining directives is
<jsp:directive.directiveType attribute=value />
For example, the XML equivalent of
<%@ page import="java.util.*" %>
is
<jsp:directive.page import="java.util.*" />
5.2 The JSP include Directive
This directive lets you include files at the time the JSP page is translated into a servlet. The
directive looks like this:
<%@ include file="relative url" %>
The URL specified is normally interpreted relative to the JSP page that refers to it, but, as
with relative URLs in general, you can tell the system to interpret the URL relative to the
home directory of the Web server by starting the URL with a forward slash. The contents of
the included file are parsed as regular JSP text, and thus can include static HTML, scripting
elements, directives, and actions.
For example, many sites include a small navigation bar on each page. Due to problems with
HTML frames, this is usually implemented by way of a small table across the top of the page
or down the left-hand side, with the HTML repeated for each page in the site. The include
directive is a natural way of doing this, saving the developers from the maintenance
Page 74 of 159
nightmare of actually copying the HTML into each separate file. Here's some representative
code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Servlet Tutorial: JavaServer Pages (JSP) 1.0</TITLE>
<META NAME="author" CONTENT="webmaster@somesite.com">
<META NAME="keywords" CONTENT="...">
<META NAME="description" CONTENT="...">
<LINK REL=STYLESHEET
HREF="Site-Styles.css"
TYPE="text/css">
</HEAD>
<BODY>
<%@ include file="/navbar.html" %>
</BODY>
</HTML>
Note that since the include directive inserts the files at the time the page is translated, if the
navigation bar changes, you need to re-translate all the JSP pages that refer to it. This is a
good compromise in a situation like this, since the navigation bar probably changes
infrequently, and you want the inclusion process to be as efficient as possible. If, however,
the included files changed more often, you could use the jsp:include action instead. This
includes the file at the time the JSP page is requested, and is discussed in the tutorial
section on JSP actions.
6. Example Using Scripting Elements and Directives
Here is a simple example showing the use of JSP expressions, scriptlets, declarations, and
directives. You can also download the source or try it on-line.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Using JavaServer Pages</TITLE>
Page 75 of 159
<CENTER>
<TABLE BORDER=5 BGCOLOR="#EF8429">
<TR><TH CLASS="TITLE">
Using JavaServer Pages</TABLE>
</CENTER>
<P>
</BODY>
</HTML>
7. Predefined Variables
To simplify code in JSP expressions and scriptlets, you are supplied with eight automatically
defined variables, sometimes called implicit objects. The available variables are request,
response, out, session, application, config, pageContext, and page. Details for each are given below.
7.1 request
This is the HttpServletRequest associated with the request, and lets you look at the request
parameters (via getParameter), the request type (GET, POST, HEAD, etc.), and the incoming
HTTP headers (cookies, Referer, etc.). Strictly speaking, request is allowed to be a subclass
of ServletRequest other than HttpServletRequest, if the protocol in the request is something other
than HTTP. This is almost never done in practice.
7.2 response
This is the HttpServletResponse associated with the response to the client. Note that, since the
output stream (see out below) is buffered, it is legal to set HTTP status codes and response
headers, even though this is not permitted in regular servlets once any output has been sent
to the client.
Page 76 of 159
7.3 out
This is the PrintWriter used to send output to the client. However, in order to make the response
object (see the previous section) useful, this is a buffered version of PrintWriter called JspWriter.
Note that you can adjust the buffer size, or even turn buffering off, through use of the buffer
attribute of the page directive. This was discussed in Section 5. Also note that out is used
almost exclusively in scriptlets, since JSP expressions automatically get placed in the output
stream, and thus rarely need to refer to out explicitly.
7.4 session
This is the HttpSession object associated with the request. Recall that sessions are created
automatically, so this variable is bound even if there was no incoming session reference. The
one exception is if you use the session attribute of the page directive (see Section 5) to turn
sessions off, in which case attempts to reference the session variable cause errors at the
time the JSP page is translated into a servlet.
7.5 application
This is the ServletContext as obtained via getServletConfig().getContext().
7.6 config
This is the ServletConfig object for this page.
7.7 pageContext
JSP introduced a new class called PageContext to encapsulate use of server-specific features
like higher performance JspWriters. The idea is that, if you access them through this class
rather than directly, your code will still run on "regular" servlet/JSP engines.
7.8 page
This is simply a synonym for this, and is not very useful in Java. It was created as a
placeholder for the time when the scripting language could be something other than Java.
8. Actions
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You
can dynamically insert a file, reuse JavaBeans components, forward the user to another
page, or generate HTML for the Java plugin. Available actions include:
• jsp:include - Include a file at the time the page is requested. See Section 8.1.
• jsp:useBean - Find or instantiate a JavaBean. See Section 8.2 for an overview, and
Section 8.3 for details.
• jsp:setProperty - Set the property of a JavaBean. See Section 8.4.
• jsp:getProperty - Insert the property of a JavaBean into the output. See Section 8.5.
• jsp:forward - Forward the requester to a new page. See Section 8.6.
• jsp:plugin - Generate browser-specific code that makes an OBJECT or EMBED tag for the
Java plugin. See Section 8.7.
These actions are described in more detail below. Remember that, as with XML in general,
the element and attribute names are case sensitive.
8.1 The jsp:include Action
This action lets you insert files into the page being generated. The syntax looks like this:
<jsp:include page="relative URL" flush="true" />
Unlike the include directive, which inserts the file at the time the JSP page is translated into a
servlet, this action inserts the file at the time the page is requested. This pays a small penalty
in efficiency, and precludes the included page from containing general JSP code (it cannot
Page 77 of 159
set HTTP headers, for example), but it gains significantly in flexibility. For example, here is a
JSP page that inserts four different snippets into a "What's New?" Web page. Each time the
headlines change, authors only need to update the four files, but can leave the main JSP
page unchanged.
WhatsNew.jsp
You can also download the source or try it on-line.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>What's New</TITLE>
<LINK REL=STYLESHEET
HREF="My-Style-Sheet.css"
TYPE="text/css">
</HEAD>
<CENTER>
<TABLE BORDER=5 BGCOLOR="#EF8429">
<TR><TH CLASS="TITLE">
What's New at JspNews.com</TABLE>
</CENTER>
<P>
Page 78 of 159
This usually means "instantiate an object of the class specified by class, and bind it to a
variable with the name specified by id." However, as we'll see shortly, you can specify a scope
attribute that makes the bean associated with more than just the current page. In that case, it
is useful to obtain references to existing beans, and the jsp:useBean action specifies that a
new object is instantiated only if there is no existing one with the same id and scope. Now,
once you have a bean, you can modify its properties via jsp:setProperty, or by using a scriptlet
and calling a method explicitly on the object with the variable name specified earlier via the id
attribute. Recall that with beans, when you say "this bean has a property of typeX called foo",
you really mean "this class has a method called getFoo that returns something of type X, and
another method called setFoo that takes an X as an argument." The jsp:setProperty action is
discussed in more detail in the next section, but for now note that you can either supply an
explicit value, give a param attribute to say that the value is derived from the named request
parameter, or just list the property to indicate that the value should be derived from the
request parameter with the same name as the property. You read existing properties in a JSP
expression or scriptlet by calling the appropriate getXxx method, or more commonly, by using
the jsp:getProperty action.
Note that the class specified for the bean must be in the server's regular class path, not the
part reserved for classes that get automatically reloaded when they change. For example, in
the Java Web Server, it and all the classes it uses should go in the classes directory or be in a
jar file in the lib directory, not be in the servlets directory.
Here is a very simple example that loads a bean and sets/gets a simple String parameter.
BeanTest.jsp
You can also download the source or try it on-line.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Reusing JavaBeans in JSP</TITLE>
<LINK REL=STYLESHEET
HREF="My-Style-Sheet.css"
TYPE="text/css">
</HEAD>
<BODY>
<CENTER>
<TABLE BORDER=5>
<TR><TH CLASS="TITLE">
Reusing JavaBeans in JSP</TABLE>
</CENTER>
<P>
<jsp:useBean id="test" class="hall.SimpleBean" />
<jsp:setProperty name="test"
property="message"
value="Hello WWW" />
<H1>Message: <I>
<jsp:getProperty name="test" property="message" />
</I></H1>
</BODY>
</HTML>
Page 79 of 159
SimpleBean.java
Here's the source code for the bean used in the BeanTest JSP page. You can also download
the source.
package hall;
public class SimpleBean {
private String message = "No message specified";
public String getMessage() {
return(message);
}
public void setMessage(String message) {
this.message = message;
}
}
8.3 More jsp:useBean Details
The simplest way to use a bean is to use
<jsp:useBean id="name" class="package.class" />
to load the bean, then use jsp:setProperty and jsp:getProperty
to modify and retrieve bean
properties. However, there are two other options. First, you can use the container format,
namely
<jsp:useBean ...>
Body
</jsp:useBean>
to indicate that the Body portion should be executed only when the bean is first instantiated,
not when an existing bean is found and used. As discussed below, beans can be shared, so
not all jsp:useBean statements result in a new bean being instantiated. Second, in addition to id
and class, there are three other attributes that you can use: scope, type, and beanName. These
attributes are summarized in the following table.
Atrib
Usage
ute
Gives a name to the variable that will reference the bean. A previous bean object is
id used instead of instantiating a new one if one can be found with the same id and
scope.
class Designates the full package name of the bean.
Indicates the context in which the bean should be made available. There are four
possible values: page, request, session, and application. The default, page, indicates
that the bean is only available on the current page (stored in the PageContext of the
current page). A value of request indicates that the bean is only available for the
current client request (stored in the ServletRequest object). A value of session
indicates that the object is available to all pages during the life of the current
scope
HttpSession. Finally, a value of application indicates that it is available to all pages that
share the same ServletContext. The reason that the scope matters is that a
jsp:useBean entry will only result in a new object being instantiated if there is no
previous object with the same id and scope. Otherwise the previously existing object
is used, and any jsp:setParameter elements or other entries between the jsp:useBean
start and end tags will be ignored.
Specifies the type of the variable that will refer to the object. This must match the
type classname or be a superclass or an interface that the class implements.
Remember that the name of the variable is designated via the id attribute.
bean Gives the name of the bean, as you would supply it to the instantiate method of
Page 80 of 159
Name Beans. It is permissible to supply a type and a beanName, and omit the class attribute.
8.4 The jsp:setProperty Action
You use jsp:setProperty to give values to properties of beans that have been referenced earlier.
You can do this in two contexts. First, you can use jsp:setProperty after, but outside of, a
jsp:useBean element, as below:
<jsp:useBean id="myName" ... />
...
<jsp:setProperty name="myName"
property="someProperty" ... />
In this case, the jsp:setProperty is executed regardless of whether a new bean was instantiated
or an existing bean was found. A second context in which jsp:setProperty can appear is inside
the body of a jsp:useBean element, as below:
<jsp:useBean id="myName" ... >
...
<jsp:setProperty name="myName"
property="someProperty" ... />
</jsp:useBean>
Here, the jsp:setProperty is executed only if a new object was instantiated, not if an existing
one was found.
There are four possible attributes of jsp:setProperty:
Attri
Usage
bute
This required attribute designates the bean whose property will be set. The
name
jsp:useBean element must appear before the jsp:setProperty element.
This required attribute indicates the property you want to set. However, there is
proper
ty one special case: a value of "*" means that all request parameters whose names
match bean property names will be passed to the appropriate setter methods.
This optional attribute specifies the value for the property. String values are
automatically converted to numbers, boolean, Boolean, byte, Byte, char, and Character
via the standard valueOf method in the target or wrapper class. For example, a
value value of "true" for a boolean or Boolean property will be converted via Boolean.valueOf,
and a value of "42" for an int or Integer property will be converted via Integer.valueOf.
You can't use both value and param, but it is permissible to use neither. See the
discussion of param below.
param This optional attribute designates the request parameter from which the property
should be derived. If the current request has no such parameter, nothing is done:
the system does not pass null to the setter method of the property. Thus, you can
let the bean itself supply default values, overriding them only when the request
parameters say to do so. For example, the following snippet says "set the
numberOfItems property to whatever the value of the numItems request parameter is,
if there is such a request parameter. Otherwise don't do anything."
<jsp:setProperty name="orderBean"
property="numberOfItems"
param="numItems" />
If you omit both value and param, it is the same as if you supplied a param name that
matches the property name. You can take this idea of automatically using the
request property whose name matches the property one step further by supplying
a property name of "*" and omitting both value and param. In this case, the server
iterates through available properties and request parameters, matching up ones
Page 81 of 159
with identical names.
Here's an example that uses a bean to create a table of prime numbers. If there is a
parameter named numDigits in the request data, it is passed into the bean's numDigits property.
Likewise for numPrimes.
JspPrimes.jsp
To download the JSP source, right click on the source code link. You can also download the
source code for the NumberedPrimes bean referenced by the jsp:useBean element. Browse the
source code directory for other Java classes used by NumberedPrimes. The best way to try it
out on-line is to start with the HTML page that acts as a front end to it.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Reusing JavaBeans in JSP</TITLE>
<LINK REL=STYLESHEET
HREF="My-Style-Sheet.css"
TYPE="text/css">
</HEAD>
<BODY>
<CENTER>
<TABLE BORDER=5>
<TR><TH CLASS="TITLE">
Reusing JavaBeans in JSP</TABLE>
</CENTER>
<P>
<jsp:useBean id="primeTable" class="hall.NumberedPrimes" />
<jsp:setProperty name="primeTable" property="numDigits" />
<jsp:setProperty name="primeTable" property="numPrimes" />
Page 82 of 159
8.6 The jsp:forward Action
This action lets you forward the request to another page. It has a single attribute, page, which
should consist of a relative URL. This could be a static value, or could be computed at
request time, as in the two examples below.
<jsp:forward page="/utils/errorReporter.jsp" />
<jsp:forward page="<%= someJavaExpression %>" />
8.7 The jsp:plugin Action
This action lets you insert the browser-specific OBJECT or EMBED element needed to specify
that the browser run an applet using the Java plugin.
9. Comments and Character Quoting Conventions
There are a small number of special constructs you can use in various cases to insert
comments or characters that would otherwise be treated specially. Here's a summary:
Syntax Purpose
<%--
A JSP comment. Ignored by JSP-to-scriptlet translator. Any embedded JSP
comme
scripting elements, directives, or actions are ignored.
nt --%>
<!--
An HTML comment. Passed through to resultant HTML. Any embedded JSP
comme
scripting elements, directives, or actions are executed normally.
nt -->
<\% Used in template text (static HTML) where you really want "<%".
%\> Used in scripting elements where you really want "%>".
A single quote in an attribute that uses single quotes. Remember, however, that
\' you can use either single or double quotes, and the other type of quote will then
be a regular character.
A double quote in an attribute that uses double quotes. Remember, however,
\" that you can use either single or double quotes, and the other type of quote will
then be a regular character.
%\> %> in an attribute.
<\% <% in an attribute.
JSP Templates
allows layout to be encapsulated and reused. JSP templates minimize the impact of layout
changes and encourage modular design.
XML Parser
JDBC Drivers
Page 83 of 159
JDBC technology drivers fit into one of four categories:
7. A JDBC-ODBC bridge provides JDBC API access via one or more ODBC drivers.
Note that some ODBC native code and in many cases native database client code
must be loaded on each client machine that uses this type of driver. Hence, this kind
of driver is generally most appropriate when automatic installation and downloading of
a Java technology application is not important. For information on the JDBC-ODBC
bridge driver provided by Sun, see JDBC-ODBC Bridge Driver.
8. A native-API partly Java technology-enabled driver converts JDBC calls into calls on
the client API for Oracle, Sybase, Informix, DB2, or other DBMS. Note that, like the
bridge driver, this style of driver requires that some binary code be loaded on each
client machine.
9. A net-protocol fully Java technology-enabled driver translates JDBC API calls into a
DBMS-independent net protocol which is then translated to a DBMS protocol by a
server. This net server middleware is able to connect all of its Java technology-based
clients to many different databases. The specific protocol used depends on the
vendor. In general, this is the most flexible JDBC API alternative. It is likely that all
vendors of this solution will provide products suitable for Intranet use. In order for
these products to also support Internet access they must handle the additional
requirements for security, access through firewalls, etc., that the Web imposes.
Several vendors are adding JDBC technology-based drivers to their existing database
middleware products.
10. A native-protocol fully Java technology-enabled driver converts JDBC technology calls
into the network protocol used by DBMSs directly. This allows a direct call from the
client machine to the DBMS server and is a practical solution for Intranet access.
Since many of these protocols are proprietary the database vendors themselves will
be the primary source for this style of driver. Several database vendors have these in
progress.
Page 84 of 159
recommended one for server-side java development unless a type 2
driver
driver has considerable performance advantages.
Answer
Any amount of data can be stored there because the session is kept on the server side.
The only limitation is sessionId length, which shouldn't exceed ~4000 bytes - this limitation is
implied by HTTP header length limitation to 4Kb since sessionId may be stored in the cookie
or encoded in URL (using "URL rewriting") and the cookie specification says the size of
cookie as well as HTTP request (e.g. GET /document.html\n) cannot be longer then 4kb.
What is a Cookie?
A cookie is a text-only string that gets entered into the memory of your browser. This value of
a variable that a website sets. If the lifetime of this value is set to be longer than the time you
spend at that site, then this string is saved to file for future reference.
Answer
Sharing sessions between a servlet and a JSP page is straight forward. JSP makes it a little
easy by creating a session object and making it availabe already. In a servlet you would have
to do it yourself. This is how:
//create a session if one is not created already now
HttpSession session = request.getSession(true);
//assign the session variable to a value.
session.putValue("variable","value");
in the jsp page this is how you get the session value:
<%
session.getValue("varible");
%>
What is Session Tracking?
There are a number of problems that arise from the fact that HTTP is a "stateless" protocol.
In particular, when you are doing on-line shopping, it is a real annoyance that the Web server
can't easily remember previous transactions. This makes applications like shopping carts
very problematic: when you add an entry to your cart, how does the server know what's
already in your cart? Even if servers did retain contextual information, you'd still have
problems with e-commerce. When you move from the page where you specify what you want
to buy (hosted on the regular Web server) to the page that takes your credit card number and
shipping address (hosted on the secure server that uses SSL), how does the server
remember what you were buying?
There are three typical solutions to this problem.
11. Cookies. You can use HTTP cookies to store information about a shopping session,
and each subsequent connection can look up the current session and then extract
information about that session from some location on the server machine. This is an
excellent alternative, and is the most widely used approach. However, even though
servlets have a high-level and easy-to-use interface to cookies, there are still a
number of relatively tedious details that need to be handled:
• Extracting the cookie that stores the session identifier from the other cookies
(there may be many, after all),
• Setting an appropriate expiration time for the cookie (sessions interrupted by 24
hours probably should be reset), and
Page 85 of 159
• Associating information on the server with the session identifier (there may be
far too much information to actually store it in the cookie, plus sensitive data
like credit card numbers should never go in cookies).
12. URL Rewriting. You can append some extra data on the end of each URL that
identifies the session, and the server can associate that session identifier with data it
has stored about that session. This is also an excellent solution, and even has the
advantage that it works with browsers that don't support cookies or where the user
has disabled cookies. However, it has most of the same problems as cookies, namely
that the server-side program has a lot of straightforward but tedious processing to do.
In addition, you have to be very careful that every URL returned to the user (even via
indirect means like Location fields in server redirects) has the extra information
appended. And, if the user leaves the session and comes back via a bookmark or link,
the session information can be lost.
13. Hidden form fields. HTML forms have an entry that looks like the following: <INPUT
TYPE="HIDDEN" NAME="session" VALUE="...">. This means that, when the form is
submitted, the specified name and value are included in the GET or POST data. This
can be used to store information about the session. However, it has the major
disadvantage that it only works if every page is dynamically generated, since the
whole point is that each session has a unique identifier.
Servlets provide an outstanding technical solution: the HttpSession API. This is a high-level
interface built on top of cookies or URL-rewriting. In fact, on many servers, they use cookies
if the browser supports them, but automatically revert to URL-rewriting when cookies are
unsupported or explicitly disabled. But the servlet author doesn't need to bother with many of
the details, doesn't have to explicitly manipulate cookies or information appended to the URL,
and is automatically given a convenient place to store data that is associated with each
session.
2. The Session Tracking API
Using sessions in servlets is quite straightforward, and involves looking up the session object
associated with the current request, creating a new session object when necessary, looking
up information associated with a session, storing information in a session, and discarding
completed or abandoned sessions.
2.1 Looking up the HttpSession object associated with the current request.
This is done by calling the getSession method of HttpServletRequest. If this returns null, you can
create a new session, but this is so commonly done that there is an option to automatically
create a new session if there isn't one already. Just pass true to getSession. Thus, your first
step usually looks like this:
HttpSession session = request.getSession(true);
2.2 Looking up Information Associated with a Session.
HttpSession objects live on the server; they're just automatically associated with the requester
by a behind-the-scenes mechanism like cookies or URL-rewriting. These session objects
have a builtin data structure that let you store any number of keys and associated values. In
version 2.1 and earlier of the servlet API, you use getValue("key") to look up a previously stored
value. The return type is Object, so you have to do a typecast to whatever more specific type
of data was associated with that key in the session. The return value is null if there is no such
attribute. In version 2.2, getValue is deprecated in favor of getAttribute, both because of the
better naming match with setAttribute (the match for getValue is putValue, not setValue), and
because setAttribute lets you use an attached HttpSessionBindingListener to monitor values,
while putValue doesn't. Nevertheless, since few commercial servlet engines yet support
Page 86 of 159
version 2.2, I'll use getValue in my examples. Here's one representative example, assuming
ShoppingCart is some class you've defined yourself that stores information on items being
purchased.
HttpSession session = request.getSession(true);
ShoppingCart previousItems =
(ShoppingCart)session.getValue("previousItems");
if (previousItems != null) {
doSomethingWith(previousItems);
} else {
previousItems = new ShoppingCart(...);
doSomethingElseWith(previousItems);
}
In most cases, you have a specific attribute name in mind, and want to find the value (if any)
already associated with it. However, you can also discover all the attribute names in a given
session by calling getValueNames, which returns a String array. In version 2.2, use
getAttributeNames, which has a better name and which is more consistent in that it returns an
Enumeration, just like the getHeaders and getParameterNames methods of HttpServletRequest.
Although the data that was explicitly associated with a session is the part you care most
about, there are some other pieces of information that are sometimes useful as well.
• getId. This method returns the unique identifier generated for each session. It is
sometimes used as the key name when there is only a single value associated with a
session, or when logging information about previous sessions.
• isNew. This returns true if the client (browser) has never seen the session, usually
because it was just created rather than being referenced by an incoming client
request. It returns false for preexisting sessions.
• getCreationTime. This returns the time, in milliseconds since the epoch, at which the
session was made. To get a value useful for printing out, pass the value to the Date
constructor or the setTimeInMillis method of GregorianCalendar.
• getLastAccessedTime. This returns the time, in milliseconds since the epoch, at
which the session was last sent from the client.
• getMaxInactiveInterval. This returns the amount of time, in seconds, that a session
should go without access before being automatically invalidated. A negative value
indicates that the session should never timeout.
Page 87 of 159
range of factors, including the number of simultaneous users a cluster can support and the
time it takes to process a request.
Of the many methods available to balance a server load, the main two are:
• DNS round robin and
• Hardware load balancers.
DNS Round Robin
As most readers of ONJava probably know, the Domain Name Server (DNS) database maps
host names to their IP addresses.
When you enter a URL in a browser (say, www.loadbalancedsite.com), the browser sends a
request to the DNS asking it to return the IP address of the site. This is called the DNS
lookup. After the Web browser gets the IP address for that site, it contacts the site using the
IP address, and displays the page for you.
The DNS server generally contains a single IP address mapped to a particular site name. In
our fictional example, our site www.loadbalancedsite.com maps to the IP address
203.24.23.3
To balance server loads using DNS, the DNS server maintains several different IP addresses
for a site name. The multiple IP addresses represent the machines in the cluster, all of which
map to the same single logical site name. Using our example, www.loadbalancedsite.com
could be hosted on three machines in a cluster with the following IP addresses:
203.34.23.3
203.34.23.4
203.34.23.5
In this case, the DNS server contains the following mappings:
www.loadbalancedsite.com 203.34.23.3
www.loadbalancedsite.com 203.34.23.4
www.loadbalancedsite.com 203.34.23.5
When the first request arrives at the DNS server, it returns the IP address 203.34.23.3, the
first machine. On the second request, it returns the second IP address: 203.34.23.4. And so
on. On the fourth request, the first IP address is returned again.
Using the above DNS round robin, all of the requests to the particular site have been evenly
distributed among all of the machines in the cluster. Therefore, with the DNS round robin
method of load balancing, all of the nodes in the cluster are exposed to the net.
Advantages of DNS Round Robin
The main advantages of DNS round robin are that it's cheap and easy:
• Inexpensive and easy to set up. The system administrator only needs to make a few
changes in the DNS server to support round robin, and many of the newer DNS
servers already include support. It doesn't require any code change to the Web
application; in fact, Web applications aren't aware of the load-balancing scheme in
front of it.
• Simplicity. It does not require any networking experts to set up or debug the system
in case a problem arises.
Disadvantages of DNS Round Robin
Two main disadvantages of this software-based method of load balancing are that it offers no
real support for server affinity and doesn't support high availability.
Page 88 of 159
• No support for server affinity. Server affinity is a load-balancing system's ability to
manage a user's requests, either to a specific server or any server, depending on
whether session information is maintained on the server or at an underlying, database
level.
Without server affinity, DNS round robin relies on one of three methods devised to
maintain session control or user identity to requests coming in over HTTP, which is a
stateless protocol.
• cookies
• hidden fields
• URL rewriting
When a user makes a first request, the Web server returns a text-based token
uniquely identifying that user. Subsequent requests include this token using either
cookies, URL rewriting, or hidden fields, allowing the server to appear to maintain a
session between client and server. When a user establishes a session with one
server, all subsequent requests usually go to the same server.
The problem is that the browser caches that server's IP address. Once the cache
expires, the browser makes another request to the DNS server for the IP address
associated with the domain name. If the DNS server returns a differnt IP address, that
of another server in the cluster, the session information is lost.
• No support for high availability. Consider a cluster of n nodes. If a node goes down,
then every nth request to the DNS server directs you to the dead node. An advanced
router solves this problem by checking nodes at regular intervals, detecting failed
nodes and removing them from the list, so no requests go to them. However, the
problem still exists if the node is up but the Web application running on the node goes
down.
Changes to the cluster take time to propagate through the rest of the Internet. One
reason is that many large organizations -- ISPs, corporations, agencies -- cache their
DNS requests to reduce network traffic and request time. When a user within these
organizations makes a DNS request, it's checked against the cache's list of DNS
names mapped to IP addresses. If it finds an entry, it returns the IP address to the
user. If an entry is not found in its local cache, the ISP sends this DNS request to the
DNS server and caches response.
When a cached entry expires, the ISP updates its local database by contacting other
DNS servers. When your list of servers changes, it can take a while for the cached
entries on other organizations' networks to expire and look for the updated list of
servers. During that period, a client can still attempt to hit the downed server node, if
that client's ISP still has an entry pointing to it. In such a case, some users of that ISP
couldn't access your site on their first attempt, even if your cluster has redundant
servers up and running.
This is a bigger problem when removing a node than when adding one. When you
drop a node, a user may be trying to hit a non-existing server. When you add one, that
server may just be under-utilized until its IP address propogates to all the DNS
servers.
Although this method tries to balance the number of users on each server, it doesn't
necessarily balance the server load. Some users could demand a higher load of
activity during their session than users on another server, and this methodology
cannot guard against that inequity.
WebLogic performance-enhancing features
WebLogic has several features that enhance performance for JDBC applications.
Page 89 of 159
Connection Pools
Establishing a JDBC connection with a DBMS can be very slow. If your application requires
database connections that are repeatedly opened and closed, this can become a significant
performance issue; creating a database connection can be exponentially more expensive
than any other. WebLogic connection pools offer an efficient solution to this problem.
When the WebLogic Server is started, a connection pool is created containing connections
that are independent of any single client. Unlike applications that open and close a new
connection for each query, a connection from a connection pool may be used by any client;
and its lifetime is not tied in any way to the lifetime of a client. When a client closes a
connection from a connection pool, the connection is returned to the pool and becomes
available again for other clients, but the connection itself is not closed. Since the connections
already exist, there is no overhead involved with opening and closing the connection, which
improves overall performance.
How many connections should you create in the pool? A connection pool can grow and
shrink according to a configured interval, up to a maximum number of connections. The best
performance will always be when the connection pool is just large enough to service users
without waits.
Page 90 of 159
By using the above methods, a WebLogic JDBC query for 100 rows will make only 4 calls
from the client to WebLogic, and for only one of those will WebLogic actually go all the way to
the DBMS for data.
Note: You must turn off RowCaching if any ResultSets will contain Blobs or Clobs.
Page 91 of 159
This will return the number of rows the original query would have returned. The actual count
may change when the query is issued if there has been any other DBMS activity which alters
the relevant data.
You should be aware, however, that this is a resource-intensive operation. Depending on the
original query, the DBMS will have to perform nearly as much work to count the rows as it will
to send them.
Your application should tailor its queries to be as specific as possible about what data it
actually wants. Tricks include first selecting into temporary tables, returning only the count,
and then sending a refined second query to return only a subset of the rows in the temporary
table.
Learning to select only the data you really want at the client is crucial. Some applications
ported from ISAM will unnecessarily send a query selecting all the rows in a table when only
the first few rows are really wanted. Some applications use a 'sort by' clause to get the rows
they want to come back first. Database queries like this cause unnecessary degradation of
performance.
Proper use of SQL can avoid these performance problems. For example, if you only want
data about the top 3 earners on the payroll, the proper way to make this query is with a
correlated subquery. Here is the entire table, which is returned by the SQL
select * from payroll;
NAME SALARY
Joe 1
Mike 2
Sam 3
Tom 4
Jan 5
Ann 6
Sue 7
Hal 8
May 8
Here is the much smaller result returned by a correlated subquery:
NAME SALARY
Sue 7
Hal 8
May 8
select p.name, p.salary from payroll p
where 3 >= (select count(*) from payroll pp
where pp.salary >= p.salary);
This query will return only 3 rows, with the name and salary of the top 3 earners. It scans
through the payroll table, and for every row, it goes through the whole payroll table again in
an inner loop to see how many salaries are higher than the current row of the outer scan.
This may look complicated, but DBMSes are designed to use SQL efficiently for this type of
operation.
4. Make transactions single-batch wherever possible
Whenever possible, collect a set of data operations and submit an update transaction in one
statement in the form:
BEGIN TRANSACTION
UPDATE TABLE1...
INSERT INTO TABLE2
DELETE TABLE3
Page 92 of 159
COMMIT
This approach results in better performance than using separate statements and commits.
Even with conditional logic and temporary tables in the batch, it is preferable because the
DBMS will obtain all the locks necessary on the various rows and tables, and will use them
and release them in one step. Using separate statements and commits results in many more
client-to-DBMS transmissions and holds the locks in the DBMS for much longer. These locks
will block out other clients from accessing this data, and, depending on whether different
updates can alter tables in different orders, may cause deadlocks.
Warning: If any individual statement in the above transaction might fail, due, for instance, to
violating a unique key constraint, you should put in conditional SQL logic to detect any
statement failure and rollback the transaction rather than commit. If, in the above example,
the insert failed, most DBMSes will send back an error message about the failed insert, but
will behave as if you got the message between the second and third statement, and decided
to commit anyway! MS SQLServer has a nice connection option enabled by executing the
SQL set xact_abort on, which will automatically roll back the transaction if any statement
fails.
5. Never have a DBMS transaction span user input
If an application sends a 'BEGIN TRAN' and some SQL which locks rows or tables for an
update, do not write your application so that it must wait on the user to press a key before
committing the transaction. That user may go to lunch first and lock up a whole DBMS table
until he comes back.
If user input is needed to form or complete a transaction, use optimistic locking. Briefly,
optimistic locking employs timestamps and triggers (some DBMSes will generate these
automatically with tables set up for it) in queries and updates. Queries select data with
timestamp values and prepare a transaction based on that data, without locking the data in a
transaction.
When an update transaction is finally defined by the user input, it is sent as a single
submission that includes timestamped safeguards to make sure the data is the same as
originally fetched. A successful transaction will automatically update the relevant timestamps
for changed data. If any interceding update from another client has altered any of the data on
which the current transaction is based, the timestamps will have changed, and the current
transaction will be rejected. Most of the time, no relevant data has been changed so
transactions usually succeed. When one a transaction fails, the application can refetch the
updated data to present to the user to reform the transaction if desired.
Refer to your DBMS documents for a full description of this technique.
6. Use in-place updates
Changing a data row in place is much faster than moving a row, which may be required if the
update requires more space than the table design can accommodate. If you design your
rows to have the space they need initially, updates will be faster. The trade-off is that your
table may require more disk space but may run faster. Since disk space is cheap, using a
little more of it can be a worthwhile investment to improve performance.
7. Keep your operational data set as small as possible
Some applications store operational data in the same table as historical data. Over time and
with accumulation of this historical data, all operational queries have to read through lots of
useless (on a day-to-day basis) data to get to the more current data. Move non-current data
to other tables and do joins to these tables for the rarer historical queries. If this can't be
done, index and cluster your table so that the most frequently used data is logically and
physically localized.
Page 93 of 159
8. Use pipelining and parallelism
DBMSes are designed to work best when very busy with lots of different things to do. The
worst way to use a DBMS is as dumb file storage for one big single-threaded application. If
you can design your application and data to support lots of parallel processes working on
easily distinguished subsets of the work, your application will be much faster. If there are
multiple steps to processing, try to design your application so that subsequent steps can start
working on the portion of data that any prior process has finished, instead of having to wait
until the prior process is complete. This may not always be possible, but you can dramatically
improve performance by designing your program with this in mind.
9. Choose the right driver for your application
There are several possible choices for a JDBC driver. The Type 2 WebLogic jDriver for
Oracle uses a native layer and is usually faster than a pure-Java Type 4 driver, although this
difference is narrowing as JITs continue to increase their performance. A Type 3 driver (also
pure-Java) uses no native methods, and requires no client-side installation of vendor
libraries. For an overview see WebLogic's whitepaper Choosing a Java Database
Connectivity driver.
Page 94 of 159
1. What's the JDBC 3.0 API?
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.
2. Does the JDBC-ODBC Bridge support the new features in the JDBC 3.0 API?
The JDBC-ODBC Bridge provides a limited subset of the JDBC 3.0 API.
Use of the JDBC-ODBC bridge from an untrusted applet running in a browser, such as
Netscape Navigator, isn't allowed. 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. Remember 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.
A good way 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 connections that can participate in
distributed transactions, you use the XADataSource.setLogWriter method.)
5. How can I use the JDBC API to access a desktop database like Microsoft Access
over the network?
Most desktop databases currently require a JDBC solution that uses ODBC underneath. This
is because the vendors of these database products haven't implemented all-Java JDBC
drivers.
Page 95 of 159
The best approach is to use a commercial JDBC driver that supports ODBC and the
database you want to use. See the JDBC drivers page for a list of available JDBC drivers.
The JDBC-ODBC bridge from Sun's Java Software does not provide network access to
desktop databases by itself. The JDBC-ODBC bridge loads ODBC as a local DLL, and
typical ODBC drivers for desktop databases like Access aren't networked. The JDBC-ODBC
bridge can be used together with the RMI-JDBC bridge, however, to access a desktop
database like Access over the net. This RMI-JDBC-ODBC solution is free.
See our web page on JDBC technology-enabled drivers for a current listing.
See the JDBC technology home page for links to information about JDBC technology. This
page links to information about features and benefits, a list of new features, a section on
getting started, online tutorials, a section on driver requirements, and other information in
addition to the specifications and javadoc documentation.
8. Are there any ODBC drivers that do not work with the JDBC-ODBC Bridge?
Most ODBC 2.0 drivers should work with the Bridge. Since there is some variation in
functionality between ODBC drivers, the functionality of the bridge may be affected. The
bridge works with popular PC databases, such as Microsoft Access and FoxPro.
"No suitable driver" is an error that usually occurs during a call to the
DriverManager.getConnection method. The cause can be failing to load the appropriate
JDBC drivers before calling the getConnection method, or it can be specifying an invalid
JDBC URL--one that isn't recognized by your JDBC driver. Your best bet is to check the
documentation for your JDBC driver or contact your JDBC driver vendor if you suspect that
the URL you are specifying is not being recognized by your JDBC driver.
In addition, when you are using the JDBC-ODBC Bridge, this error can occur if one or more
the the shared libraries needed by the Bridge cannot be loaded. If you think this is the cause,
check your configuration to be sure that the shared libraries are accessible to the Bridge.
This problem can be caused by running a JDBC applet in a browser that supports the JDK
1.0.2, such as Netscape Navigator 3.0. The JDK 1.0.2 does not contain the JDBC API, so the
DriverManager class typically isn't found by the Java virtual machine running in the browser.
Page 96 of 159
Here's a solution that doesn't require any additional configuration of your web clients.
Remember that classes in the java.* packages cannot be downloaded by most browsers for
security reasons. Because of this, many vendors of all-Java JDBC drivers supply versions of
the java.sql.* classes that have been renamed to jdbc.sql.*, along with a version of their
driver that uses these modified classes. If you import jdbc.sql.* in your applet code instead of
java.sql.*, and add the jdbc.sql.* classes provided by your JDBC driver vendor to your
applet's codebase, then all of the JDBC classes needed by the applet can be downloaded by
the browser at run time, including the DriverManager class.
This solution will allow your applet to work in any client browser that supports the JDK 1.0.2.
Your applet will also work in browsers that support the JDK 1.1, although you may want to
switch to the JDK 1.1 classes for performance reasons. Also, keep in mind that the solution
outlined here is just an example and that other solutions are possible.
11. How do I retrieve a whole row of data at once, instead of calling an individual
ResultSet.getXXX method for each column?
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. It is unlikely that
this is the cause of a 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. We
welcome input from developers on this issue.
12. Why does the ODBC driver manager return 'Data source name not found and no
default driver specified Vendor: 0'
This type of error occurs during an attempt to connect to a database with the bridge. First,
note that the error is coming from the ODBC driver manager. This indicates that the bridge-
which is a normal ODBC client-has successfully called ODBC, so the problem isn't due to
native libraries not being present. In this case, it appears that the error is due to the fact that
an ODBC DSN (data source name) needs to be configured on the client machine.
Developers often forget to do this, thinking that the bridge will magically find the DSN they
configured on their remote server machine
Back to top
13. Are all the required JDBC drivers to establish connectivity to my database part of
the JDK?
No. There aren't any JDBC technology-enabled drivers bundled with the JDK 1.1.x or Java 2
Platform releases other than the JDBC-ODBC Bridge. So, developers need to get a driver
and install it before they can connect to a database. We are considering bundling JDBC
technology- enabled drivers in the future.
No. The JDBC-ODBC Bridge does not support concurrent access from different threads. The
JDBC-ODBC 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. In addition, deadlocks can occur between locks held in the database and
Page 97 of 159
the semaphore used by the Bridge. We are thinking about removing the synchronized
methods in the future. They were added originally to make things simple for folks writing Java
programs that use a single-threaded ODBC driver.
15. Does the JDBC-ODBC Bridge support multiple concurrent open statements per
connection?
No. You can open only one Statement object per connection when you are using the JDBC-
ODBC Bridge.
16. Why can't I invoke the ResultSet methods afterLast and beforeFirst when the
method next works?
You are probably using a driver implemented for the JDBC 1.0 API. You need to upgrade to a
JDBC 2.0 driver that implements scrollable result sets. Also be sure that your code has
created scrollable result sets and that the DBMS you are using supports them.
17. How can I retrieve a String or other object type without creating a new object each
time?
Creating and garbage collecting potentially large numbers of objects (millions) unnecessarily
can really hurt performance. It may be better to provide a way to retrieve data like strings
using the JDBC API without always allocating a new object.
We are studying this issue to see if it is an area in which the JDBC API should be improved.
Stay tuned, and please send us any comments you have on this question.
18. There is a method getColumnCount in the JDBC API. Is there a similar method to
find the number of rows in a result set?
No, but it is easy to find the number of rows. If you are using a scrollable result set, rs, you
can call the methods rs.last and then rs.getRow to find out how many rows rs has. If the
result is not scrollable, you can either count the rows by iterating through the result set or get
the number of rows by submitting a query with a COUNT column in the SELECT clause.
19. I would like to download the JDBC-ODBC Bridge for the Java 2 SDK, Standard
Edition (formerly JDK 1.2). I'm a beginner with the JDBC API, and I would like to start
with the Bridge. How do I do it?
The JDBC-ODBC Bridge is bundled with the Java 2 SDK, Standard Edition, so there is no
need to download it separately.
No, this is just one of many possible solutions. We recommend using a pure Java JDBC
technology-enabled driver, type 3 or 4, in order to get all of the benefits of the Java
programming language and the JDBC API.
21. Once I have the Java 2 SDK, Standard Edition, from Sun, what else do I need to
connect to a database?
Page 98 of 159
You still need to get and install a JDBC technology-enabled driver that supports the database
that you are using. There are many drivers available from a variety of sources. You can also
try using the JDBC-ODBC Bridge if you have ODBC connectivity set up already. The Bridge
comes with the Java 2 SDK, Standard Edition, and Enterprise Edition, and it doesn't require
any extra setup itself. The Bridge is a normal ODBC client. Note, however, that you should
use the JDBC-ODBC Bridge only for experimental prototyping or when you have no other
driver available.
XML
Q. What is XML?
A. XML is an activity of the World Wide Web Consortium (W3C). The XML
development effort started in 1996.
A. XML promises to simplify and lower the cost of data interchange and
publishing in a Web environment. XML is a text-based syntax that is readable by
both computer and humans. XML offers data portability and reusability across
different platforms and devices. It is also flexible and extensible, allowing new
tags to be added without breaking an existing document structure. Based on
Unicode, XML provides global language support.
A. XML and the Java technology are complementary. Java technology provides
Page 99 of 159
the portable, maintainable code to process portable, reusable XML data. In
addition, XML and Java technology have a number of shared features that make
them the ideal pair for Web computing, including being industry standards,
platform-independence, extensible, reusable, Web-centric, and internationalized.
A. The Java Technology & XML Documentation page has a comprehensive list of
all documentation related to Java Technology and XML available on this website.
Q. Are there other Sun hosted XML mailing lists I can subscribe to?
A. For general discussion about topics related to XML technologies in the Java
platform, subscribe to xml-interest@java.sun.com.
Back to Top
The Java API for XML Processing, or "JAXP" for short, enables applications to
parse and transform XML documents using an API that is independent of a
particular XML processor implementation. JAXP also provides a pluggability
feature which enables applications to easily switch between particular XML
processor implementations.
The reason for the existance of JAXP is to facilitate the use of XML on the Java
platform. For example, current APIs such as DOM Level 2 do not provide a
method to bootstrap a DOM Document object from an XML input document,
JAXP does. (When DOM Level 3 provides this functionality, a new version of the
JAXP specification will probably support the new Level 3 scheme also.) Other
parts of JAXP such as the javax.xml.transform portion do not have any other
equivalent APIs that are XSLT processor independent.
Back to Top
A. The Java Architecture for XML Binding (JAXB) simplifies the creation and
maintenance of XML-enabled Java applications. JAXB provides a binding
compiler and a runtime framework to support a two-way mapping between XML
documents and Java objects. The binding compiler translates W3C XML Schema
into one or more Java classes without requiring the developer to write complex
parsing code. The schema-derived classes and binding framework enable error
and validity checking of incoming and outgoing XML documents, thereby making
it possible to ensure that only valid, error-free messages are accepted,
processed, and generated by a system. For more information, see the Reference
Implementation and the Public Draft Specification, both available for download
from the JAXB homepage.
Q. What is the difference between JAXB, SAX, and DOM? Which one
should I use?
A JAXB application can perform structure and content validation with Java
classes that it generates from a schema. A JAXB application builds an in-
A. To build a JAXB application, start with an XML schema. The beta release
requires that the schema language be W3C 2001 Recommendation for XML
Schema.
After obtaining an XML Schema, you build and use a JAXB application by
performing these steps:
1. Generate the Java source files by submitting the XML Schema to the
binding compiler.
You can use custom binding declarations to override the default binding of
XML Schema components to Java representations
3. With the classes and the binding framework, write Java applications that:
Build object trees representing XML data that is valid against the
XML Schema by either unmarshalling the data from a document or
instantiating the classes you created.
A. JAXB is being developed through the Java Community Process (JCP) with an
expert group consisting of IBM, Software AG, BEA Systems, Hewlett-Packard,
TIBCO Software Inc., Oracle, Fujitsu Limited, Breeze Factor LLC, Macromedia,
Inc. and Intalio, Inc. Sun is an active member of the W3C XML Schema Working
Group and is also working with other industry consortia such as OASIS and
A. For a higher-level explanation of JAXB, refer to the JAXB chapters in the Java
Web Services Tutorial. Also note that a detailed user's guide is included as part
of the JAXB distribution. For a more technical and detailed description of JAXB,
see the the latest version of the Specification, which you can download from the
JAXB homepage. Please note that the Specification is in Adobe Acrobat PDF
format. Download Adobe Acrobat for free.
Back to Top
A: The Java API for XML Messaging (JAXM) is an API designed specifically for
the exchange of XML business documents over the Internet. Examples of XML
documents that might typically be exchanged are purchase orders, order
confirmations, and invoices. You can send non-XML data by adding attachments
to your message.
A: JAXM is based on the Simple Object Access Protocol (SOAP) 1.1 and SOAP
with Attachments specifications. JAXM also allows the implementation of
standard protocols on top of the SOAP implementation, such as SOAP-RP or the
ebXML Transport, Routing & Packaging V1.0 - Message Service Specification.
A: No, you are free to use the Java 2 Platform, Standard Edition (J2SE) as well
as the Java 2 Platform, Enterprise Edition (J2EE). A stand-alone client (a client
that does not use a messaging provider) can use the J2SE platform to send
request-response messages to Web services that process request-response
messages. This requires no deployment or configuration from the client, so it is
easy to do.
A: No. You need to use a messaging provider only when your application
requires one-way (asynchronous) messaging. In this type of messaging, a
message is sent to a recipient as one operation, and the recipient responds at
some later time in a different operation. If you application uses a request-
response style of messaging, in which the response to a message is sent back
as part of the same operation, you do not need a messaging provider. When you
do not use a messaging provider, you use a SOAPConnection object, which
supports the simpler request-response messaging model.
A: Yes, you can use ebXML headers if you use an ebXML profile that is
implemented on top of SOAP. A profile is a standard protocol, such as ebXML
TRP or SOAP-RP, that works on top of SOAP to give you added functionality.
You need to use a messaging provider that supports the profile, and you need to
arrange with your recipients to use the same profile.
Back to Top
A. The Java API for XML Registries (JAXR) API provides a uniform and standard
Java API for accessing different kinds of XML Registries. XML registries are an
enabling infrastructure for building, deployment, and discovery of Web services.
Q. What is the relationship between the JAXR API and other XML APIs?
Implementations of JAXR providers may use the Java API for XML Messaging
(JAXM) API for communication between JAXR providers and registry providers
that export an XML Messaging-based interface (for example, ebXML TRP).
The Java API for XML Processing (JAXP) and Java Architecture for XML Binding
(JAXB) may be used by implementers of JAXR providers and JAXR clients for
processing XML content that is submitted to or retrieved from the Registry.
Q. Why do we need a new JAXR API when we have the Java Naming and
Directory Interface (JNDI)?
A. The JNDI API was designed with a very different set of requirements from the
JAXR API. Both are abstraction APIs over existing specifications. However, the
abstraction in directory services differs considerably from that of XML Registries
used for publishing and discovery of Web services. The JAXR API needs richer
metadata capabilities for classification and association, as well as richer query
capabilities.
Q. Would it not be better to have enhanced the JNDI API with the added
functionality of the JAXR API?
Q. Why does the JAXR API not use UDDI terms and concepts?
A. The JAXR API is not specific to UDDI or any other registry specification. It is
an abstraction API that covers multiple specifications. It is designed to enable
developer choice in the use of a Web service registry and/or repository. The
JAXR API uses UDDI terms and concepts when they fit the JAXR information
model (for example, Service, ServiceBinding, and method names in
BusinessQueryManager and BusinessLifeCycleManager).
Q. Why did the JAXR information model use the ebXML Registry
Information Model as its basis rather than the UDDI data structures?
A. The JAXR API is designed to support multiple registries. The ebXML Registry
Information Model is more generic and extensible than the UDDI data structures.
Because of this characteristic, it was possible to extend the ebXML Registry
Information Model to satisfy the needs of UDDI and other registries.
Q. Why was the JAXR information model not designed from the ground
up?
A. Information models take time to develop. It was easier to start with an existing
information model and improve upon it.
Back to Top
A. The Java API for XML-Based RPC (JAX-RPC) enables Java technology
developers to build Web applications and Web services incorporating XML-
based RPC functionality according to the SOAP (Simple Object Access Protocol)
1.1 specification.
A. RPC stands for remote procedure call, a mechanism that allows a client to
execute procedures on other systems. The RPC mechanism is often used in a
distributed client/server model. The server defines a service as a collection of
procedures that may be called by remote clients.
1. Synchronous Request-Response: The client invokes a remote procedure and blocks until it
receives a return or an exception.
2.
3. One-Way RPC: The client invokes a remote procedure but it does not block or wait until it receives
a return. The runtime system for the JAX-RPC client may throw an exception.
4.
5. Non-Blocking RPC Invocation: The client invokes a remote procedure and continues processing in
the same thread without waiting for a return. Later, the client processes the remote method return
by blocking for the receive or polling for the return.
6.
A. The xrpcc tool does in fact generate the WSDL file, but due to a bug it gets
deleted along with the source files if the -keep option is not specified. You can
use the -keep option which will cause xrpcc to not delete the WSDL or .java
source files. If you also use the -s sourcepath option, all of the source files will be
Back to Top
A. The Java 2 Platform, Enterprise Edition (J2EE) promotes the use of XML for
data messaging between loosely-coupled business systems. The J2EE
reference implementation includes the Java API for XML Parsing (JAXP).
JavaServer Pages (JSP) can generate and consume XML between multi-tier
servers or between server and client. Java Message Service (JMS) provides an
asynchronous transport mechanism for XML data messaging. Enterprise
JavaBeans (EJB) offers a robust, synchronous transport mechanism by allowing
a business service object to be invoked by XML tags. EJB also uses XML to
describe its deployment properties, such as transactions and security.
A. JSP pages enables the authoring of XML pages. XML pages can be
generated using JSP pages, which include elements to produce the dynamic
portions of the document. The JSP specification includes a powerful tag
extension mechanism that can be used to perform XML-based operations, such
as applying an XSLT transformation to an XML document.
Back to Top
JSP
What is JavaServer Pages technology?
JavaServer Pages (JSP) technology provides a simplified, fast way to create web pages that display
dynamically-generated content. The JSP specification, developed through an industry-wide initiative led
by Sun Microsystems, defines the interaction between the server and the JSP page, and describes the
format and syntax of the page.
JSP pages use XML tags and scriptlets written in the Java programming language to encapsulate the
logic that generates the content for the page. It passes any formatting (HTML or XML) tags directly back
to the response page. In this way, JSP pages separate the page logic from its design and display.
JSP technology is part of the Java technology family. JSP pages are compiled into servlets and may call
JavaBeans components (beans) or Enterprise JavaBeans components (enterprise beans) to perform
processing on the server. As such, JSP technology is a key component in a highly scalable architecture
for web-based applications.
What is a servlet?
A servlet is a program written in the Java programming language that runs on the server, as opposed to
the browser (applets). Detailed information can be found at http://java.sun.com/products/servlet.
JSP pages are compiled into servlets, so theoretically you could write servlets to support your web-based
applications. However, JSP technology was designed to simplify the process of creating pages by
separating web presentation from web content. In many applications, the response sent to the client is a
combination of template data and dynamically-generated data. In this situation, it is much easier to work
with JSP pages than to do everything with servlets.
Where can I get the most current version of the JSP specification?
The JavaServer Pages 2.0 specification is available for download from here.
How does the JSP specification relate to the Java 2 Platform, Enterprise Edition?
The JSP 2.0 specification is an important part of the Java 2 Platform, Enterprise Edition 1.4. Using JSP
and Enterprise JavaBeans technologies together is a great way to implement distributed enterprise
applications with web-based front ends.
There are a number of JSP technology implementations for different web servers. The latest information
on officially-announced support can be found at http://java.sun.com/products/jsp/industry.html.
The J2EE SDK is a reference implementation of the JavaTM 2 Platform, Enterprise Edition. Sun adapts
and integrates the Tomcat JSP and Java Servlet implementation into the J2EE SDK. The J2EE SDK can
be used as a development enviroment for applications prior to their deployment and distribution.
Tomcat a free, open-source implementation of Java Servlet and JavaServer Pages technologies
developed under the Jakarta project at the Apache Software Foundation, can be downloaded from
http://jakarta.apache.org. Tomcat is available for commercial use under the ASF license from the Apache
web site in both binary and source versions. An implementation of JSP technology is part of the J2EE
SDK.
JSP technology is the result of industry collaboration and is designed to be an open, industry-standard
method supporting numerous servers, browsers and tools. JSP technology speeds development with
reusable components and tags, instead of relying heavily on scripting within the page itself. All JSP
implementations support a Java programming language-based scripting language, which provides
inherent scalability and support for complex operations.
The first place to check for information on JSP technology is http://java.sun.com/products/jsp/. This site
includes numerous resources, as well as pointers to mailing lists and discussion groups for JSP
technology-related topics.
A JSP page is a page created by the web developer that includes JSP technology-specific and custom
tags, in combination with other static (HTML or XML) tags. A JSP page has the extension .jsp or .jspx; this
signals to the web server that the JSP engine will process elements on this page. Using the web.xml
deployment descriptor, additional extensions can be associated with the JSP engine.
A JSP engine interprets tags, and generates the content required - for example, by calling a bean,
accessing a database with the JDBC API or including a file. It then sends the results back in the form of
an HTML (or XML) page to the browser. The logic that generates the content is encapsulated in tags and
beans processed on the server.
Does JSP technology require the use of other Java platform APIs?
JSP pages are typically compiled into Java platform servlet classes. As a result, JSP pages require a Java
virtual machine that supports the Java platform servlet specification.
Pages built using JSP technology are typically implemented using a translation phase that is performed
once, the first time the page is called. The page is compiled into a Java Servlet class and remains in
server memory, so subsequent calls to the page have very fast response times.
The syntax card and reference can be viewed or downloaded from our website.
Yes, the JSP specification does support creation of XML documents. For simple XML generation, the XML
tags may be included as static template portions of the JSP page. Dynamic generation of XML tags
occurs through bean components or custom tags that generate XML output. See the white paper
Developing XML Solutions with JavaServer Pages Technology (PDF) for details.
The JSP 2.0 specification describes a mapping between JSP pages and XML documents. The mapping
enables the creation and manipulation of JSP pages using XML tools.
The JSP specification includes standard tags for bean use and manipulation. The useBean tag creates an
instance of a specific JavaBeans class. If the instance already exists, it is retrieved. Otherwise, it is
created. The setProperty and getProperty tags let you manipulate properties of the given object. These
tags are described in more detail in the JSP specification and tutorial.
J2EE
Q: What is the Java 2 Platform, Enterprise Edition (J2EE)?
The Java 2 Platform, Enterprise Edition (J2EE) is a set of coordinated specifications and
Complete Web services support. The J2EE platform provides a framework for developing
and
deploying web services on the Java platform. The Java API for XML-based RPC (JAX-RPC)
enables Java technology developers to develop SOAP based interoperable and portable web
services. Developers use the standard JAX-RPC programming model to develop SOAP
based web
service clients and endpoints. A web service endpoint is described using a Web Services
Description Language (WSDL) document. JAX-RPC enables JAX-RPC clients to invoke web
services
developed across heterogeneous platforms. In a similar manner, JAX-RPC web service
endpoints
can be invoked by heterogeneous clients. For more info, see
http://java.sun.com/webservices/.
Faster solutions delivery time to market. The J2EE platform uses "containers" to simplify
development. J2EE containers provide for the separation of business logic from resource
and
lifecycle management, which means that developers can focus on writing business logic --
their value add -- rather than writing enterprise infrastructure. For example, the
Enterprise JavaBeans (EJB) container (implemented by J2EE technology vendors) handles
distributed communication, threading, scaling, transaction management, etc. Similarly, Java
Servlets simplify web development by providing infrastructure for component,
communication,
and session management in a web container that is integrated with a web server.
Freedom of choice. J2EE technology is a set of standards that many vendors can implement.
The vendors are free to compete on implementations but not on standards or APIs. Sun
supplies a comprehensive J2EE Compatibility Test Suite (CTS) to J2EE licensees. The J2EE
CTS
helps ensure compatibility among the application vendors which helps ensure portability for
the applications and components written for the J2EE platform. The J2EE platform brings
Write Once, Run Anywhere (WORA) to the server.
Simplified connectivity. J2EE technology makes it easier to connect the applications and
systems you already have and bring those capabilities to the web, to cell phones, and to
devices. J2EE offers Java Message Service for integrating diverse applications in a loosely
By offering one platform with faster solution delivery time to market, freedom of choice,
and simplified connectivity, the J2EE platform helps IT by reducing TCO and simultaneously
avoiding single-source for their enterprise software needs.
Q: Can the J2EE platform interoperate with other WS-I implementations?
The primary technologies in the J2EE platform are: Java API for XML-Based RPC (JAX-
RPC),
JavaServer Pages, Java Servlets, Enterprise JavaBeans components, J2EE Connector
Architecture, J2EE Management Model, J2EE Deployment API, Java Management
Extensions (JMX),
J2EE Authorization Contract for Containers, Java API for XML Registries (JAXR), Java
Message
Service (JMS), Java Naming and Directory Interface (JNDI), Java Transaction API (JTA),
CORBA, and JDBC data access API.
The Java 2 Platform, Enterprise Edition version 1.4 features complete Web services support
through the new JAX-RPC 1.1 API, which supports service endpoints based on servlets and
enterprise beans. JAX-RPC 1.1 provides interoperability with Web services based on the
WSDL
and SOAP protocols. The J2EE 1.4 platform also supports the Web Services for J2EE
specification (JSR 921), which defines deployment requirements for Web services and
utilizes
the JAX-RPC programming model. In addition to numerous Web services APIs, J2EE 1.4
platform
also features support for the WS-I Basic Profile 1.0. This means that in addition to
platform independence and complete Web services support, J2EE 1.4 offers platform Web
services interoperability.
The J2EE 1.4 platform also introduces the J2EE Management 1.0 API, which defines the
information model for J2EE management, including the standard Management EJB (MEJB).
The
J2EE Management 1.0 API uses the Java Management Extensions API (JMX). The J2EE 1.4
platform
also introduces the J2EE Deployment 1.1 API, which provides a standard API for deployment
of
J2EE applications.
The J2EE platform now makes it easier to develop web front ends with enhancements to
with the introduction of a simple expression language, tag files, and a simpler tag
extension API, among other features. This makes it easier than ever for developers to build
JSP-enabled pages, especially those who are familiar with scripting languages.
Other enhancements to the J2EE platform include the J2EE Connector Architecture, which
provides incoming resource adapter and Java Message Service (JMS) pluggability. New
features
in Enterprise JavaBeans (EJB) technology include Web service endpoints, a timer service,
and
enhancements to EJB QL and message-driven beans. The J2EE 1.4 platform also includes
enhancements to deployment descriptors. They are now defined using XML Schema which
can also
be used by developers to validate their XML structures.
The J2EE 1.4 specification is final and you can use the J2EE 1.4 SDK to deploy applications
today. However, for improved reliability,scability, and performance, it is recommended that
you deploy your applications on J2EE 1.4 commercial implementations that will be available
early in 2004. If you want to deploy your application before 2004, and
reliability,scability, and performance are critical, you should consider using a high
performance application server that supports J2EE v1.3 such as the Sun Java System
Application Server 7. Many application server vendors are expected to release J2EE platform
Q: Can applications written for the J2EE platform v1.3 run in a J2EE platform v1.4
implementation?
J2EE applications that are written to the J2EE 1.3 specification will run in a J2EE 1.4
implementation. Backwards compatibility is a requirement of the specification.
Q: How is the J2EE architecture and the Sun Java Enterprise System related?
The J2EE architecture is the foundation of the Sun Java System Application Server, a
component of the Sun Java Enterprise System. The Java System Application Server in the
current Sun Java Enterprise System is based on the J2EE platform v1.3, with additional
support for Web services. Developers familiar with J2EE technology can easily apply their
skills to building applications, including Web services applications, using the Sun Java
Enterprise System. For more information, see the Sun Java Enterprise System Web site.
For more information about the J2EE platform and how to get the specification, see
http://java.sun.com/j2ee/.
The J2EE documentation page provides links to a wide variety of self-paced learning
materials, such as tutorials and FAQs, for beginners.
Developers looking for more advanced material should consult the Java BluePrints for the
enterprise. The Java BluePrints for the enterprise are the best practices philosophy for the
design and building of J2EE-based applications. The design guidelines document provides
two
things. First, it provides the philosophy of building n-tier applications on the Java 2
platform. Second, it provides a set of design patterns for designing these applications, as
well as a set of examples or recipes on how to build the applications.
Sun educational services also provides many training courses, which can lead to can lead to
one of three certifications: Sun Certified Web Component Developer, Sun Certified Business
Component Developer, or Sun Certified Enterprise Architect.
There are numerous choices of tools available for developing Java and J2EE applications.
You
can download the Open Source NetBeans IDE for free at http://netbeans.org. Many of the
J2EE
compatible vendors offer tools that support any J2EE compatible application server.
ISVs need the J2EE platform because it gives them a blueprint for providing a complete
enterprise computing solution on the Java platform. Enterprise developers need J2EE
because
writing distributed business applications is hard, and they need a high-productivity
solution that allows them to focus only on writing their business logic and having a full
range of enterprise-class services to rely on, like transactional distributed objects,
message oriented middleware, and naming and directory services.
When we say "Free" we mean that you don't pay Sun to develop or deploy the J2EE 1.4 SDK
or
the Sun Java System Application Server Platform Edition 8. Free means that you don't pay
Sun
for supplementary materials including documentation, tutorials and/or J2EE Blueprints. You
are also free to bundle and distribute (OEM) Sun Java System Application Server Platform
Here are some examples of how you can use Sun Java System Application Server Platform
Edition 8 for free.
If you are a developer you can build an application with the J2EE 1.4 SDK and then deploy it
on the Sun Java System Application Server Platform Edition 8 (included with the J2EE 1.4
SDK
or available separately). No matter how many developers are on your team, all of them can
use the J2EE 1.4 SDK at no charge. Once your application is ready for production, you can
deploy including the Sun Java System Application Server Platform 8 Edition in production on
as many servers or CPUs as you want.
If you are an ISV, you don't have to pay to include Sun Java System Application Server
Platform Edition 8 with your product, no matter how many copies of your software that you
distribute. Bundling Sun Java System Application Server Platform Edition 8 makes good
business sense because it ensures that you are distributing a J2EE 1.4 platform compatible
server that doesn't lock you or your customers into a proprietary product. ISV's that wish
to bundle Sun Java System Application Server Platform Edition 8 (for free of course) should
contact Sun OEM sales.
If you are a System Administrator or IT manager, you can install Sun Java System
Application
Server Platform Edition 8 on as many servers and CPUs as you wish. Using Sun Java
System
Application Server Platform Edition 8 also gives reduced cost and complexity by saving
money
on licensing fees and the assurance of a J2EE 1.4 platform compatible application server
that can be used with other J2EE 1.4 platform compatible application servers.
Q: Is support "Free"?
There are resources that are available for free on our site that may help you resolve your
issues without requiring technical support. For example you can ask questions on our
forums,
search for known issues on the bug data base, review the documentation, or take a look at
code samples and applications to help you at no cost.
Production support is also available for a fee through Sun Service. For more information
about Developer Technical Service and Sun Service, please visit
http://wwws.sun.com/software/products/appsrvr/support.html.
Yes. The J2EE Compatibility Test Suite (CTS) is available for the J2EE platform. The J2EE
CTS contains over 5,000 tests for J2EE 1.4 and will contain more for later versions. This
test suite tests compatibility by performing specific application functions and checking
results. For example, to test the JDBC call to insert a row in a database, an EJB component
makes a call to insert a row and then a call is made to check that the row was inserted.
A J2EE licensee has signed a commercial distribution license for J2EE. That means the
licensee has the compatibility tests and has made a commitment to compatibility. It does not
mean the licensees products are necessarily compatible yet. Look for the J2EE brand which
signifies that the specific branded product has passed the Compatibility Test Suite (CTS)
and is compatible.
Q: What is the relationship of the Apache Tomcat open-source application server to the J2EE
SDK?
Tomcat is based on the original implementation of the JavaServer Pages (JSP) and Java
Servlet specifications, which was donated by Sun to the Apache Software Foundation in
1999.
Sun continues to participate in development of Tomcat at Apache, focusing on keeping
Tomcat
current with new versions of the specifications coming out of the Java Community Source
ProcessSM. Sun adapts and integrates the then-current Tomcat source code into new
releases
of the J2EE SDK. However, since Tomcat evolves rapidly at Apache, there are additional
differences between the JSP and Servlet implementations in the J2EE SDK and in Tomcat
between J2EE SDK releases. Tomcat source and binary code is governed by the ASF
license,
which freely allows deployment and redistribution.
Java Language
Only the most important questions listed below and they are not categorized, since your
interviewing questions will not be categorized either.
1. What is a transient variable?
A transient variable is a variable that may not be serialized.
2. Which containers use a border layout as their default layout?
The window, Frame and Dialog classes use a border layout as their default layout.
3. How are Observer and Observable used?
Objects that subclass the Observable class maintain a list of observers. When an
Observable object is updated it invokes the update() method of each of its observers
to notify the observers that it has changed state. The Observer interface is
implemented by objects that observe Observable objects.
4. What is synchronization and why is it important?
With respect to multithreading, synchronization is the capability to control the access
of multiple threads to shared resources. Without synchronization, it is possible for one
thread to modify a shared object while another thread is in the process of using or
updating that object's value. This often causes dirty data and leads to significant
errors.
5. What are synchronized methods and synchronized statements?
Synchronized methods are methods that are used to control access to an object. A
thread only executes a synchronized method after it has acquired the lock for the
method's object or class. Synchronized statements are similar to synchronized
methods. A synchronized statement can only be executed after a thread has acquired
the lock for the object or class referenced in the synchronized statement.
6. What are three ways in which a thread can enter the waiting state?
A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O,
by unsuccessfully attempting to acquire an object's lock, or by invoking an object's
wait() method. It can also enter the waiting state by invoking its (deprecated)
suspend() method.
7. Can a lock be acquired on a class?
Yes, a lock can be acquired on a class. This lock is acquired on the class's Class
object.
8. What's new with the stop(), suspend() and resume() methods in JDK 1.2?
The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.
9. What is the preferred size of a component?
The preferred size of a component is the minimum component size that will allow the
component to display normally.
10. What method is used to specify a container's layout?
The setLayout() method is used to specify a container's layout.
11. Which containers use a FlowLayout as their default layout?
The Panel and Applet classes use the FlowLayout as their default layout.
12. What state does a thread enter when it terminates its processing?
When a thread terminates its processing, it enters the dead state.
13. What is the Collections API?
Networking
Sockets & RMI
1. What is the difference between URL instance and URLConnection instance?
A URL instance represents the location of a resource, and a URLConnection instance
represents a link for accessing or communicating with the resource at the location.
2. How do I make a connection to URL?
You obtain a URL instance and then invoke openConnection on it. URLConnection is
an abstract class, which means you can't directly create instances of it using a
constructor. We have to invoke openConnection method on a URL instance, to get the
right kind of connection for your URL. Eg. URL url;
URLConnection connection;
try{ url = new URL("...");
connection = url.openConnection();
}catch (MalFormedURLException e) { }
3. What Is a Socket?
A socket is one end-point of a two-way communication link between two programs
running on the network. A socket is bound to a port number so that the TCP layer can
identify the application that data is destined to be sent. Socket classes are used to
represent the connection between a client program and a server program. The
java.net package provides two classes--Socket and ServerSocket--which implement
the client side of the connection and the server side of the connection, respectively.
4. What information is needed to create a TCP Socket?
The Local System’s IP Address and Port Number. And the Remote System's
IPAddress and Port Number.
5. What are the two important TCP Socket classes?
Socket and ServerSocket. ServerSocket is used for normal two-way socket
communication. Socket class allows us to read and write through the sockets.
JDBC
1. What is JDBC?
JDBC is a layer of abstraction that allows users to choose between databases. It
allows you to change to a different database engine and to write to a single API. JDBC
allows you to write database applications in Java without having to concern yourself
with the underlying details of a particular database.
2. What are the two major components of JDBC?
One implementation interface for database manufacturers, the other implementation
interface for application and applet writers.
3. What is JDBC Driver interface?
The JDBC Driver interface provides vendor-specific implementations of the abstract
classes provided by the JDBC API. Each vendors driver must provide implementations
of the java.sql.Connection,Statement,PreparedStatement, CallableStatement,
ResultSet and Driver.
4. What are the common tasks of JDBC?
1.Create an instance of a JDBC driver or load JDBC drivers through jdbc.drivers; 2.
Register a driver; 3. Specify a database; 4. Open a database connection; 5. Submit a
query; 6. Receive results.
5. What packages are used by JDBC?
There are 8 packages: java.sql.Driver, Connection,Statement, PreparedStatement,
CallableStatement, ResultSet, ResultSetMetaData, DatabaseMetaData.
6. What are the flow statements of JDBC?
A URL string -->getConnection-->DriverManager-->Driver-->Connection-->Statement--
>executeQuery-->ResultSet.
7. What are the steps involved in establishing a connection?
This involves two steps: (1) loading the driver and (2) making the connection.
8. How can you load the drivers?
Loading the driver or drivers you want to use is very simple and involves just one line
of code. If, for example, you want to use the JDBC-ODBC Bridge driver, the following
code will load it:
Eg.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Your driver documentation will give you the class name to use. For instance, if the
class name is jdbc.DriverXYZ , you would load the driver with the following line of
code:
Second:
String s = rs.getString("COF_NAME");
The method getString is invoked on the ResultSet object rs , so getString will retrieve
(get) the value stored in the column COF_NAME in the current row of rs
13. What are the different types of Statements?
1.Statement (use createStatement method) 2. Prepared Statement (Use
prepareStatement method) and 3. Callable Statement (Use prepareCall)
14. How can you use PreparedStatement?
This special type of statement is derived from the more general class, Statement. If
you want to execute a Statement object many times, it will normally reduce execution
time to use a PreparedStatement object instead. The advantage to this is that in most
cases, this SQL statement will be sent to the DBMS right away, where it will be
compiled. As a result, the PreparedStatement object contains not just an SQL
statement, but an SQL statement that has been precompiled. This means that when
the PreparedStatement is executed, the DBMS can just run the PreparedStatement 's
SQL statement without having to compile it first.
E.g.
PreparedStatement updateSales = con.prepareStatement("UPDATE COFFEES SET
SALES = ? WHERE COF_NAME LIKE ?");
15. How to call a Stored Procedure from JDBC?
The first step is to create a CallableStatement object. As with Statement an and
PreparedStatement objects, this is done with an open Connection object. A
CallableStatement object contains a call to a stored procedure;
JSP
1. What is JSP technology?
Java Server Page is a standard Java extension that is defined on top of the servlet
Extensions. The goal of JSP is the simplified creation and management of dynamic
Web pages. JSPs are secure, platform-independent, and best of all, make use of Java
as a server-side scripting language.
2. What is JSP page?
A JSP page is a text-based document that contains two types of text: static template
data, which can be expressed in any text-based format such as HTML, SVG, WML,
and XML, and JSP elements, which construct dynamic content.
3. What are the implicit objects?
Servlet
1. What is the servlet?
Servlets are modules that extend request/response-oriented servers, such as Java-
enabled web servers. For example, a servlet may be responsible for taking data in an
HTML order-entry form and applying the business logic used to update a company's
order database.
2. What's the difference between servlets and applets?
Servlets are to servers; applets are to browsers. Unlike applets, however, servlets
have no graphical user interface.
3. What's the advantages using servlets than using CGI?
Servlets provide a way to generate dynamic documents that is both easier to write and
faster to run. It is efficient, convenient, powerful, portable, secure and inexpensive.
Servlets also address the problem of doing server-side programming with platform-
specific APIs: they are developed with Java Servlet API, a standard Java extension.
4. What are the uses of Servlets?
A servlet can handle multiple requests concurrently, and can synchronize requests.
This allows servlets to support systems such as on-line conferencing. Servlets can
forward requests to other servers and servlets. Thus servlets can be used to balance
load among several servers that mirror the same content, and to partition a single
logical service over several servers, according to task type or organizational
boundaries.
5. What's the Servlet Interface?
The central abstraction in the Servlet API is the Servlet interface. All servlets
implement this interface, either directly or, more commonly, by extending a class that
implements it such as HttpServlet. Servlets-->Generic Servlet-->HttpServlet--
>MyServlet. The Servlet interface declares, but does not implement, methods that
manage the servlet and its communications with clients. Servlet writers provide some
or all of these methods when developing a servlet.
6. When a servlet accepts a call from a client, it receives two objects. What are they?
EJB
1. What is EJB?
EJB stands for Enterprise JavaBean and is the widely-adopted server side component
architecture for J2EE. it enables rapid development of mission-critical application that
are versatile, reusable and portable across middleware while protecting IT investment
and preventing vendor lock-in.
J2EE
1. What is J2EE?
J2EE is an environment for developing and deploying enterprise applications. The
J2EE platform consists of a set of services, application programming interfaces
(APIs), and protocols that provide the functionality for developing multitiered, web-
based applications.
JMS
1. Java Message Service is the new standard for interclient communication. It allows
J2EE application components to create, send, receive, and read messages. It enables
distributed communication that is loosely coupled, reliable, and asynchronous.
Return to top
Misc
1. What is WML?
Wireless Markup Language (WML) page is delivered over Wireless Application
Protocol (WAP) and the network configuration requires a gateway to translate WAP to
HTTP and back again. It can be generated by a JSP page or servlet running on the
J2EE server.
2. What is your favorite sport?
My answer would be football if the interviewer is a man.
3. What is JUnit?
JUnit is a unit-testing framework. Unit-testing is a means of verifying the results you
expect from your classes. If you write your test before hand and focus your code on
passing the test you are more likely to end up with simple code that does what it
should and nothing more. Unit-testing also assists in the refactoring process. If your
code passes the unit-test after refactoring you will know that you haven't introduced
any bugs to it.
4. What is the difference between Java and PL/SQL?
Java is a general programming language. PL/SQL is a database query languague,
especially for Oracle database.
Return to top
Example 1
<!-- This is a commnet sent to client on
<%= (new java.util.Date()).toLocaleString() %>
-->
You can use any characters in the body of the comment except the closing --%> combination. If you need to
use --%> in your comment, you can escape it by typing --%\>.
JSP Syntax
<%-- comment --%>
Examples
<%@ page language="java" %>
<html>
<head><title>A Hidden Comment </title></head>
<body>
<%-- This comment will not be visible to the colent in the page source --%>
</body>
</html>
TOP
Q: What is a Expression?
A: An expression tag contains a scripting language expression that is evaluated, converted to a String, and
inserted where the expression appears in the JSP file. Because the value of an expression is converted to a
String, you can use an expression within text in a JSP file. Like
Q: What is a Declaration?
A: A declaration declares one or more variables or methods for use later in the JSP source file.
A declaration must contain at least one complete declarative statement. You can declare any number of
variables or methods within one declaration tag, as long as they are separated by semicolons. The
declaration must be valid in the scripting language used in the JSP file.
Q: What is a Scriptlet?
A: A scriptlet can contain any number of language statements, variable or method declarations, or expressions
that are valid in the page scripting language.Within scriptlet tags, you can
1.Declare variables or methods to use later in the file (see also Declaration).
2.Write expressions valid in the page scripting language (see also Expression).
3.Use any of the JSP implicit objects or any object declared with a <jsp:useBean> tag.
You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet.
Scriptlets are executed at request time, when the JSP engine processes the client request. If the scriptlet
produces output, the output is stored in the out object, from which you can display it.
TOP
• exception
TOP
TOP
1. page
2. request
3.session
4.application
TOP
Question: How do I prevent the output of my JSP or Servlet pages from being cached by the browser?
Question: How does JSP handle run-time exceptions?
Question: How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of
using it?
Question: How do I use a scriptlet to initialize a newly instantiated bean?
Question: How can I prevent the word "null" from appearing in my HTML input text fields when I populate them
with a resultset that has null values?
Question: What's a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface
or Synchronization?
Question: How can I enable session tracking for JSP pages if the browser has disabled cookies?
Q: How do I prevent the output of my JSP or Servlet pages from being cached by the browser?
A: You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the
JSP page from being cached by the browser. Just execute the following scriptlet at the beginning of your JSP
pages to prevent them from being cached at the browser. You need both the statements to take care of some
of the older browser versions.
<%
response.setHeader("Cache-Control","no-store"); //HTTP 1.1
response.setHeader("Pragma\","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
%>
Q: How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using
it?
A: You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is
done by adding the directive <%@ page isThreadSafe="false" %> within your JSP page. With this, instead of
a single instance of the servlet generated for your JSP page loaded in memory, you will have N instances of
the servlet loaded and initialized, with the service method of each instance effectively synchronized. You can
typically control the number of instances (N) that are instantiated for all servlets implementing
SingleThreadModel through the admin screen for your JSP engine. More importantly, avoid using the tag for
variables. If you do use this tag, then you should set isThreadSafe to true, as mentioned above. Otherwise,
all requests to that page will access those variables, causing a nasty race condition. SingleThreadModel is
not recommended for normal use. There are many pitfalls, including the example above of not being able to
use <%! %>. You should try really hard to make them thread-safe the old fashioned way: by making them
thread-safe .
[ Received from Sumit Dhamija ] TOP
The following example shows the “today” property of the Foo bean initialized to the current date when it is
instantiated. Note that here, we make use of a JSP expression within the jsp:setProperty action.
</jsp:useBean >
Q: How can I prevent the word "null" from appearing in my HTML input text fields when I populate them
with a resultset that has null values?
A: You could make a simple wrapper function, like
<%!
String blanknull(String s) {
return (s == null) ? \"\" : s;
}
%>
Q: What's a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface
or Synchronization?
A: Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not
scale well. If you anticipate your users to increase in the future, you may be better off implementing explicit
synchronization for your shared data. The key however, is to effectively minimize the amount of code that is
synchronzied so that you take maximum advantage of multithreading.
Also, note that SingleThreadModel is pretty resource intensive from the server\'s perspective. The most
serious issue however is when the number of concurrent requests exhaust the servlet instance pool. In that
case, all the unserviced requests are queued until something becomes free - which results in poor
performance. Since the usage is non-deterministic, it may not help much even if you did add more memory
and increased the size of the instance pool.
Q: How can I enable session tracking for JSP pages if the browser has disabled cookies?
Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp, interact with each
other. Basically, we create a new session within hello1.jsp and place an object within this session. The user
can then traverse to hello2.jsp by clicking on the link present within the page. Within hello2.jsp, we simply
extract the object that was earlier placed in the session and display its contents. Notice that we invoke the
encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the session ID is
automatically appended to the URL, allowing hello2.jsp to still retrieve the session object. Try this example
first with cookies enabled. Then disable cookie support, restart the brower, and try again. Each time you
should see the maintenance of the session across pages. Do note that to get this example to work with
cookies disabled at the browser, your JSP engine has to support URL rewriting.
hello1.jsp
<%@ page session=\"true\" %>
<%
Integer num = new Integer(100);
session.putValue("num",num);
String url =response.encodeURL("hello2.jsp");
%>
<a href=\'<%=url%>\'>hello2.jsp</a>
hello2.jsp
<%@ page session="true" %>
<%
Integer i= (Integer )session.getValue("num");
out.println("Num value in session is " + i.intValue());
%>
[ Received from Vishal Khasgiwala ] TOP
1. What is JSP? Describe its concept. JSP is a technology that combines HTML/XML
markup languages and elements of Java programming Language to return dynamic
content to the Web client, It is normally used to handle Presentation logic of a web
application, although it may have business logic.
2. What are the lifecycle phases of a JSP?
JSP page looks like a HTML page but is a servlet. When presented with JSP page the
JSP engine does the following 7 phases.
1. Page translation: -page is parsed, and a java file which is a servlet is created.
2. Page compilation: page is compiled into a class file
3. Page loading : This class file is loaded.
4. Create an instance :- Instance of servlet is created
5. jspInit() method is called
6. _jspService is called to handle service calls
7. _jspDestroy is called to destroy it when the servlet is not required.
o request
o response
o pageContext
o session
o application
o out
o config
o page
o exception
2. What’s the difference between forward and sendRedirect? When you
invoke a forward request, the request is sent to another resource on the server,
without the client being informed that a different resource is going to process
1. What is the query used to display all tables names in SQL Server (Query
analyzer)?
2. select * from information_schema.tables
3. How many types of JDBC Drivers are present and what are they?- There are 4
types of JDBC Drivers
o JDBC-ODBC Bridge Driver
But it’s a little trickier if you want the server to evaluate any JSP code that’s inside the
included file. If your data.inc file contains jsp code you will have to use
20. I made my class Cloneable but I still get Can’t access protected method clone.
Why?- Some of the Java books imply that all you have to do in order to have your
class support clone() is implement the Cloneable interface. Not so. Perhaps that was
the intent at some point, but that’s not the way it works currently. As it stands, you
have to implement your own public clone() method, even if it doesn’t do anything
special and just calls super.clone().
21. Why is XML such an important development?- It removes two constraints which
were holding back Web developments: dependence on a single, inflexible document
type (HTML) which was being much abused for tasks it was never designed for; the
complexity of full SGML, whose syntax allows many powerful but hard-to-program
options. XML allows the flexible development of user-defined document types. It
In general, all things being equal, you can assume that the more your request and
response change hands, the slower it will be. This means that 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).
or
boolean hasParameter =
request.getParameterMap().contains(theParameter); //(which works in Servlet 2.3+)
My database has a column of type DATETIME. What type of Java variable do I use in
the EJB?
java.sql.Timestamp
9. In an HTML form I have a Button which makes us to open another page in 15 seconds.
How will do you that ?
16. How will you pass values from HTML page to the Servlet ?
27. How will you call an Applet using a Java Script function ?
32. How you can know about drivers and database information ?
33. If you are truncated using JDBC, How can you know ..that how much data is truncated ?
36. In RMI, server object first loaded into the memory and then the stub reference is sent to
the client ? or whether a stub reference is directly sent to the client ?
37. Suppose server object is not loaded into the memory, and the client request for it , what
will happen?
39. Can you load the server object dynamically? If so, what are the major 3 steps involved in
it ?
41. To a server method, the client wants to send a value 20, with this value exceeds to 20,. a
message should be sent to the client ? What will you do for achieving for this ?
49. Can you run the product development on all operating systems ?
57. What are the files generated after using IDL to Java Compilet ?
61. What is the mapping mechanism used by Java to identify IDL language ?
70. Suppose If we have variable ' I ' in run method, If I can create one or more thread each
thread will occupy a separate copy or same variable will be shared ?
78. What is Constructor and Virtual function? Can we call Virtual funciton in a constructor ?
85. What is the exact difference in between Unicast and Multicast object ? Where we will use
?
88. What is the difference in between C++ and Java ? can u explain in detail ?
89. I want to store more than 10 objects in a remote server ? Which methodology will follow ?
93. What is meant by Servelet? What are the parameters of the service method ?
95. How do you invoke a Servelt? What is the difference in between doPost and doGet
methods ?
96. What is the difference in between the HTTPServlet and Generic Servlet ? Expalin their
methods ? Tell me their parameter names also ?
100. In a Container there are 5 components. I want to display the all the components
names, how will you do that one ?
101. Why there are some null interface in java ? What does it mean ? Give me some null
interfaces in JAVA ?
103. What is meant by class loader ? How many types are there? When will we use them ?
106. What is meant by distributed Application ? Why we are using that in our applications ?
109. What is the latest version of JDBC ? What are the new features are added in that ?
112. How have you done validation of the fileds in your project ?
113. What is the main difficulties that you are faced in your project ?
try
{
// Open an output stream
fout = new FileOutputStream ("myfile.txt");
try
{
// Open an input stream
fin = new FileInputStream ("myfile.txt");
1) session should work regardless of the settings on the client browser. even if users decide
to forbid the cookie (through browser settings) session still works. there is no way to disable
sessions from the client browser.
2) session and cookies differ in type and amount of information they are capable of storing.
javax.servlet.http.Cookie class has a setValue() method that accepts Strings.
javax.servlet.http.HttpSession has a setAttribute() method which takes a String to denote the
name and java.lang.Object which means that HttpSession is capable of storing any java
object. Cookie can only store String objects.
A. The class System has a variable out that represents the standard output, and the variable err that represents the
standard error device. By default, they both point at the system console. This how the standard output could be re-directed:
Stream st = new Stream(new FileOutputStream("output.txt")); System.setErr(st); System.setOut(st);
A. An abstract class may contain code in method bodies, which is not allowed in an interface. With abstract classes, you
have to inherit your class from it and Java does not allow multiple inheritance. On the other hand, you can implement
multiple interfaces in your class.
*Q3. Why would you use a synchronized block vs. synchronized method?
A. Synchronized blocks place locks for shorter periods than synchronized methods.
A. You can't force GC, but could request it by calling System.gc(). JVM does not guarantee that GC will be started
immediately.
A. If you assign a superclass object to a variable of a subclass's data type, you need to do explicit casting. For example:
Object a; Customer b; b = (Customer) a;
When you assign a subclass to a variable having a supeclass type, the casting is performed automatically.
*Q7. What's the difference between the methods sleep() and wait()
A. The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one
second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the
class Object and the method sleep() is defined in the class Thread.
*Q8. Can you write a Java class that could be used both as an applet as well as an application?
A. Constructors must have the same name as the class and can not return a value. They are only called once while regular
methods could be called many times.
*Q10. Can you call one constructor from another if a class has multiple constructors
A. This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when
different packages have classes with the same names. Packages access level also allows you to protect data from being
used by the non-authorized classes.
*Q12. If a class is located in a package, what do you need to change in the OS environment to be able to use it?
A. You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable.
Let's say a class Employee belongs to a package com.xyz.hr; and is located in the file c:\dev\com\xyz\hr\Employee.java. In
this case, you'd need to add c:\dev to the variable CLASSPATH. If this class contains the method main(), you could test it
from a command prompt window as follows:
c:\>java com.xyz.hr.Employee
*Q13. What's the difference between J2SDK 1.5 and J2SDK 5.0?
*Q14. What would you use to compare two String variables - the operator == or the method equals()?
A. I'd use the method equals() to compare the values of the Strings and the == to check if two variables point at the same
instance of a String object.
A. Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's subclasses have to be caught
first.
*Q16. Can an inner class declared inside of a method access local variables of this method?
*Q17. What can go wrong if you replace && with & in the following code:
String a=null; if (a!=null && a.length()>10) {...}
A. A single ampersand here would lead to a NullPointerException.
A. This method is used to ensure that Swing components are updated through the event-dispatching thread.
A. Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super(); in the first line of
the subclass's constructor.
A. Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule
**Q22. You can create an abstract class that contains only abstract methods. On the other hand, you can create an
interface that declares the same methods. So can you use abstract classes instead of interfaces?
A. Sometimes. But your class may be a descendent of another class and in this case the interface is your only option.
**Q23. What comes to mind when you hear about a young generation in Java?
A. Garbage collection.
**Q24. What comes to mind when someone mentions a shallow copy in Java?
A. Object cloning.
**Q25. If you're overriding the method equals() of an object, which other method you might also consider?
A. hashCode()
**Q26. You are planning to do an indexed search in a list of objects. Which of the two Java collections should you
use:
ArrayList or LinkedList?
A. ArrayList
A. Have this class implement Cloneable interface and call its method clone().
**Q28. How can you minimize the need of garbage collection and make the memory use more effective?
**Q29. There are two classes: A and B. The class B need to inform a class A when some important event has
happened. What Java technique would you use to implement it?
A. If these classes are threads I'd consider notify() or notifyAll(). For regular classes you can use the Observer interface.
*Q30. What access level do you need to specify in the class declaration to ensure that only classes from the same
directory can access it?
A. You do not need to specify any access level, and Java will use a default package access level.
Answer :
Answered by asreeni on 2005-04-08 03:24:40: The core of the Struts framework is a flexible
control layer based on standard technologies like Java Servlets, JavaBeans,
ResourceBundles, and XML, as well as various Jakarta Commons packages. Struts
encourages application architectures based on the Model 2 approach, a variation of the
classic Model-View-Controller (MVC) design paradigm.
Struts provides its own Controller component and integrates with other technologies to
provide the Model and the View. For the Model, Struts can interact with standard data access
technologies, like JDBC and EJB, as well as most any third-party packages, like Hibernate,
iBATIS, or Object Relational Bridge. For the View, Struts works well with JavaServer Pages,
including JSTL and JSF, as well as Velocity Templates, XSLT, and other presentation
systems.
The Struts framework provides the invisible underpinnings every professional web
application needs to survive. Struts helps you create an extensible development environment
for your application, based on published standards and proven design patterns.
Question : What is the difference between Struts 1.0 and Struts 1.1
User Answers/Comments Print Question Email Question Comment/Answer
Posted by Anju Molugu on 2005-03-14 13:35:48The new features added to Struts 1.1
are 1. RequestProcessor class 2. Method perform() replaced by execute() in Struts base
Action Class 3. Changes to web.xml and struts-config.xml 4.Declarative exception handling
5.Dynamic ActionForms 6.Plug-ins 7.Multiple Application Modules 8.Nested Tags 9.The
Question : How you will save the data across different pages for a particular client
request using Struts