Servelets FAQ's

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
Servlets are designed to work within a request/response processing model. In a request/response model, a client sends a request message to a server and the server responds by sending back a reply message. Requests can come in the form of an
HTTP
URL,
FTP,
URL, or a custom protocol.
The request and the corresponding response reflect the state of the client and the server at the time of the request. Normally, the state of the client/server connection cannot be maintained across different request/response pairs. However, session information is maintainable with servlets through means to be described later. The Java Servlet API includes several Java interfaces and fully defines the link between a hosting server and servlets. The Servlet API is defined as an extension to the standard JDK. JDK extensions are packaged under javax--the root of the Java extension library tree. The Java Servlet API contains the following packages:
 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.
Architectural Roles for Servlets
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
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.
Other middle tier roles include:
 Business rule enforcement
 Transaction management
 Mapping clients to a redundant set of servers
 Supporting different types of clients such as pure HTML and Java capable clients
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 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.
Inline HTML Generation
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:
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.
Replacing CGI Scripts
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:
1. Install the servlet in a hosting server
2. Request a servlet's service via a client request
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.
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.
There is no special code necessary to make a servlet temporary or permanent; this is a function of the server configuration.
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:
Usage: servletrunner [options]
Options:
-p port the port number to listen on
-b backlog the listen backlog
-m max maximum number of connection handlers
-t timeout connection timeout in milliseconds
-d dir servlet directory
-s filename servlet property file name
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
1. Hosting with servletrunner
Using Java Web Server
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.
Servlets are installed by moving them to the c:\JavaWebServer1.1\servlets directory. As mentioned, JWS detects when servlets have been added to this directory. Although you can use the JWS management applet to tailor the servlet installation, this is generally not advised except for production server installations.
To shut down the JWS, press +C in the command window. The server prints a message to the console when it has finished shutting down.
Magercise
2. Hosting with the Java Web Server
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
The API provides support in four categories:
 Servlet life cycle management
 Access to servlet context
 Utility classes
 HTTP-specific support classes
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.
A web server communicates with a servlet through a simple interface, javax.servlet.Servlet. This interface consists of three main methods:
 init()
 service()
 destroy()
and two ancillary methods:
 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.
The init() Method
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
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 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
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;


public void init (ServletConfig config)
throws ServletException {
this.config = config;
}
public void destroy() {} // do nothing
public ServletConfig getServletConfig() {
return config;
}

public String getServletInfo() {
return "A Simple Servlet";
}

public void service (ServletRequest req,
ServletResponse res
) throws ServletException, IOException {
res.setContentType( "text/html" );
PrintWriter out = res.getWriter();
out.println( "" );
out.println( " );
out.println( "A Sample Servlet" );
out.println( "" );
out.println( "" );
out.println( "

A Sample Servlet

" );
out.println( "" );
out.println( "" );
out.close();
}
}
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.
Servlet Initialization 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");
}
An Enumeration of all initialization parameters is available to the servlet via the getInitParameterNames() method.
Server Context Information
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.
getAttribute() An extensible way to get information about a server via attribute name/value pairs. This is server specific.
getMimeType() Returns the MIME type of a given file.
getRealPath() This method translates a relative or virtual path to a new path relative to the server's HTML documentation root location.
getServerInfo() Returns the name and version of the network service under which the servlet is running.
getServlet() Returns a Servlet object of a given name. Useful when you want to access the services of other servlets.
getServletNames() Returns an enumeration of servlet names available in the current namespace.
log() Writes information to a servlet log file. The log file name and format are server specific.
The following example code shows how a servlet uses the host server to write a message to a servlet log when it initializes:
private ServletConfig config;
public void init(ServletConfig config) {
// Store config in an instance variable
this.config = config;
ServletContext sc = config.getServletContext();
sc.log( "Started OK!" );
}
Servlet Context During a Service Request
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.
The following code shows how to get service-time information:
BufferedReader reader;
String param1;
String param2;
public void service (
ServletRequest req,
ServletResponse res) {

reader = req.getReader();
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.
getAttribute() Returns value of a named attribute for this request.
getContentLength() Size of request, if known.
getContentType() Returns MIME type of the request message body.
getInputStream() Returns an InputStream for reading binary data from the body of the request message.
getParameterNames() Returns an array of strings with the names of all parameters.
getParameterValues() Returns an array of strings for a specific parameter name.
getProtocol() Returns the protocol and version for the request as a string of the form /..
getReader() Returns a BufferedReader to get the text from the body of the request message.
getRealPath() Returns actual path for a specified virtual path.
getRemoteAddr() IP address of the client machine sending this request.
getRemoteHost() Host name of the client machine that sent this request.
getScheme() Returns the scheme used in the URL for this request (for example, https, http, ftp, etc.).
getServerName() Name of the host server that received this request.
getServerPort() Returns the port number used to receive this request.
The following Magercise shows you how to extract parameters from a service request.
Magercise
3. Accessing Servlet Service-Time Parameters
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.
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
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).
An HTTP GET request takes the form:
GET URL
Host:
in addition to several other lines of information.
For example, the following HTTP GET message is requesting the home page from the MageLang web site:
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:
HTTP/1.1 200 Document follows
Date: Tue, 14 Apr 1997 09:25:19 PST
Server: JWS/1.1
Last-modified: Mon, 17 Jun 1996 21:53:08 GMT
Content-type: text/html
Content-length: 4435

<4435>
The HEAD Method
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.
HEAD is often used to check the following:
 The last-modified date of a document on the server for caching purposes
 The size of a document before downloading (so the browser can present progress information)
 The server type, allowing the client to customize requests for that server
 The type of the requested document, so the client can be sure it supports it
Note that HEAD, like GET, is expected to be safe and idempotent.
The POST Method
An HTTP POST request allows a client to send data to the server. This can be used for several purposes, such as
 Posting information to a newsgroup
 Adding entries to a web site's guest book
 Passing more information than a GET request allows
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.
A typical POST request might be as follows:
POST /servlet/MyServlet HTTP/1.1
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, */
Content-type: application/x-www-form-urlencoded
Content-length: 39

name=Scott&company=MageLang%20Institute
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.
HTTP Support Classes
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()
and correspond directly with the HTTP protocol methods.
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.
Using the HTTP Support Classes
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.
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.
A servlet's doGet() method should
 Read request data, such as input parameters
 Set response headers (length, type, and encoding)
 Write the response data
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.
Servlet support currently spans two packages:
javax.servlet: General Servlet Support
Servlet An interface that defines communication between a web server and a servlet. This interface defines the init(), service(), and destroy() methods (and a few others).
ServletConfig An interface that describes the configuration parameters for a servlet. 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.
ServletContext An interface that describes how a servlet can get information about the server in which it is running. It can be retrieved via the getServletContext() method of the ServletConfig object.
ServletRequest An interface that describes how to get information about a client request.
ServletResponse An interface that describes how to pass information back to the client.
GenericServlet A base servlet implementation. It takes care of saving the ServletConfig object reference, and provides several methods that delegate their functionality to the ServletConfig object. It also provides a dummy implementation for init() and destroy().
ServletInputStream A subclass of InputStream used for reading the data part of a client's 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.

javax.servlet.http: Support for HTTP Servlets
HttpServletRequest A subclass of ServletRequest that defines several methods that parse HTTP request headers.
HttpServletResponse A subclass of ServletResponse that provides access and interpretation of HTTP status codes and header information.
HttpServlet A subclass of GenericServlet that provides automatic separation of HTTP request by method type. For example, an HTTP GET request will be processed by the service() method and passed to a doGet() method.
HttpUtils A class that provides assistance for parsing HTTP GET and POST requests.
Servlet Examples
Now for an in-depth look at several servlets. These examples include:
 Generating Inline Content
 Processing HTTP Post Requests
 Using Cookies
 Maintaining Session Information
 Connecting to Databases
Generating Inline Content
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 tag, for example:



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
4. Generating In-line Content
Processing HTTP Post Requests
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 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
5. Posting and Processing HTML Forms
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.
private static final String SUM_KEY = "sum";
...
int sum = ...; // get old value and add to it
Cookie theCookie =
new Cookie (SUM_KEY, Integer.toString(sum));
response.setContentType("text/html");
response.addCookie(theCookie);
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, 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;
}
}
}
The complete code example shown above is available for testing.
Maintaining Session Information
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.
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.
private static final String SUM_KEY =
"session.sum";
private static final String ERROR_KEY =
"session.errors";
Integer sum = (Integer) session.getValue(SUM_KEY);
int ival = 0;
if (sum != null) {
ival = sum.intValue();
}
try {
String addendString =
request.getParameter("Addend");
int addend = Integer.parseInt (addendString);
sum = new Integer(ival + addend);
session.putValue (SUM_KEY, sum);
} catch (NumberFormatException e) {
Integer errorCount =
(Integer)session.getValue(ERROR_KEY);
if (errorCount == null) {
errorCount = new Integer(1);
} else {
errorCount = new Integer(errorCount.intValue()+1);
}
session.putValue (ERROR_KEY, errorCount);
}
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("" +
"Session Information" +
"" +
"

Session Information

");
out.println ("");
out.println ("");
out.println ("");
out.println ("");
out.println ("");
out.println ("");
out.println ("");
out.println ("");
String names[] = session.getValueNames();
for (int i=0, n=names.length; i out.println ("");
out.println ("");
}
out.println("
Identifier" + session.getId() + "
Created" + new Date(
session.getCreationTime()) + "
Last Accessed" + new Date(
session.getLastAccessedTime()) + "
New Session?" + session.isNew() + "
" + names[i] + "" + session.getValue (names[i])
+ "
");
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.
 In the init() method connect to the database.
 Connection con = null;
 public void init (ServletConfig cfg)
 throws ServletException {
 super.init (cfg);
 // Load driver
 String name = cfg.getInitParameter("driver");
 Class.forName(name);
 // Get Connection
 con = DriverManager.getConnection (urlString);
 }
 In the doGet() method retrieve database information.
 public void doGet (HttpServletRequest request,
 HttpServletResponse response)
 throws ServletException, IOException {
 response.setContentType("text/html");

 // Have browser ignore cache - force reload
 response.setHeader ("Expires",
 "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.
The Servlet Sandbox
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...
Access Control Lists (ACLs)
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:
 What kind of access is allowed
 What object the access applies to
 Which users are granted access
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.)
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:
private int counter = 0;
Next, suppose that your service() method contained the following code:
int myNumber = counter + 1; // line 1
counter = myNumber; // line 2

// rest of the code in the service() method

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;
}

// rest of code in the service() method

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.
JSDK 1.0 and JSDK 2.0
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 still provide servlet support that complies with the JSDK 1.0 API definitions, you need to be careful about upgrading to the new JSDK.
New Servlet Features in JSDK 2.0
JSDK 2.0 adds the following servlet support:
 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
JSDK 2.0 deprecated one method:
 getServlets() --you should use getServletNames() instead




























Class javax.servlet.ServletInputStream
javax.servlet.ServletInputStream
public abstract class ServletInputStream
An input stream for reading servlet requests, it provides an efficient readLine method. This is an abstract class, to be implemented by a network services writer. For some application protocols, such as the HTTP POST and PUT methods, servlet writers use the input stream to get data from clients. They access the input stream via the ServletRequest's getInputStream method, available from within the servlet's service method. Subclasses of ServletInputStream must provide an implementation of the read() method.
See Also:
read
ServletInputStream()
The default constructor does no work.
readLine(byte[], int, int)
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.
ServletInputStream
protected ServletInputStream()
The default constructor does no work.
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



Java Servlets and Applets
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.
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.
Modelling using Session and Entity EJBs
Gopalan Suresh Raj

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

The service Method
Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service method checks the HTTP request
type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete,
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.

The destroy Method
The server may decide to remove a previously loaded servlet instance, perhaps because it is explicitly asked to do so by the server administrator, or perhaps because the servlet is idle for a long time. Before it does, however, it
calls the servlet’s destroy method. This method gives your servlet a chance
to close database connections, halt background threads, write cookie lists or
hit counts to disk, and perform other such cleanup activities.
2. ServletConfig
A. ServletConfig has a getInitParameter method with which you can look up
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) +
"\n" +
"

" + title + "

");
for(int i=0; iout.println(message + "
");
}
out.println("");
}
}

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();
for(int i=0; iCookie 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");
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("...");
• Redirect URLs
String originalURL = someURL; // Relative URL OK in 2.2
String encodedURL = response.encodeRedirectURL(originalURL);
response.sendRedirect(encodedURL);

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

6. What are the various ways of forwarding a request to JSP?
A. Once you have a RequestDispatcher, you use forward to completely transfer
control to the associated URL and use include to output the associated URL’s
content. In both cases, you supply the HttpServletRequest and
HttpServletResponse as arguments. Both methods throw ServletException and IOException.
Request Forwarding Syntax
String url = "/path/presentation1.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);

Getting a RequestDispatcher by Alternative Means (2.2 Only)
• By name: use getNamedDispatcher method of ServletContext.
• By path relative to initial servlet’s location: use the getRequestDispatcher method of HttpServletRequest rather than the one from ServletContext.
Including Static or Dynamic Content
• Basic usage:
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("...");
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/path/resource");
dispatcher.include(request, response);
out.println("...");
• JSP equivalent is jsp:include(action), not the JSP include directive.
Forwarding Requests from JSP Pages


Including Static or Dynamic Content
If a servlet uses the forward method of RequestDispatcher, it cannot actually send any output to the client—it must leave that entirely to the destination page. If the servlet wants to generate some of the content itself but use a JSP page or static HTML document for other parts of the result, the servlet
can use the include method of RequestDispatcher instead. The process is very similar to that for forwarding requests: call the getRequestDispatcher method of ServletContext with an address relative to the server root, then call include with the HttpServletRequest and HttpServletResponse.
The two differences when include is used are that you can send content to
the browser before making the call and that control is returned to the Servlet after the include call finishes. Although the included pages (servlets, JSP pages, or even static HTML) can send output to the client, they should not try to set HTTP response headers. Here is an example:
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("...");
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher("/path/resource");
dispatcher.include(request, response);
out.println("...");

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

7. How context can be transferred from servlet to JSP?
A. response.sendredirect and requestdispatcher.forward() mechanisms are used.

8. How can you write a FTP Servlet?
A. By extending Generic Servlet.

9. Difference between RequestDispatcher, forward and response.sendredirect?
A. If you redirect users to a page within your site, plan ahead for session tracking by
using response.sendRedirect(response.encodeURL(url)), rather than just response.sendRedirect(url). With sendRedirect, the servlet automatically builds a
page containing the link to show to older browsers that don’t automatically follow redirects. Finally, with version 2.2 of servlets (the version in J2EE), sendRedirect can handle relative URLs, automatically translating them into absolute ones. You must use an absolute URL in version 2.1, however.

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.

2. Usage of all JSP tags
A. JSP scripting elements let you insert code into the servlet that will be generated
from the JSP page. There are three forms:
1. Expressions of the form <%= expression %>, which are evaluated and inserted into the servlet’s output
Ex: Current time: <%= new java.util.Date() %>
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 :

Java Expression

Ex:

JSP Expressions



  • Current time: <%= new java.util.Date() %>
  • Your hostname: <%= request.getRemoteHost() %>
  • Your session ID: <%= session.getId() %>
  • The testParam form parameter:
    <%= request.getParameter("testParam") %>



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:

<%
String bgColor = request.getParameter("bgColor");
boolean hasExplicitColor;
if (bgColor != null) {
hasExplicitColor = true;
} else {
hasExplicitColor = false;
bgColor = "WHITE";
}
%>
">

Color Testing


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


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:

JSP Declarations


<%! private int accessCount = 0; %>

Accesses to page since server reboot:
<%= ++accessCount %>



Note: Check the page Comp’s-of-jsp in the same folder

3. What are the scopes in jsp?
A. page, session, application, request.

4.What is the difference between the session and application scope?
A. application
Means that, in addition to being bound to a local variable, bean will be stored in shared ServletContext available through predefined application variable or by a call to getServletContext().This means a variable is created per application to all users.
session
Means that, in addition to being bound to a local variable, bean will be stored in HttpSession object associated with current request, where it can be retrieved with getValue. This means a variable is created per session per user.

5. Can a jsp extend any class?
A. The extends attribute indicates the superclass of the servlet that will be generated
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.

6. JSP- A sample Jsp file
A.


JSP Expressions






JSP Expressions



  • Current time: <%= new java.util.Date() %>
  • Your hostname: <%= request.getRemoteHost() %>
  • Your session ID: <%= session.getId() %>
  • The testParam form parameter:
    <%= request.getParameter("testParam") %>




7. Jsp Implicit Objects
A. As a JSP author, you have access to certain objects that are available for use in JSP
documents without being declared first. These objects are parsed by the JSP engine and
inserted into the generated Servlet as if you defined them yourself. In reality the JSP
engine recognizes the implicit object names and knows that they will be declared by,
or passed into, the generated servlet. Here's a example of a code snippet containing a
_jspService() method:
request : This variable is the HttpServletRequest associated with the request; it gives you access to the request parameters, the request type (e.g., GET or POST), and the incoming HTTP headers (e.g., cookies). Strictly speaking, if the protocol in the request is something other than HTTP, request is allowed to be a subclass of ServletRequest other than HttpServletRequest. However, few, if any, JSP servers currently support non-HTTP servlets.
response : This variable is the HttpServletResponse associated with the response to the client. Note that since the output stream (see out) is normally buffered, it is legal to set HTTP status codes and response headers in JSP pages, even though the setting of headers or status codes is not permitted in servlets once any output has been sent to the client.
out : This is the PrintWriter used to send output to the client. However, to make the response object useful, this is a buffered version of PrintWriter called JspWriter. You can adjust the buffer size through use of the buffer attribute of the page directive. Also 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.


8. Difference between page and pageContext?
A. 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. See Section 13.4
(Sharing Beans) for a discussion of its use.

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.

The action provides a mechanism for including additional static and dynamic resources in the current JSP page. The syntax for this action is as follows:

and



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

2.When do you use executeQuery()?
A. The method used most often for executing SQL statements is executeQuery .
This method is used to execute SELECT statements, which comprise the vast majority
of SQL statements.

3. When do you use executeUpdate()?
A. We use the method executeUpdate because the SQL statement contained in
createTableCoffees is a DDL (data definition language) statement. Statements that
create a table, alter a table, or drop a table are all examples of DDL statements and
are executed with the method executeUpdate . As you might expect from its name,
the method executeUpdate is also used to execute SQL statements that update a
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.

4. How will you do exception Handling?
A. JDBC lets you see the warnings and exceptions generated by your DBMS and by the Java compiler. To see exceptions, you can have a catch block print them out. For example, the following two catch blocks from the sample code print out a message explaining the exception:
try {
// Code that could generate an exception goes here. If an exception is generated, the catch //block below will print out information about it.
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}

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

5. Usage of finally{ } statement
A. Using finally
The generalized exception-handling code has one more part to it than you saw in the last example. This is the finally block. If you put a finally block after a try and its associated catch blocks, then once execution enters the try block the code in that finally block will definitely be executed whatever the circumstances—well, nearly definitely. If an exception arises with a matching catch block, then the finally block is executed after the catch block. If no exception arises, the finally block is executed after the try block. If an exception arises for which there is no appropriate catch block, then the finally block is executed after the try block.The circumstances that can prevent execution of the code in a finally block are
• The death of the thread
• The use of System.exit()
• Turning off the power to the CPU
• An exception arising in the finally block itself
6. What are the various type of Drivers?
A. JDBC Driver Types
Sun has defined four JDBC driver types:
1. JDBC-ODBC Bridge, plus ODBC driver
2. Native-API, partly-Java driver
3. JDBC-net, pure Java driver
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.

7. What is prepared statement? (Pre-compiled)
A. If you want to execute a Statement object many times, it will normally reduce execution time to use a PreparedStatement object instead.
The main feature of a PreparedStatement object is that, unlike a Statement object, it is given an SQL statement when it is created. 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.

8. How will you use prepared Statement?
A. As with Statement objects, you create PreparedStatement objects with a Connection method. Using our open connection con from previous examples, you might write code such as the following to create a PreparedStatement object that takes two input parameters:
PreparedStatement updateSales = con.prepareStatement(
"UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
You will need to supply values to be used in place of the question mark placeholders, if there are any, before you can execute a PreparedStatement object. You do this by calling one of the setXXX methods defined in the class PreparedStatement . If the value you want to substitute for a question mark is a Java int , you call the method setInt. If the value you want 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():


9. What is a callable statement?
A. A CallableStatement object contains a call to a stored procedure; it does not contain the stored procedure itself.

10. How will you use callable statement?
A. The first line of code below creates a call to the stored procedure SHOW_SUPPLIERS using the connection con . The part that is enclosed in curly braces is the escape syntax for stored procedures. When the driver encounters "{call SHOW_SUPPLIERS}" , it will translate this escape syntax into the native SQL used by the database to call the stored procedure named SHOW_SUPPLIERS.
Ex:
CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();

11. How do you release connections?
A. This final section is used to put our connection back into the ConnectionPool for further use. The connection is released by calling the pool.releaseConnection() method with the Connection object. This method call is placed in the finally block to guarantee its execution.
Ex:
finally {
try {
if ( con != null ) {
// release the connection no matter what
pool.releaseConnection(con);
}
}
catch (Exception e) {
out.println(e.getMessage());
}


12. How do you parse result set?
A.

13.What is rs.next()? What happens with this?
A. The variable rs, which is an instance of ResultSet , contains the rows of coffees
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.

14. Autocommit(), commit(), rollback()
A. When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and will be automatically committed right after it is executed. (To be more precise, the default is for an SQL statement to be committed when it is completed, not when it is executed. A statement is completed when all of its result sets and update counts have been retrieved. In almost all cases, however, a statement is completed, and therefore committed, right after it is executed.)
The way to allow two or more statements to be grouped into a transaction is to disable auto-commit mode. This is demonstrated in the following line of code, where con is an active connection :
con.setAutoCommit(false);

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.

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

Serving Up Web Server Basics

By Chris Hughes and Gunther Birznieks

Contents

How a Web Server Works – Overview?
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?
How Does Web Server Security Work?
How Does a Web Server Differ From an Application Server?
How Does a Web Server Run Web Applications?
Wrapping Up


How a Web Server Works – Overview

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


That's all there is to it.
But if it's that simple, then why such an in-depth tutorial?
Because this simple arrangement, which allows the serving of static content such as HyperText Markup Language (HTML) and image files to a Web browser was the initial concept behind what we now call the World Wide Web. The beauty of its simplicity is that it has led to much more complex information exchanges being possible between browsers and Web servers.
Perhaps the most important expansion on this was the concept of dynamic content (i.e., Web pages created in response to a user's input, whether directly or indirectly). The oldest and most used standard for doing this is Common Gateway Interface (CGI). This is a pretty meaningless name, but it basically defines how a Web server should run programs locally and transmit their output through the Web server to the user's Web browser that is requesting the dynamic content.
For all intents and purposes the user's Web browser never really has to know that the content is dynamic because CGI is basically a Web server extension protocol. The figure below shows what happens when a browser requests a page dynamically generated from a CGI program.



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?


What is HTTP, and how does it work?

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


eXtropia Homepage
[...]


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.


How Does a Web Server Serve Content?
Of course, it's all very well to define HTTP as the protocol for a browser to communicate with a Web server. However, there is more to a Web server than its function a communications protocol. Ultimately, a Web server serves up content.
This content must be identified in a way such that a Web browser can download and display that content in correctly. The primary mechanism for deciding how to display content is the MIME type header.
Multipurpose Internet Mail Extension (MIME) types tell a Web browser what sort of document is being sent. Such type identification is not limited to simple graphics or HTML.
In fact, more than 370 MIME types are distributed with the Apache Web server by default in the mime.types configuration file. And even this list does not represent the entire universe of possible MIME types! MIME types are distinguished using a type/subtype syntax associated with a file extension. Here is a brief snippet from an Apache mime.types file.

text/xml xml
video/mpeg mpeg mpg mpe

video/quicktime qt mov

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.

How Does a Web Server Accept Connections?
Web servers are designed around a certain set of basic goals:
 Accept network connections from browsers.
 Retrieve content from disk.
 Run local CGI programs.
 Transmit data back to clients.
 Be as fast as possible.
Unfortunately, these goals are not totally compatible. For example, a simple Web server could follow the logic below:
 Accept connection
 Generate static or dynamic content and return to browser
 Close connection
 Accept connection
 Back to the start...
This would work just fine for the very simplest of Web sites, but the server would start to encounter problems as soon as clients started hitting the site in numbers, or if a dynamic page took a long time to generate.
For example, if a CGI program took 30 seconds to generate content (certainly not an ideal situation anywhere, but not completely unheard of), during this time the Web server would be unable to serve any other pages.
So although this model works, it would need to be redesigned to serve more users than just a few at a time. Web servers tend to take advantage of two different ways of handling this concurrency: multi-threading and multi-processing. Either they support the inetd module on Unix (which is a form of multi-processing), multi-threading, multi-processing, or a hybrid of multi-processing and multi-threading.

How Do You Choose a Web Server Platform?
Early Web servers used inetd to spawn a Web server process that could handle each Web browser request. They were fairly simple applications, and there was no expectation of them having to cope with a high number of hits, so this was a totally reasonable design decision to make at the time.
The easiest way to write a server application for Unix systems that needs to handle multiple connections is to take advantage of the inetd daemon, which handles all needed TCP/IP communication.
Normally, a server process has to handle listening for and accepting TCP connections as they are made. It must then make the choice to either juggle concurrent connections, or effectively block any new connections until the current one has been fully served and closed. The inetd daemon can do all this instead, by listening on the desired port (80, by default, for HTTP requests), and running a Web server process as it received each connection.
Using this method also makes administration of the machine easier. On most Unix machines, inetd is run by default, and is a very stable process. Web servers on the other hand, are more complex programs and can be prone to crashing or dying unexpectedly (although this has become less of a problem as these applications have matured). It also means that the 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.

How Do You Organise Web Servers for Performance?
No matter how good your Web server is or how powerful a machine it is running on, there is always going to be a limit to the number of pages it can serve in a given time frame -- particularly if you are relying on a high percentage of dynamic content. Dynamic content typically relies on heavy database usage or processing of other program code, which takes up many server-side resources.
Another problem comes up when running a Web site that has grown popular beyond its immediate means of serving content and ways to spread this load out -- usually across multiple machines, and sometimes across multiple sites.
There are a number of ways to achieve load balancing. Perhaps the simplest way is to split the content across multiple hosts. For example, you could place all static HTML files on one host, all images on another, and have the third run all CGI scripts. Of course, this is a very crude form of load balancing and, depending on the content of the site, may have very little effect.
For example, if a single CGI script is causing a bottleneck for a Web site, moving it to a separate server helps only the HTML, images, and other CGI scripts continue operating. Unfortunately, the heavily-loaded CGI script will still be a bottleneck for users who are utilising that particular resource. Thus, load balancing on a Web server requires a bit more sophistication to figure out the right mix of where to migrate workload.
In other words, a number of factors must be worked out before deciding on a correct solution for load balancing. In particular, examining the access patterns for the site is crucial to the performance tuning and load balancing process.
The list below outlines some possible mechanisms used to spread the load among Web servers. We have included a brief description of these mechanisms to provide a sense of how the Web server ties into external infrastructure and the clients that may direct traffic to them. The figure below illustrates the concept of a load-balanced Web server farm.

 DNS balancing (round-robin type)
 Hardware load balancing
 Software load balancing
 Reverse proxying
 Content spreading across hosts
 Content spreading across outsourced providers
Load Balancing - DNS
DNS balancing is one of the easiest ways to create a Web site that can handle more hits. It basically involves having multiple copies of the site on separate physical servers. However, each server must be identical.
Then, the DNS server for the hostname of the site such as www.extropia.com is set up to return multiple IP addresses for the site. The DNS server can do this by either just returning 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.


How Do You Configure Web Servers for Performance?
Of course, load balancing is really just a trick. We really have not improved the performance of a single Web server, we've just used external techniques to spread the load among many equivalent Web servers.
The most obvious way to accelerate a Web server is to boost the resources available to it. These resources include disk speed, memory, and CPU power.
Having reasonable CPU power is important for serving content; however, boosting it rarely helps a Web site unless the content being served is dynamic -- that is, the content is being generated by a program. Thus, most traditional content-based Web sites make use of the other techniques to increase Web server performance.
Naturally, the first step to serving content, such as an image or an HTML document, is to retrieve it from disk. Thus, it makes sense that disk access speed is increased. There are a variety of ways to increase I/O speed, and many of these are discussed in ServerWatch's Tuning a Server for High Performance.
However, disk configuration helps only so much. Ultimately, physics gets in the way, and you cannot retrieve data off of a rotating platter any faster. Thus, most Web sites get the best benefit out of adding raw memory to the server. The more memory a Web server has, the longer Web pages and images can be cached in memory instead of read from the disk over and over again.
Another technique is used to cache images and data is proxying. We talked about proxies earlier within the context of load balancing in front of several Web servers.
In the context of improving performance on a single Web server, an accelerating Web proxy sits in front of a traditional Web server and acts as a pipe that sucks down the content from the Web server and keeps it in memory. High performance proxies also go so far as to store the images and data they cannot keep in memory in a highly indexed data store on disk.
The difference between this data store and the Web site itself is that the data store is structured for extremely fast retrieval of content. A Web site directory structure on the other hand, is optimized for the organization of data from a human point of view.
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.


How Does Web Server Security Work?
There are two different levels of security for a Web server. On one level is the security of the data stream itself so that it may not be viewed or modified by a malicious third party. On another level is the security of the content itself -- the authentication and authorization of people to view and change that content.
As we mentioned earlier, URLs that begin with "https" are handled using SSL (now referred to as Transport Level Security -- TLS) algorithms. These algorithms basically work by setting up a secure, encrypted link between a Web browser and a Web server.
However, you might ask, what is SSL protecting anyway? There are really only two choices: SSL is protecting either the data being posted to the Web server or the retrieval of some confidential data from the Web server.
An example of a user posting confidential data to a Web server can be found in a typical Web store application. In such an application, the user is usually given a choice of presenting his or her credit card information to the order form. Although the Web server may not echo the user's credit card information again to the Web browser, the actual transmission of this information must to be treated as confidential.
Then, there is the issue of protecting content on the Web server that is being served. For example, an auction site may want to protect the bids a user is receiving for an item so that only the individual who posted the item sees all the bids.
In this case, it is not enough to simply encrypt the traffic being sent. The Web server must also be able to identify the user and the data she has access to. These two processes are referred to as authentication and authorization, respectively.
Web servers usually support authentication using a technique called basic authorization. In this technique, a Web server sends a special header to the user's Web browser asking for a username/password combination. This results in the Web browser popping up a log-in window.
Web servers are usually less sophisticated with regard to authorizing the viewing of data. Most Web servers merely allow the restriction of the reading of directories and files within a directory by group or user. More sophisticated options for determining whether a user is authorized to view files (such as time of day) must usually be programmed into a Web application.


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



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

1. Basic Servlet Structure
Here's the outline of a basic servlet that handles GET requests. GET requests, for those unfamiliar with HTTP, are requests made by browsers when the user types in a URL on the address line, follows a link from a Web page, or makes an HTML form that does not specify a METHOD. Servlets can also very easily handle POST requests, which are generated when someone creates an HTML form that specifies METHOD="POST". We'll discuss that in later sections.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SomeServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

// Use "request" to read incoming HTTP headers (e.g. cookies)
// and HTML form data (e.g. data the user entered and submitted)

// Use "response" to specify the HTTP response line and headers
// (e.g. specifying the content type, setting cookies).

PrintWriter out = response.getWriter();
// Use "out" to send content to browser
}
}
(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.*;

public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello World");
}
}
2.2 Compiling and Installing the Servlet
Note that the specific details for installing servlets vary from Web server to Web server. Please refer to your Web server documentation for definitive directions. The on-line examples are running on Java Web Server (JWS) 2.0, where servlets are expected to be in a directory called servlets in the JWS installation hierarchy. However, I placed this servlet in a separate package (hall) to avoid conflicts with other servlets on this server; you'll want to do the same if you are using a Web server that is used by other people and doesn't have a good infrastructure for "virtual servers" to prevent these conflicts automatically. Thus, HelloWorld.java actually goes in a subdirectory called hall in the servlets directory. Note that setup on most other servers is similar, and the servlet and JSP examples in the tutorial have also been tested using BEA WebLogic and IBM WebSphere 3.0. WebSphere has an excellent mechanism for virtual servers, and it is not necessary to use packages solely to prevent name conflicts with other users.
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.

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

public class HelloWWW extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(" "Transitional//EN\">\n" +
"\n" +

"Hello WWW\n" +
"\n" +
"

Hello WWW

\n" +
"");
}
}

4. Simple HTML-Building Utilities
It is a bit cumbersome to generate HTML with println statements. The real solution is to use Java Server Pages (JSP), which is discussed later in this tutorial. However, for standard servlets, there are two parts of the Web page (DOCTYPE and HEAD) that are unlikely to change and thus could benefit from being incorporated into a simple utility file.
The DOCTYPE line is technically required by the HTML spec, and although most major browsers ignore it, it is very useful when sending pages to formal HTML validators. These validators compare the HTML syntax of pages against the formal HTML specification, and use the DOCTYPE line to determine which version of HTML to check against. Their use is very 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;

public class ServletUtilities {
public static final String DOCTYPE =
"";

public static String headWithTitle(String title) {
return(DOCTYPE + "\n" +
"\n" +
"" + title + "\n");
}

// Other utilities will be shown later...
}
4.2 HelloWWW2.java (Download source code)
Here's a rewrite of the HelloWWW class that uses this.
package hall;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWWW2 extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(ServletUtilities.headWithTitle("Hello WWW") +
"\n" +
"

Hello WWW

\n" +
"");
}
}

1. 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.
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: . 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 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.
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.*;

/** Simple example of session tracking. See the shopping
* cart example for a more detailed one.
*


* Part of tutorial on servlets and JSP that appears at
* http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/
* 1999 Marty Hall; may be freely used or adapted.
*/

public class ShowSession extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
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) +
"\n" +
"

" + heading + "

\n" +
"

Information on Your Session:

\n" +
"\n" +
"\n" +
" \n" +
" \n" +
" \n" +
" \n" +
"
Info TypeValue\n" +
"
ID\n" +
"
" + session.getId() + "\n" +
"
Creation Time\n" +
"
" + new Date(session.getCreationTime()) + "\n" +
"
Time of Last Access\n" +
"
" + new Date(session.getLastAccessedTime()) + "\n" +
"
Number of Previous Accesses\n" +
"
" + accessCount + "\n" +
"
\n" +
"");

}

public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Here's a typical result, shown after visiting the page several without quitting the browser in between:


1. What types of servlets do you know?
A. There are two types of servlets - GenericServlet and HttpServlet.

2. What is the difference between HttpServlet and GenericServlet?
A. GenericServlet has a serve() method aimed to handle requests. HttpServlet extends GenericServlet and adds support for doGet(), doPost(), doHead() methods (HTTP 1.0) plus doPut(), doOptions(), doDelete(), doTrace() methods (HTTP 1.1). Both these classes are abstract.

3. What is the difference between Difference between doGet() and doPost()?
A doGet() method is limited with 2k of data to be sent, and doPost() method doesn't have
this limitation. A request string for doGet() looks like the following:
http://www.server.com/servlet?param1=value1&param2=value2&...&paramN=valueN
doPost() method call doesn't need a long text tail after a servlet name in a request. All
parameters are stored in a request itself, not in a request string, and it's impossible to
guess the data transmitted to a servlet only looking at a request string.

4. What are the methods in HttpServlet?
A. Methods of HttpServlet can be divided into 3 groups:
1. Initialization methods. These methods are inherited from GenericServlet interface. They
include init(ServletConfig config) (allowing initializing a servlet with the prepared or
existing config), ServletConfig getServletConfig() (the opposite method), destroy()
(removing a servlet), ServletContext getServletContext() (to obtain the context of a
servlet), log methods (logging servlet operations).
2. Request processing methods. These are the methods listed in point 2 of this document
plus getLastModified(HttpServletRequest request) method.
3. Programmer-defined methods. These methods are written by a programmer and are
not regulated by Sun's Servlet specification.

5. Why do you need to use session tracking?
A. Session tracking becomes necessary when you are exchanging any information with the visitor and don't want to lose this information. Session tracking is the most convenient and easy way of unique client identification.

6. What are the types of session tracking?
A. There are 4 types of session tracking: using cookies for identifying a client (reading a cookie each time a page is requested), using URL rewriting mechanism (appending the session id to each URL), using SSL built-in session tracking mechanisms and hiding the session information in hidden fields of a HTML form (e.g. login name).

7. What are cookies? Why are cookies widely used?
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.


9. Can I use JavaScript in servlets?
A. You can include JavaScript code to the servlet response (i.e. to the generated page), but
not to the servlet code itself.

10. What are the types of protocols used in HttpServlet?
A. HttpServlet class was developed for usage with HTTP and HTTPS protocols.

Servlet interview questions
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 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.
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
<%= request.getParameter("title") %>
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 Element Syntax Interpretation Notes
JSP Expression <%= expression %> Expression is evaluated and placed in output. XML equivalent is

expression
. Predefined variables are request, response, out, session, application, config, and pageContext (available in scriptlets also).
JSP Scriptlet <% code %> Code is inserted in service method. XML equivalent is

code
.
JSP Declaration <%! code %> Code is inserted in body of servlet class, outside of service method. XML equivalent is

code
.
JSP page Directive <%@ page att="val" %> Directions to the servlet engine about general setup. XML equivalent is
. Legal attributes, with default values in bold, are:
 import="package.class"
 contentType="MIME-Type"
 isThreadSafe="true|false"
 session="true|false"
 buffer="sizekb|none"
 autoflush="true|false"
 extends="package.class"
 info="message"
 errorPage="url"
 isErrorPage="true|false"
 language="java"
JSP include Directive <%@ include file="url" %> A file on the local system to be included when the JSP page is translated into a servlet. XML equivalent is
file="url"\>.
The URL must be a relative one. Use the jsp:include action to include a file at request time instead of translation time.
JSP Comment <%-- comment --%> Comment; ignored when JSP page is translated into servlet. If you want a comment in the resultant HTML, use regular HTML comment syntax of <-- comment -->.
The jsp:include Action page="relative URL"
flush="true"/> Includes a file at the time the page is requested. If you want to include the file at the time the page is translated, use the page directive with the include attribute instead. Warning: on some servers, the included file must be an HTML file or JSP file, as determined by the server (usually based on the file extension).
The jsp:useBean Action or

...
Find or build a Java Bean. Possible attributes are:
 id="name"
 scope="page|request|session|application"
 class="package.class"
 type="package.class"
 beanName="package.class"
The jsp:setProperty Action Set bean properties, either explicitly or by designating that value comes from a request parameter. Legal attributes are
 name="beanName"
 property="propertyName|*"
 param="parameterName"
 value="val"
The jsp:getProperty Action name="propertyName"
value="val"/> Retrieve and output bean properties.
The jsp:forward Action page="relative URL"/> Forwards request to another page.
The jsp:plugin Action attribute="value"*>
...
Generates OBJECT or EMBED tags, as appropriate to the browser type, asking that an applet be run using the Java Plugin.
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 %>
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:

Java 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() <>
Have a nice day!
<% } else { %>
Have a lousy day!
<% } %>
will get converted to something like:
if (Math.random() < 0.5) {
out.println("Have a nice day!");
} else {
out.println("Have a lousy day!");
}
If you want to use the characters "%>" inside a scriptlet, enter "%\>" instead. Finally, note that the XML equivalent of <% Code %> is

Code

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

Code

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"); %>
 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

For example, the XML equivalent of
<%@ page import="java.util.*" %>
is

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 nightmare of actually copying the HTML into each separate file. Here's some representative code:



Servlet Tutorial: JavaServer Pages (JSP) 1.0



HREF="Site-Styles.css"
TYPE="text/css">



<%@ include file="/navbar.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.



Using JavaServer Pages


CONTENT="JSP,JavaServer Pages,servlets">
CONTENT="A quick example of the four main JSP tags.">
HREF="My-Style-Sheet.css"
TYPE="text/css">


VLINK="#551A8B" ALINK="#FF0000">




Using JavaServer Pages




Some dynamic content created using various JSP mechanisms:


  • Expression.

    Your hostname: <%= request.getRemoteHost() %>.
  • Scriptlet.

    <% out.println("Attached GET data: " +
    request.getQueryString()); %>
  • Declaration (plus expression).

    <%! private int accessCount = 0; %>
    Accesses to page since server reboot: <%= ++accessCount %>
  • Directive (plus expression).

    <%@ page import = "java.util.*" %>
    Current date: <%= new Date() %>






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

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



What's New
HREF="My-Style-Sheet.css"
TYPE="text/css">


VLINK="#551A8B" ALINK="#FF0000">




What's New at JspNews.com




Here is a summary of our four most recent news stories:










8.2 The jsp:useBean Action
This action lets you load in a JavaBean to be used in the JSP page. This is a a very useful capability because it lets you exploit the reusability of Java classes without sacrificing the convenience that JSP adds over servlets alone. The simplest syntax for specifying that a bean should be used is:

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.



Reusing JavaBeans in JSP
HREF="My-Style-Sheet.css"
TYPE="text/css">





Reusing JavaBeans in JSP




property="message"
value="Hello WWW" />

Message:




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

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

Body

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.
Atribute Usage
id Gives a name to the variable that will reference the bean. A previous bean object is 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.
scope 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 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.
type Specifies the type of the variable that will refer to the object. This must match the 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.
beanName Gives the name of the bean, as you would supply it to the instantiate method of 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:

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

...
property="someProperty" ... />

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:
Attribute Usage
name This required attribute designates the bean whose property will be set. The jsp:useBean element must appear before the jsp:setProperty element.
property This required attribute indicates the property you want to set. However, there is 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.
value 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 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."
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 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.



Reusing JavaBeans in JSP
HREF="My-Style-Sheet.css"
TYPE="text/css">





Reusing JavaBeans in JSP







Some
digit primes:



Here's a typical result:

8.5 The jsp:getProperty Action
This element retrieves the value of a bean property, converts it to a string, and inserts it into the output. The two required attributes are name, the name of a bean previously referenced via jsp:useBean, and property, the property whose value should be inserted. Here's an example; for more examples, see Sections 8.2 and 8.4.

...


  • Number of items:

  • Cost of each:


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.

" />
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
<%-- comment --%> A JSP comment. Ignored by JSP-to-scriptlet translator. Any embedded JSP scripting elements, directives, or actions are ignored.
An HTML comment. Passed through to resultant HTML. Any embedded JSP scripting elements, directives, or actions are executed normally.
<\% 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

Provides classes allowing the processing of XML documents.
There are two types of XML parsers, validating and nonvalidating. Validating parsers check a document's contents against a set of specific rules stating what elements are allowed in a document and in what order they must appear. These rules appear in an XML document as an optional XML structure called a document type definition, or DTD. Nonvalidating parsers are smaller and faster, but they don't check documents against the DTD; they only that the document is structurally well-formed.

JDBC Drivers

JDBC technology drivers fit into one of four categories:
1. 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.
2. 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.
3. 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.
4. 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.

There are four types of JDBC database driver:
Driver type code Explanation Comment
1 The JDBC/ODBC bridge driver A piece of native C-code that translates a JDBC call to an ODBC call. Use this driver for development, not for industrial-strength application environments. Note that you have to have an ODBC database driver manager + an ODBC database driver installed on the server in addition to the JDBC/ODBC bridge.
2 Native API partly java driver A piece of native C-code that translates a java JDBC call to a native database call level API. Use this driver for development and deployment. Due to its native code, this driver can only be used by Java Applications with full computer access (i.e. not Applets).
3 JDBC-Net pure Java driver A piece of pure java code that translates an incoming JDBC call to an outgoing database Net protocol call (such as SQL*Net). Use this driverfor development and deployment. Flexible and powerful, this driver can be used by any Java component and requires only connect access to work.
4 Native protocol pure Java driver A piece of pure java code that translates an incoming JDBC call to an outgoing database native protocol call (such as Oracle CLI). Use this driver for development and deployment. This driver type is the recommended one for server-side java development unless a type 2 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.
5. 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).
6. 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.
7. Hidden form fields. HTML forms have an entry that looks like the following: . 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 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.

Load Balancing Web Applications
This article offers an overview of several approaches to load balancing on Web application server clusters. A cluster is a group of servers running a Web application simultaneously, appearing to the world as if it were a single server. To balance server load, the system distributes requests to different nodes within the server cluster, with the goal of optimizing system performance. This results in higher availability and scalability -- necessities in an enterprise, Web-based application.
High availability can be defined as redundancy. If one server cannot handle a request, can other servers in the cluster handle it? In a highly available system, if a single Web server fails, then another server takes over, as transparently as possible, to process the request.
Scalability is an application's ability to support a growing number of users. If it takes an application 10 milliseconds(ms) to respond to one request, how long does it take to respond to 10,000 concurrent requests? Infinite scalability would allow it to respond to those in 10 ms; in the real world, it's somwhere between 10 ms and a logjam. Scalability is a measure of a 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.
 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.
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.

Caching data in WebLogic Workspaces
Accessing a DBMS is an operation that uses considerable resources. If your program accesses frequently used data that can be shared among applications or can persist between connections, you can store the data in a WebLogic Workspace. Data in a Workspace can be obtained, altered, and either kept private or shared quickly by any application without repeatedly querying the DBMS.
WebLogic provides bidirectional asynchronous service to any client application. You can write a server-side class that queries the DBMS and maintains Workspace contents for applications. Your server-side class can generate events that notify client applications of changes in Workspace contents.
Speeding up applets with archives
The JDBC protocol is also resource-intensive. An applet that uses JDBC directly will need to download many classes, which takes time. WebLogic has utilities that scan an HTML server log and create a zip file of classes for an applet. Using this zip file by referencing it in the ARCHIVE attribute of your applet will improve performance when the applet first starts.
An even faster alternative is to avoid JDBC in the applet when possible, and obtain DBMS data in HTML form from servlets instead. Servlets can run queries for the applet, and/or retrieve data from Workspaces and supply it as HTML. In concert with WebLogic processes which asynchronously maintain this data, the performance of your applications will improve.
Generally, any time you can avoid accessing the DBMS you can improve performance.
Row caching: WebLogic JDBC and Oracle
WebLogic JDBC is not just a passive proxy for JDBC calls. It will, by default, pre-fetch up to 25 rows for any query sent by a WebLogic client, and supply them in an array to the WebLogic JDBC driver. The driver can then make next() calls without each next() call requiring a round-trip to WebLogic and to the DBMS and back. This 25-row default can be altered via the property weblogic.t3.cacheRows, and can also be changed by the client via a call to the Connection.cacheRows(int) method.
Oracle also provides array fetching to its clients, and jDriver for Oracle supports this feature. By default, jDriver for Oracle will array-fetch up to 100 rows from the DBMS. This number can be altered via the property weblogic.oci.cacheRows.
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.

Designing your application for best performance
The large majority of the performance to be gained or lost in a DBMS application is not in the application language, but in how the application is designed. The number and location of clients, size and structure of DBMS tables and indexes, and the number and types of queries all affect application performance.
Below are general hints that apply to all DBMSes. It is also important to be familiar with the performance documentation of the specific DBMS that you use in your application.
1. Streamline data before the result crosses the network
Most serious performance problems in DBMS applications come from moving raw data around needlessly, whether it is across the network or just in and out of cache in the DBMS. A good method for minimizing this waste is to put your logic where the data is -- in the DBMS, not in the client -- even if the client is running on the same box as the DBMS. In fact, for some DBMSes a fat client and a fat DBMS sharing one CPU is a performance disaster.
Most DBMSes provide stored procedures, an ideal tool for putting your logic where your data is. There is a significant difference in performance between a client that calls a stored procedure to update 10 rows, and another client that fetches those rows, alters them, and sends update statements to save the changes to the DBMS.
You should also review the DBMS documentation on managing cache memory in the DBMS. Some DBMSes (Sybase, for example) provide the means to partition the virtual memory allotted to the DBMS, and to guarantee certain objects exclusive use of some fixed areas of cache. This means that an important table or index can be read once from disk and remain available to all clients without having to access the disk again.
2. Use built-in DBMS set-based processing
SQL is a set processing language. DBMSes are designed from the ground up to do set-based processing. Accessing a database one row at a time is, without exception, slower than set-based processing and, on some DBMSes is poorly implemented. For example, it will always be faster to update each of four tables one at a time for all the hundred employees represented in the tables than to alter each table 100 times, once for each employee.
Understanding set-based methodology can be very useful. Many complicated processes that were originally thought too complex to do any other way but row-at-a-time have been rewritten using set-based processing, resulting in improved performance. For example, a major payroll application was converted from a huge slow COBOL application to four stored procedures running in series, and what took hours on a multi-CPU machine now takes fifteen minutes with many fewer resources used.
3. Make your queries as smart as possible
Frequently customers ask how to tell how many rows will be coming back in a given result set. This is a valid question, but there is no easy answer. The only way to find out without fetching all the rows is by issuing the same query using the count keyword:
SELECT count(*) from myTable, yourTable where ...
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
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.
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.





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.
3. Can the JDBC-ODBC Bridge be used with applets?
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.
4. How do I start debugging problems related to the JDBC API?
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.
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.
6. What JDBC technology-enabled drivers are available?
See our web page on JDBC technology-enabled drivers for a current listing.

7. What documentation is available for the JDBC API?
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.
9. What causes the "No suitable driver" error?
"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.

10. Why isn't the java.sql.DriverManager class being found?
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.
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.
14. Is the JDBC-ODBC Bridge multi-threaded?
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 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.
20. If I use the JDBC API, do I have to use ODBC underneath?
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?
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, the Extensible Markup Language, is a universal syntax for describing and structuring data independent from the application logic. XML can be used to define unlimited languages for specific industries and applications.
Q. Who developed XML?
A. XML is an activity of the World Wide Web Consortium (W3C). The XML development effort started in 1996.
A diverse group of markup language experts, from industry to academia, developed a simplified version of SGML (Standard Generalized Markup Language) for the Web. In February 1998, XML 1.0 specification became a recommendation by the W3C.
Q. What are the key benefits of XML?
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.
Q. What are the applications of XML?
A. XML is poised to play a prominent role as a data interchange format in B2B Web applications such as e-commerce, supply-chain management, workflow, and application integration. Another use of XML is for structured information management, including information from databases. XML also supports media-independent publishing, allowing documents to be written once and published in multiple media formats and devices. On the client, XML can be used to create customized views into data.
Q. What is the relationship between XML and Java technology?
A. XML and the Java technology are complementary. Java technology provides 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.
Q. What are the benefits of using Java technology with XML?
A. Java technology offers a substantial productivity boost for software developers compared to programming languages such as C or C++. In addition, developers using the Java platform can create sophisticated programs that are reusable and maintainable compared to programs written with scripting languages. Using XML and Java together, developers can build sophisticated, interoperable Web applications more quickly and at a lower cost.
Q. What XML-related activities is Sun participating in?
A. Sun is actively participating in W3C working groups for XML Stylesheet/Transformation Language (XSL/T), XML Schema, Xlink, and XML Query. Sun is also participating in a number of other industry consortia including Oasis, XML.org, and Apache.
Q. Where can I find additional documentation?
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. Where can I send comments and suggestions?
A. For feedback on the project, please send email to xml-feedback@sun.com.
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


Java API for XML Processing (JAXP)
Q. What is Java API for XML Processing (JAXP)?
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.
To achieve the goal of XML processor independence, an application should limit itself to the JAXP API and avoid implementation-dependent APIs. This may or may not be easy depending on the application. JAXP includes industry standard APIs such as DOM and SAX.
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.
Q. Where can I read more about JAXP?
A. See the JAXP FAQ for more information.
Back to Top


Java Architecture for XML Binding (JAXB)
Q. What is Java Architecture for XML Binding (JAXB)?
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. SAX is an event-driven XML parser that is appropriate for high-speed processing of XML because it does not produce a representation of the data in memory. DOM, on the other hand, produces an in-memory data representation, which allows an application to manipulate the contents in memory. Both SAX and DOM automatically perform structure validation. An application could perform content validation with SAX and DOM, but such an application must provide the necessary extra code, which might be complicated, error-prone, and difficult to maintain.
A JAXB application can perform structure and content validation with Java classes that it generates from a schema. A JAXB application builds an in-memory data structure, like a DOM, by marshalling an XML document to build a content tree, which contains objects that are instances of the derived classes. However, unlike a DOM tree, a content tree is specific to one source schema, does not contain extra tree-manipulation functionality, allows access to its data with the derived classes' accessor methods, and is not built dynamically. For these reasons, a JAXB application uses memory more efficiently than a DOM application does. If the content of a document is more dynamic and not well-constrained, DOM and SAX are more appropriate than JAXB for processing XML content that does not have a well-known schema prior to processing the content.
Q. How does JAXB work?
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
2. Compile the Java source code.
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.
 Access and modify the data.
Optionally validate the modifications to the data relative to the constraints expressed in the XML Schema
 Marshal the data to new XML documents.
Q. Who is involved in developing JAXB?
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 xml.org.
Q. Where can I read more about JAXB?
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


Java API for XML Messaging (JAXM)
Q. What is the Java API for XML Messaging (JAXM)?
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.
Q: What standards is JAXM based on?
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.
Q. Do I have to use the J2EE platform to use JAXM?
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.
Q. What is a messaging provider?
A: A messaging provider is a service that works with the messaging infrastructure to route and transmit messages. What it does is completely transparent to the client sending or receiving a message. An application that uses a messaging provider must use a connection that goes to the provider, called a ProviderConnection object in the JAXM API. Using a messaging provider also requires some deployment and configuration. Normally, a client using a messaging provider runs in a container -- either a servlet or a J2EE container. At deployment time, the client needs to give the container information about the messaging provider. In the future, there will be a deployment tool that makes this easy.
Q. Do I have to use a messaging provider?
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.
Q. Can a JAXM message be routed to more than one destination?
Yes. Intermediate recipients can be specified in a message's header. One way this capability can be used is to automate business processes. For example, two businesses can agree to the conditions under which they exchange XML documents so that they can implement the automatic generation of messages and responses. Assume that two businesses have an arrangement specifying that purchase orders will go first to the order entry department, then to the order confirmation department, then to the shipping department, and finally to the billing department. Each department is an intermediate recipient (called an actor). After an actor has done its part, it removes everything in the header that relates to it and sends the message on to the next actor listed in the header.
Q. Can I use ebXML headers in a JAXM message?
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


Java API for XML Registries (JAXR)
Q. What is the Java API for XML Registries (JAXR)?
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?
A. Implementations of JAXR providers may use the Jav API for XML-Based RPC (JAX-RPC) for communication between JAXR providers and registry providers that export a SOAP based RPC-like interface (for example, UDDI).
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?
A. That option was considered. Meeting the additional requirements of XML Registries requires an elaborate information model. The JNDI API has an existing information model that is constrained by design to address the requirements for directory services. Extending the JNDI API would overly constrain the JAXR API and would create backward compatibility issues for the JNDI API.
Q. What is the purpose of Association in the JAXR information model? It is not used anywhere in the API.
A. An Association relates two RegistryObjects to each other. An Association may be defined between two objects in the registry and submitted using the GenericLifeCycleManager's saveObjects method.
Q. What is the purpose of Classification in the JAXR information model? It is not used anywhere in the API.
A. A Classification classifies a RegistryObject. A Classification may be defined for a RegistryObject and submitted using the GenericLifeCycleManager's saveObjects method.
Q. Why is JAXR an abstraction API and not targeted to a specific registry such as UDDI or ebXML?
A. An abstraction-based JAXR API gives developers the ability to write registry client programs that are portable across different target registries. This is consistent with the Java philosophy of Write Once, Run Anywhere. It also enables value-added capabilities beyond what the underlying registries are capable of. For example, a non-JAXR UDDI client does not have the ability to do taxonomy browsing and taxonomy-aware smart queries, which are available to a JAXR client for UDDI.
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


Java API for XML-Based RPC (JAX-RPC)
Q. What is the Java API for XML-Based RPC (JAX-RPC)?
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.
Q. How does JAX-RPC use SOAP?
A. Please refer to JSR-101.
Q. What is RPC?
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.
Q. How is XML related to RPC?
A. The remote procedure call is represented by an XML-based protocol, such as SOAP. In addition to defining envelope structure and encoding rules, the SOAP specification defines a convention for representing remote procedure calls and responses.
Q. What does JAX-RPC have to do with Web services?
A. An XML-based RPC server application can define, describe, and export a Web service as an RPC-based service. WSDL (Web Service Description Language) specifies an XML format for describing a service as a set of endpoints operating on messages. With the JAX-RPC API, developers can implement clients and services described by WSDL.
Q. What are the modes of interaction between clients and JAX-RPC services?
A. There are three different modes:
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.
Q. Can a remote method call or response carry service context information?
A. Yes. For example, it may carry a unique transaction identifier or digital signature.
Q. Why doesn't xrpcc generate a WSDL file?
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 placed in the sourcepath directory and then you can easily delete them. The WSDL file will still be placed in the current directory or the directory specified by the -d option.
Back to Top


Java 2 Platform, Enterprise Edition
Q. Does the Java 2 Platform, Enterprise Edition (J2EE) use XML?
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.
Q. Can I generate dynamic XML documents using JSP pages?
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.
How does the JavaServer Pages technology work?
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.

JSP pages are not restricted to any specific platform or web server. The JSP specification represents a broad spectrum of industry input.
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.
Why do I need JSP technology if I already have servlets?
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.
Which web servers support JSP technology?
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.
Is Sun providing a reference implementation for the JSP specification?
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.
How is JSP technology different from other products?
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.
Where do I get more information on JSP technology?
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.

Technical FAQ
What is a JSP page?
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.

The exact format of a JSP page is described in the JSP specification..
How do JSP pages work?
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.
How is a JSP page invoked and compiled?
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.
What is the syntax for JavaServer Pages technology?
The syntax card and reference can be viewed or downloaded from our website.
Can I create XML pages using JSP technology?
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.
Can I generate and manipulate JSP pages using XML tools?
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.
How do I use JavaBeans components (beans) from a JSP page?
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
practices that together enable solutions for developing, deploying, and managing multitier
server-centric applications. Building on the Java 2 Platform, Standard Edition (J2SE), the
J2EE platform adds the capabilities necessary to provide a complete, stable, secure, and
fast Java platform to the enterprise level. It provides value by significantly reducing the
cost and complexity of developing and deploying multitier solutions, resulting in services
that can be rapidly deployed and easily enhanced.

Q: What are the main benefits of the J2EE platform?

The J2EE platform provides the following:

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
coupled, asynchronous way. The J2EE platform also offers CORBA support for tightly linking
systems through remote method calls. In addition, the J2EE platform has J2EE Connectors for
linking to enterprise information systems such as ERP systems, packaged financial
applications, and CRM applications.

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?

Yes, if the other implementations are WS-I compliant.

Q: What technologies are included in the J2EE platform?

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.

Q: What's new in the J2EE 1.4 platform?

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 Java
Servlet and JavaServer Pages (JSP) technologies. Servlets now support request listeners and
enhanced filters. JSP technology has simplified the page and extension development models
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.

Q: Which version of the platform should I use now -- 1.4 or 1.3?

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
v1.4 versions of their product before the spring.

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.

Q: How can I learn about the J2EE platform?

For more information about the J2EE platform and how to get the specification, see
http://java.sun.com/j2ee/.

The most effective way to learn about the J2EE platform and what's new in the J2EE 1.4
platform is to get hands on experience with the APIs by using the J2EE 1.4 SDK. The J2EE 1.4
SDK provides a J2EE 1.4 compatible application server as the foundation to develop and
deploy Web services enabled, multitier enterprise applications. You can download the J2EE
1.4 SDK for free at http://java.sun.com/j2ee/downloads/index.html

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.

What tools can I use to build J2EE applications?

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.

Q: Who needs the J2EE platform?

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.

Q: What do you mean by "Free"?


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
Edition 8 with your software distribution. When we say "Free", we mean "Free for All".

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.

Q: Are there compatibility tests for the J2EE platform?

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.

Q: What is the difference between being a J2EE licensee and being J2EE compatible?

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.






Questions and Answers

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?
The Collections API is a set of classes and interfaces that support operations on collections of objects.
14. What is the List interface?
The List interface provides support for ordered collections of objects.
15. How does Java handle integer overflows and underflows?
It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.
16. What is the Vector class?
The Vector class provides the capability to implement a growable array of objects
17. What modifiers may be used with an inner class that is a member of an outer class?
A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.
18. If a method is declared as protected, where may the method be accessed?
A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.
19. What is an Iterator interface?
The Iterator interface is used to step through the elements of a Collection.
20. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?
Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.
21. What is the difference between yielding and sleeping?
When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state.
22. Is sizeof a keyword?
The sizeof operator is not a keyword.
23. What are wrapped classes?
Wrapped classes are classes that allow primitive types to be accessed as objects.
24. Does garbage collection guarantee that a program will not run out of memory?
No, it doesn't. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection
25. What is the difference between preemptive scheduling and time slicing?
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.
26. Name Component subclasses that support painting.
The Canvas, Frame, Panel, and Applet classes support painting.
27. What is a native method?
A native method is a method that is implemented in a language other than Java.
28. How can you write a loop indefinitely?
for(;;)--for loop; while(true)--always true, etc.
29. Can an anonymous class be declared as implementing an interface and extending a class?
An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.
30. What is the purpose of finalization?
The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.
31. Which class is the superclass for every class.
Object
32. What invokes a thread's run() method?
After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.
33. What is the difference between the Boolean & operator and the && operator?
If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.
Operator & has no chance to skip both sides evaluation and && operator does. If asked why, give details as above.
34. What is the GregorianCalendar class?
The GregorianCalendar provides support for traditional Western calendars.
35. What is the SimpleTimeZone class?
The SimpleTimeZone class provides support for a Gregorian calendar.
36. Which Container method is used to cause a container to be laid out and redisplayed?
validate()
37. What is the Properties class?
The properties class is a subclass of Hashtable that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used.
38. What is the purpose of the Runtime class?
The purpose of the Runtime class is to provide access to the Java runtime system.
39. What is the purpose of the System class?
The purpose of the System class is to provide access to system resources.
40. What is the purpose of the finally clause of a try-catch-finally statement?
The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.
41. What is the Locale class?
The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.
42. What must a class do to implement an interface?
It must provide all of the methods in the interface and identify the interface in its implements clause.
43. What is the purpose of the wait(), notify(), and notifyAll() methods?
The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to communicate each other.
44. What is an abstract method?
An abstract method is a method whose implementation is deferred to a subclass.
45. What are the high-level thread states?
The high-level thread states are ready, running, waiting, and dead.
46. What is the difference between a static and a non-static inner class?
A non-static inner class may have object instances that are associated with instances of the class's outer class. A static inner class does not have any object instances.
47. What is an object's lock and which object's have locks?
An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.
48. When can an object reference be cast to an interface reference?
An object reference be cast to an interface reference when the object implements the referenced interface.
49. What is the difference between a Window and a Frame?
The Frame class extends Window to define a main application window that can have a menu bar.
50. What do heavy weight components mean?
51. Heavy weight components like Abstract Window Toolkit (AWT), depend on the local windowing toolkit. For example, java.awt.Button is a heavy weight component, when it is running on the Java platform for Unix platform, it maps to a real Motif button. In this relationship, the Motif button is called the peer to the java.awt.Button. If you create two Buttons, two peers and hence two Motif Buttons are also created. The Java platform communicates with the Motif Buttons using the Java Native Interface. For each and every component added to the application, there is an additional overhead tied to the local windowing system, which is why these components are called heavyweight.
52. Which package has light weight components?
javax.Swing package. All components in Swing, except JApplet, JDialog, JFrame and JWindow are lightweight components.
53. What are peerless components?
The peerless components are called light weight components.
54. What is the difference between the Font and FontMetrics classes?
The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object.
55. What happens when a thread cannot acquire a lock on an object?
If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available.
56. What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?
The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.
57. What classes of exceptions may be caught by a catch clause?
A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types.
58. If a class is declared without any access modifiers, where may the class be accessed?
A class that is declared without any access modifiers is said to have package or friendly access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.
59. What is the Map interface?
The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values.
60. Does a class inherit the constructors of its superclass?
A class does not inherit constructors from any of its superclasses.
61. Name primitive Java types.
The primitive types are byte, char, short, int, long, float, double, and boolean.
62. Which class should you use to obtain design information about an object?
The Class class is used to obtain information about an object's design.
63. How can a GUI component handle its own events?
A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener.
64. How are the elements of a GridBagLayout organized?
The elements of a GridBagLayout are organized according to a grid. However, the elements are of different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.
65. What advantage do Java's layout managers provide over traditional windowing systems?
Java uses layout managers to lay out components in a consistent manner across all windowing platforms. Since Java's layout managers aren't tied to absolute sizing and positioning, they are able to accommodate platform-specific differences among windowing systems.
66. What are the problems faced by Java programmers who don't use layout managers?
Without layout managers, Java programmers are faced with determining how their GUI will be displayed across multiple windowing systems and finding a common sizing and positioning that will work within the constraints imposed by each windowing system.
67. What is the difference between static and non-static variables?
A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.
68. What is the difference between the paint() and repaint() methods?
The paint() method supports painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread.
69. What is the purpose of the File class?
The File class is used to create objects that provide access to the files and directories of a local file system.
70. How does multithreading take place on a computer with a single CPU?
The operating system's task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.
71. What restrictions are placed on method overloading?
Two methods may not have the same name and argument list but different return types.
 If two (or more) methods of a class (whether both declared in the same class, or both inherited by a class, or one declared and one inherited) have the same name but different signatures, then the method name is said to be overloaded.
 The signature of a method consists of the name of the method and the number and types of formal parameters in particular order. A class must not declare two methods with the same signature, or a compile-time error occurs. Return types are not included in the method signature.


72. What restrictions are placed on method overriding?
Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. The overriding method may not throw any exceptions that may not be thrown by the overridden method.
73. What is casting?
There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.
74. Name Container classes.
Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane
75. What class allows you to read objects directly from a stream?
The ObjectInputStream class supports the reading of objects from input streams.
76. How are this() and super() used with constructors?
this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.
77. How is it possible for two String objects with identical values not to be equal under the == operator?
The == operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but located indifferent areas of memory.
78. What an I/O filter?
An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.
79. What is the Set interface?
The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements.
80. What is the List interface?
The List interface provides support for ordered collections of objects.
81. What is the purpose of the enableEvents() method?
The enableEvents() method is used to enable an event for a particular object. Normally, an event is enabled when a listener is added to an object for a particular event. The enableEvents() method is used by objects that handle events by overriding their event-dispatch methods.
82. What is the difference between the File and RandomAccessFile classes?
The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.
83. What interface must an object implement before it can be written to a stream as an object?
An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.
84. What is the ResourceBundle class?
The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program's appearance to the particular locale in which it is being run.
85. What is the difference between a Scrollbar and a ScrollPane?
A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling.
86. What is a Java package and how is it used?
A Java package is a naming context for classes and interfaces. A package is used to create a separate name space for groups of classes and interfaces. Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces.
87. What are the Object and Class classes used for?
The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program.
88. What is Serialization and deserialization?
Serialization is the process of writing the state of an object to a byte stream.
Deserialization is the process of restoring these objects.
89. Does the code in finally block get executed if there is an exception and a retrun statement in a catch block?
If an exception occurs and there is a return statement in catch block, the finally block is still executed. The finally block will not be executed when the System.exit(1) statement is executed earlier or the system shut down earlier or the memory is used up earlier before the thread goes to finally block.
90. How you restrict a user to cut and paste from the html page ?
Using javascript to lock keyboard keys. It is one of solutions.
91. Is Java a super set of JavaScript ?
No. They are completely different. Some syntax may be similar.
Return to top

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. getInputStream() and getOutputStream() are the two methods available in Socket class.
6. When MalformedURLException and UnknownHostException throws?
When the specified URL is not connected then the URL throw MalformedURLException and If InetAddress’ methods getByName and getLocalHost are unable to resolve the host name they throw an UnknownHostException.
7. What does RMI stand for?
It stands for Remote Method Invocation.
8. What is RMI?
RMI is a set of APIs that allows to build distributed applications. RMI uses interfaces to define remote objects to turn local method invocations into remote method invocations.
Return to top

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:
E.g.
Class.forName("jdbc.DriverXYZ");
9. What Class.forName will do while loading drivers?
It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS.
10. How can you make the connection?
In establishing a connection is to have the appropriate driver connect to the DBMS. The following line of code illustrates the general idea:
E.g.
String url = "jdbc:odbc:Fred";
Connection con = DriverManager.getConnection(url, "Fernanda", "J8");
11. How can you create JDBC statements?
A Statement object is what sends your SQL statement to the DBMS. You simply create a Statement object and then execute it, supplying the appropriate execute method with the SQL statement you want to send. For a SELECT statement, the method to use is executeQuery. For statements that create or modify tables, the method to use is executeUpdate. E.g. It takes an instance of an active connection to create a Statement object. In the following example, we use our Connection object con to create the Statement object stmt :
Statement stmt = con.createStatement();
12. How can you retrieve data from the ResultSet?
First JDBC returns results in a ResultSet object, so we need to declare an instance of the class ResultSet to hold our results. The following code demonstrates declaring the ResultSet object rs.
E.g.
ResultSet rs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");

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;
E.g.
CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();
16. How to Retrieve Warnings?
SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object
E.g.
SQLWarning warning = stmt.getWarnings();
if (warning != null) {

while (warning != null) {
System.out.println("Message: " + warning.getMessage());
System.out.println("SQLState: " + warning.getSQLState());
System.out.print("Vendor error code: ");
System.out.println(warning.getErrorCode());
warning = warning.getNextWarning();
}
}
17. How to Make Updates to Updatable Result Sets?
Another new feature in the JDBC 2.0 API is the ability to update rows in a result set using methods in the Java programming language rather than having to send an SQL command. But before you can take advantage of this capability, you need to create a ResultSet object that is updatable. In order to do this, you supply the ResultSet constant CONCUR_UPDATABLE to the createStatement method.
E.g.
Connection con = DriverManager.getConnection("jdbc:mySubprotocol:mySubName");
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = ("SELECT COF_NAME, PRICE FROM COFFEES");
Return to top

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?
Implicit objects are created by the web container and contain information related to a particular request, page, or application. They are request, response, pageContext, session, application, out, config, page and exception.
4. How many JSP scripting elements and what are they?
There are three scripting language elements: declarations, scriptlets, and expressions.
5. Why are JSP pages the preferred API for creating a web-based client program?
Because no plug-ins or security policy files are needed on the client systems(applet does). Also, JSP pages enable cleaner and more module application design because they provide a way to separate applications programming from web page design. This means personnel involved in web page design do not need to understand Java programming language syntax to do their jobs.
6. Is JSP technology extensible?
YES. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.
7. what are the two kinds of comments in JSP and whats the difference between them
<%-- JSP Comment --%>

Return to top

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?
ServeltRequest: which encapsulates the communication from the client to the server.
ServletResponse: which encapsulates the communication from the servlet back to the client.
ServletRequest and ServletResponse are interfaces defined by the javax.servlet package.
7. What information that the ServletRequest interface allows the servlet 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. The input stream, ServletInputStream.Servlets use the input stream to get data from clients that use application protocols such as the HTTP POST and PUT methods.
8. What information that the ServletResponse interface gives the servlet methods for replying to the client?
It Allows the servlet to set the content length and MIME type of the reply. Provides an output stream, ServletOutputStream and a Writer through which the servlet can send the reply data.
9. If you want a servlet to take the same action for both GET and POST request, what you should do?
Simply have doGet call doPost, or vice versa.
10. What is the servlet life cycle?
Each servlet has the same life cycle:
A server loads and initializes the servlet (init())
The servlet handles zero or more client requests (service())
The server removes the servlet (destroy()) (some servers do this step only when they shut down)
11. Which code line must be set before any of the lines that use the PrintWriter?
setContentType() method must be set before transmitting the actual document.
12. How HTTP Servlet handles 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.
13. When using servlets to build the HTML, you build a DOCTYPE line, why do you do that?
I know all major browsers ignore it even though the HTML 3.2 and 4.0 specifications require it. But building a DOCTYPE line tells HTML validators which version of HTML you are using so they know which specification to check your document against. These validators are valuable debugging services, helping you catch HTML syntax errors.(http://validator.w3.org and http://www.htmlhelp.com/tools/validator/ are two major online validators)
Return to top

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.
2. What is EJB role in J2EE?
EJB technology is the core of J2EE. It enables developers to write reusable and portable server-side business logic for the J2EE platform.
3. What is the difference between EJB and Java beans?
EJB is a specification for J2EE server, not a product; Java beans may be a graphical component in IDE.
4. What are the key features of the EJB technology?
1. EJB components are server-side components written entirely in the Java programming language
2. EJB components contain business logic only - no system-level programming & services, such as transactions, security, life-cycle, threading, persistence, etc. are automatically managed for the EJB component by the EJB server.
3. EJB architecture is inherently transactional, distributed, portable multi-tier, scalable and secure.
4. EJB components are fully portable across any EJB server and any OS.
5. EJB architecture is wire-protocol neutral--any protocol can be utilized like IIOP,JRMP, HTTP, DCOM,etc.
5. What are the key benefits of the EJB technology?
 Rapid application development
 Broad industry adoption
 Application portability
 Protection of IT investment
6. How many enterprice beans?
There are three kinds of enterprise beans:
 session beans,
 entity beans, and
 message-driven beans.
7. What is message-driven bean?
A message-driven bean combines features of a session bean and a Java Message Service (JMS) message listener, allowing a business component to receive JMS. A message-driven bean enables asynchronous clients to access the business logic in the EJB tier.
8. What is Entity Bean and Session Bean ?
Entity Bean is a Java class which implements an Enterprise Bean interface and provides the implementation of the business methods. There are two types: Container Managed Persistence(CMP) and Bean-Managed Persistence(BMP).
Session Bean is used to represent a workflow on behalf of a client. There are two types: Stateless and Stateful. Stateless bean is the simplest bean. It doesn't maintain any conversational state with clients between method invocations. Stateful bean maintains state between invocations.
Return to top

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.
2. What are the components of J2EE application?
A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its related classes and files and communicates with other components. The J2EE specification defines the following J2EE components:
 Application clients and applets are client components.
 Java Servlet and JavaServer PagesTM (JSPTM) technology components are web components.
 Enterprise JavaBeansTM (EJBTM) components (enterprise beans) are business components.
 Resource adapter components provided by EIS and tool vendors.
3. Is J2EE application only a web-based?
NO. A J2EE application can be web-based or non-web-based. if an application client executes on the client machine, it is a non-web-based J2EE application. The J2EE application can provide a way for users to handle tasks such as J2EE system or application administration. It typically has a graphical user interface created from Swing or AWT APIs, or a command-line interface. When user request, it can open an HTTP connection to establish communication with a servlet running in the web tier.
4. Are JavaBeans J2EE components?
NO. JavaBeans components are not considered J2EE components by the J2EE specification. JavaBeans components written for the J2EE platform have instance variables and get and set methods for accessing the data in the instance variables. JavaBeans components used in this way are typically simple in design and implementation, but should conform to the naming and design conventions outlined in the JavaBeans component architecture.
5. Is HTML page a web component?
NO. Static HTML pages and applets are bundled with web components during application assembly, but are not considered web components by the J2EE specification. Even the server-side utility classes are not considered web components,either.
6. What is the container?
A container is a runtime support of a system-level entity. Containers provide components with services such as lifecycle management, security, deployment, and threading.
7. What is the web container?
Servlet and JSP containers are collectively referred to as Web containers.
8. What is the thin client?
A thin client is a lightweight interface to the application that does not have such operations like query databases, execute complex business rules, or connect to legacy applications.
9. What are types of J2EE clients?
 Applets
 Application clients
 Java Web Start-enabled rich clients, powered by Java Web Start technology.
 Wireless clients, based on Mobile Information Device Profile (MIDP) technology.
10. What is deployment descriptor?
A deployment descriptor is an Extensible Markup Language (XML) text-based file with an .xml extension that describes a component's deployment settings. A J2EE application and each of its modules has its own deployment descriptor.
11. What is the EAR file?
An EAR file is a standard JAR file with an .ear extension, named from Enterprice ARchive file. A J2EE application with all of its modules is delivered in EAR file.
12. What is JTA and JTS?
JTA is the abbreviation for the Java Transaction API. JTS is the abbreviation for the Jave Transaction Service. JTA provides a standard interface and allows you to demarcate transactions in a manner that is independent of the transaction manager implementation. The J2EE SDK implements the transaction manager with JTS. But your code doesn't call the JTS methods directly. Instead, it invokes the JTA methods, which then call the lower-level JTS routines.
Therefore, JTA is a high level transaction interface that your application uses to control transaction. and JTS is a low level transaction interface and ejb uses behind the scenes (client code doesn't directly interact with JTS. It is based on object transaction service(OTS) which is part of CORBA.
13. What is JAXP?
JAXP stands for Java API for XML. XML is a language for representing and describing text-based data which can be read and handled by any program or tool that uses XML APIs.
14. What is J2EE Connector?
The J2EE Connector API is used by J2EE tools vendors and system integrators to create resource adapters that support access to enterprise information systems that can be plugged into any J2EE product. Each type of database or EIS has a different resource adapter.
15. What is JAAP?
The Java Authentication and Authorization Service (JAAS) provides a way for a J2EE application to authenticate and authorize a specific user or group of users to run it. It is a standard Pluggable Authentication Module (PAM) framework that extends the Java 2 platform security architecture to support user-based authorization.
16. What is Model 1?
Using JSP technology alone to develop Web page. Such term is used in the earlier JSP specification. Model 1 architecture is suitable for applications that have very simple page flow, have little need for centralized security control or logging, and change little over time. Model 1 applications can often be refactored to Model 2 when application requirements change.
17. What is Model 2?
Using JSP and Servelet together to develop Web page. Model 2 applications are easier to maintain and extend, because views do not refer to each other directly.
18. What is Struts?
A Web page development framework. Struts combines Java Servlets, Java Server Pages, custom tags, and message resources into a unified framework. It is a cooperative, synergistic platform, suitable for development teams, independent developers, and everyone between.
19. How is the MVC design pattern used in Struts framework?
In the MVC design pattern, application flow is mediated by a central Controller. The Controller delegates requests to an appropriate handler. The handlers are tied to a Model, and each handler acts as an adapter between the request and the Model. The Model represents, or encapsulates, an application's business logic or state. Control is usually then forwarded back through the Controller to the appropriate View. The forwarding can be determined by consulting a set of mappings, usually loaded from a database or configuration file. This provides a loose coupling between the View and Model, which can make an application significantly easier to create and maintain.
Controller--Servlet controller which supplied by Struts itself; View --- what you can see on the screen, a JSP page and presentation components; Model --- System state and a business logic JavaBeans.
20. Do you have to use design pattern in J2EE project?
Yes. If I do it, I will use it. Learning design pattern will boost my coding skill.
21. Is J2EE a super set of J2SE?
Yes
Return to top

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



JSP Interview Questions



Question: What is a output comment?
Question: What is a Hidden comment?
Question: What is an Expression?
Question: What is a Declaration ?
Question: What is a Scriptlet?
Question: What are implicit objects? List them?
Question: Difference between forward and sendRedirect?
Question: What are the different scope values for the ?
Question: Explain the life-cycle methods in JSP?

Q: What is a output comment?
A: A comment that is sent to the client in the viewable page source.The JSP engine handles an output comment as uninterpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser.
JSP Syntax


Example 1


Displays in the page source:

TOP

Q: What is a Hidden Comment?
A: A comments that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags. A hidden comment is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you want to hide or "comment out" part of your JSP page.
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" %>

A Hidden Comment

<%-- This comment will not be visible to the colent in the page source --%>


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
<%= someexpression %>
<%= (new java.util.Date()).toLocaleString() %>
You cannot use a semicolon to end an expression
TOP

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.

<%! somedeclarations %>
<%! int i = 0; %>
<%! int a, b, c; %>
TOP

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

Q: What are implicit objects? List them?
A: Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects re listed below
 request
 response
 pageContext
 session
 application
 out
 config
 page
 exception


TOP

Q: Difference between forward and sendRedirect?
A: 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 the request. This process occurs completly with in the web container. When a sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completly new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.
TOP

Q: What are the different scope valiues for the ?
A: The different scope values for are
1. page
2. request
3.session
4.application
TOP

Q: Explain the life-cycle mehtods in JSP?
A: THe generated servlet class for a JSP page implements the HttpJspPage interface of the javax.servlet.jsp package. Hte HttpJspPage interface extends the JspPage interface which inturn extends the Servlet interface of the javax.servlet package. the generated servlet class thus implements all the methods of the these three interfaces. The JspPage interface declares only two mehtods - jspInit() and jspDestroy() that must be implemented by all JSP pages regardless of the client-server protocol. However the JSP specification has provided the HttpJspPage interfaec specifically for the JSp pages serving HTTP requests. This interface declares one method _jspService().
The jspInit()- The container calls the jspInit() to initialize te servlet instance.It is called before any other method, and is called only once for a servlet instance.
The _jspservice()- The container calls the _jspservice() for each request, passing it the request and the response objects.
The jspDestroy()- The container calls this when it decides take the instance out of service. It is the last method called n the servlet instance.
TOP


JSP Interview Questions



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
%>
[ Received from Sumit Dhamija ] TOP

Q: How does JSP handle run-time exceptions?
A: You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page. For example:
<%@ page errorPage=\"error.jsp\" %> redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, if you indicate that it is an error-processing page, via the directive: <%@ page isErrorPage=\"true\" %> Throwable object describing the exception may be accessed within the error page via the exception implicit object. Note: You must always use a relative URL as the value for the errorPage attribute.
[ Received from Sumit Dhamija ] TOP

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

Q: How do I use a scriptlet to initialize a newly instantiated bean?
A: A jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified bean is instantiated. Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although you are not restricted to using those alone.
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.


value="<%=java.text.DateFormat.getDateInstance().format(new java.util.Date()) %>" / >
<%-- scriptlets calling bean setter methods go here --%>

[ Received from Sumit Dhamija ] TOP

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;
}
%>
then use it inside your JSP form, like
" >
[ Received from Sumit Dhamija ] TOP

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.
[ Received from Sumit Dhamija ] TOP

Q: How can I enable session tracking for JSP pages if the browser has disabled cookies?
A: We know that session tracking uses cookies by default to associate a session identifier with a unique user. If the browser does not support cookies, or if cookies are disabled, you can still enable session tracking using URL rewriting. URL rewriting essentially includes the session ID within the link itself as a name/value pair. However, for this to be effective, you need to append the session ID for each and every link that is part of your servlet response. Adding the session ID to a link is greatly simplified by means of of a couple of methods: response.encodeURL() associates a session ID with a given URL, and if you are using redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input. Both encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the browser; if so, the input URL is returned unchanged since the session ID will be persisted as a cookie.

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");
%>
\'>hello2.jsp
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

JSP interview questions
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.
3. What is a translation unit? JSP page can include the contents of other HTML pages or other JSP files. This is done by using the include directive. When the JSP engine is presented with such a JSP page it is converted to one servlet class and this is called a translation unit, Things to remember in a translation unit is that page directives affect the whole unit, one variable declaration cannot occur in the same unit more than once, the standard action jsp:useBean cannot declare the same bean twice in one unit.
4. How is JSP used in the MVC model? JSP is usually used for presentation in the MVC pattern (Model View Controller ) i.e. it plays the role of the view. The controller deals with calling the model and the business classes which in turn get the data, this data is then presented to the JSP for rendering on to the client.
5. What are context initialization parameters? Context initialization parameters are specified by the in the web.xml file, these are initialization parameter for the whole application and not specific to any servlet or JSP.
6. What is a output comment? A comment that is sent to the client in the viewable page source. The JSP engine handles an output comment as un-interpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser.
7. What is a Hidden Comment? A comment that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags. A hidden comment is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you want to hide or “comment out” part of your JSP page.
8. What is a Expression? Expressions are act as place holders for language expression, expression is evaluated each time the page is accessed.
9. What is a Declaration? It 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 semicolons separate them. The declaration must be valid in the scripting language used in the JSP file.
10. What is a Scriptlet? 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 declare variables or methods to use later in the file, write expressions valid in the page scripting language, use any of the JSP implicit objects or any object declared with a .
11. What are the implicit objects? List them. Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects are:
o request
o response
o pageContext
o session
o application
o out
o config
o page
o exception
12. 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 the request. This process occurs completely with in the web container And then returns to the calling method. When a sendRedirect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completely new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.
13. What are the different scope values for the ? The different scope values for are:
o page
o request
o session
o application
14. Why are JSP pages the preferred API for creating a web-based client program? Because no plug-ins or security policy files are needed on the client systems(applet does). Also, JSP pages enable cleaner and more module application design because they provide a way to separate applications programming from web page design. This means personnel involved in web page design do not need to understand Java programming language syntax to do their jobs.
15. Is JSP technology extensible? Yes, it is. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.
16. What is difference between custom JSP tags and beans? Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. Custom tags and beans accomplish the same goals — encapsulating complex behavior into simple and accessible forms. There are several differences:
o Custom tags can manipulate JSP content; beans cannot.
o Complex operations can be reduced to a significantly simpler form with custom tags than with beans.
o Custom tags require quite a bit more work to set up than do beans.
o Custom tags usually define relatively self-contained behavior, whereas beans are often defined in one servlet and used in a different servlet or JSP page.
o Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.




JDBC and JSP interview questions
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
o Native API Partly Java Driver
o Network protocol Driver
o JDBC Net pure Java Driver
4. Can we implement an interface in a JSP?- No
5. What is the difference between ServletContext and PageContext?- ServletContext: Gives the information about the container. PageContext: Gives the information about the Request
6. What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?- request.getRequestDispatcher(path): In order to create it we need to give the relative path of the resource, context.getRequestDispatcher(path): In order to create it we need to give the absolute path of the resource.
7. How to pass information from JSP to included JSP?- Using <%jsp:param> tag.
8. What is the difference between directive include and jsp include?- <%@ include>: Used to include static resources during translation time. JSP include: Used to include dynamic content or static content during runtime.
9. What is the difference between RequestDispatcher and sendRedirect?- RequestDispatcher: server-side redirect with request and response objects. sendRedirect : Client-side redirect with new request and response objects.
10. How does JSP handle runtime exceptions?- Using errorPage attribute of page directive and also we need to specify isErrorPage=true if the current page is intended to URL redirecting of a JSP.
11. How do you delete a Cookie within a JSP?
12. Cookie mycook = new Cookie(\"name\",\"value\");
13. response.addCookie(mycook);
14. Cookie killmycook = new Cookie(\"mycook\",\"value\");
15. killmycook.setMaxAge(0);
16. killmycook.setPath(\"/\");
17. killmycook.addCookie(killmycook);
18. How do I mix JSP and SSI #include?- If you’re just including raw HTML, use the #include directive as usual inside your .jsp file.
19.
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
<%@ vinclude="data.inc" %>
The is used for including non-JSP files.
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 provides a robust, non-proprietary, persistent, and verifiable file format for the storage and transmission of text and data both on and off the Web; and it removes the more complex options of SGML, making it easier to program for.
22. What is the fastest type of JDBC driver?- JDBC driver performance will depend on a number of issues:
o the quality of the driver code,
o the size of the driver code,
o the database server and its load,
o network topology,
o the number of times your request is translated to a different API.
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).
23. How do I find whether a parameter exists in the request object?
24. boolean hasFoo = !(request.getParameter(\"foo\") == null
25. || request.getParameter(\"foo\").equals(\"\"));
or
boolean hasParameter =
request.getParameterMap().contains(theParameter); //(which works in Servlet 2.3+)
26. How can I send user authentication information while makingURLConnection?- You’ll want to use HttpURLConnection.setRequestProperty and set all the appropriate headers to HTTP authorization

Can I map more than one table in a CMP?
Actually the answer is no, you cannot map more than one table to a single CMP Entity Bean. CMP has been, in fact, designed to map a single table.
Said so, we can see that there could be some workaraounds.
The easiest one is to create a VIEW on the database side and have your CMP Entity mapped to it. This is a perfect fit for a read-only solution and, since views are not database dependant, this is a portable solution.

What is the difference between Context, InitialContext and Session Context?
How they are used?
javax.naming.Context is an interface that provides methods for binding a name to an object. It's much like the RMI Naming.bind() method.
javax.naming.InitialContext is a Context and provides implementation for methods available in the Context interface.
Where as SessionContext is an EJBContext object that is provided by the EJB container to a SessionBean in order for the SessionBean to access the information and/or services or the container.
There is EntityContext too which is also and EJBContext object that'll be provided to an EntityBean for the purpose of the EntityBean accessing the container details.
In general, the EJBContext (SessionContext and EntityContext), AppletContext and ServletContext help the corresponding Java objects in knowing about its 'context' [environment in which they run], and to access particular information and/or service.
Whereas, the javax.naming.Context is for the purpose of 'NAMING' [by the way of referring to] an object.

What is the role of serialization in EJB?
A big part of EJB is that it is a framework for underlying RMI: remote method invocation. You're invoking methods remotely from JVM space 'A' on objects which are in JVM space 'B' -- possibly running on another machine on the network.
To make this happen, all arguments of each method call must have their current state plucked out of JVM 'A' memory, flattened into a byte stream which can be sent over a TCP/IP network connection, and then deserialized for reincarnation on the other end in JVM 'B' where the actual method call takes place.
If the method has a return value, it is serialized up for streaming back to JVM A. Thus the requirement that all EJB methods arguments and return values must be serializable. The easiest way to do this is to make sure all your classes implement java.io.Serializable.

My database has a column of type DATETIME. What type of Java variable do I use in the EJB?
java.sql.Timestamp
JAVA Interview Questions

1. What is the diffrence between an Abstract class and Interface ?

2. What is user defined exception ?

3. What do you know about the garbate collector ?

4. What is the difference between C++ & Java ?

5. Explain RMI Architecture?

6. How do you communicate in between Applets & Servlets ?

7. What is the use of Servlets ?

8. What is JDBC? How do you connect to the Database ?

9. In an HTML form I have a Button which makes us to open another page in 15 seconds. How will do you that ?

10. What is the difference between Process and Threads ?

11. What is the difference between RMI & Corba ?

12. What are the services in RMI ?

13. How will you initialize an Applet ?

14. What is the order of method invocation in an Applet ?

15. When is update method called ?

16. How will you pass values from HTML page to the Servlet ?

17. Have you ever used HashTable and Dictionary ?

18. How will you communicate between two Applets ?

19. What are statements in JAVA ?

20. What is JAR file ?

21. What is JNI ?

22. What is the base class for all swing components ?

23. What is JFC ?

24. What is Difference between AWT and Swing ?

25. Considering notepad/IE or any other thing as process, What will happen if you start notepad or IE 3 times? Where 3 processes are started or 3 threads are started ?

26. How does thread synchronization occurs inside a monitor ?

27. How will you call an Applet using a Java Script function ?

28. Is there any tag in HTML to upload and download files ?

29. Why do you Canvas ?

30. How can you push data from an Applet to Servlet ?

31. What are 4 drivers available in JDBC ?

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 ?

34. And What situation , each of the 4 drivers used ?

35. How will you perform transaction using JDBC ?

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?

38. What is serialization ?

39. Can you load the server object dynamically? If so, what are the major 3 steps involved in it ?

40. What is difference RMI registry and OSAgent ?

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 ?

42. What are the benefits of Swing over AWT ?

43. Where the CardLayout is used ?

44. What is the Layout for ToolBar ?

45. What is the difference between Grid and GridbagLayout ?

46. How will you add panel to a Frame ?

47. What is the corresponding Layout for Card in Swing ?

48. What is light weight component ?

49. Can you run the product development on all operating systems ?

50. What is the webserver used for running the Servlets ?

51. What is Servlet API used for conneting database ?

52. What is bean ? Where it can be used ?

53. What is difference in between Java Class and Bean ?

54. Can we send object using Sockets ?

55. What is the RMI and Socket ?

56. How to communicate 2 threads each other ?

57. What are the files generated after using IDL to Java Compilet ?

58. What is the protocol used by server and client ?

59. Can I modify an object in CORBA ?

60. What is the functionality stubs and skeletons ?

61. What is the mapping mechanism used by Java to identify IDL language ?

62. Diff between Application and Applet ?

63. What is serializable Interface ?

64. What is the difference between CGI and Servlet ?

65. What is the use of Interface ?

66. Why Java is not fully objective oriented ?

67. Why does not support multiple Inheritance ?

68. What it the root class for all Java classes ?

69. What is polymorphism ?

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 ?

71. In servlets, we are having a web page that is invoking servlets username and password ? which is cheks in the database ? Suppose the second page also If we want to verify the same information whethe it will connect to the database or it will be used previous information?

72. What are virtual functions ?

73. Write down how will you create a binary Tree ?

74. What are the traverses in Binary Tree ?

75. Write a program for recursive Traverse ?

76. What are session variable in Servlets ?

77. What is client server computing ?

78. What is Constructor and Virtual function? Can we call Virtual funciton in a constructor ?

79. Why we use OOPS concepts? What is its advantage ?

80. What is the middleware ? What is the functionality of Webserver ?

81. Why Java is not 100 % pure OOPS ? ( EcomServer )

82. When we will use an Interface and Abstract class ?

83. What is an RMI?

84. How will you pass parameters in RMI ? Why u serialize?

85. What is the exact difference in between Unicast and Multicast object ? Where we will use ?

86. What is the main functionality of the Remote Reference Layer ?

87. How do you download stubs from a Remote place ?

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 ?

90. What is the main functionality of the Prepared Statement ?

91. What is meant by static query and dynamic query ?

92. What are the Normalization Rules ? Define the Normalization ?

93. What is meant by Servelet? What are the parameters of the service method ?

94. What is meant by Session ? Tell me something about HTTPSession Class ?

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 ?

97. Have you used threads in Servelet ?

98. Write a program on RMI and JDBC using StoredProcedure ?

99. How do you sing an Applet ?

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 ?

102. Tell me the latest versions in JAVA related areas ?

103. What is meant by class loader ? How many types are there? When will we use them ?

104. How do you load an Image in a Servlet ?

105. What is meant by flickering ?

106. What is meant by distributed Application ? Why we are using that in our applications ?

107. What is the functionality of the stub ?

108. Have you used any version control ?

109. What is the latest version of JDBC ? What are the new features are added in that ?

110. Explain 2 tier and 3 -tier Architecture ?

111. What is the role of the webserver ?

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 ?

114. What is meant by cookies ? Explain ?


Why can't my applet read or write to files?
Applets execute under the control of a web browser. Netscape and Internet Explorer impose a security restriction, that prohibits access to the local filesystem by applets. While this may cause frustration for developers, this is an important security feature for the end-user. Without it, applets would be free to modify the contents of a user's hard-drive, or to read its contents and send this information back over a network.
Digitally signed applets can request permission to access the local filesystem, but the easiest way around the problem is to read and write to remote files located on a network drive. For example, in conjunction with a CGI script or servlet, you could send HTTP requests to store and retrieve data.

What is the difference between an applet and an application?
In simple terms, an applet runs under the control of a browser, whereas an application runs stand-alone, with the support of a virtual machine. As such, an applet is subjected to more stringent security restrictions in terms of file and network access, whereas an application can have free reign over these resources.
Applets are great for creating dynamic and interactive web applications, but the true power of Java lies in writing full blown applications. With the limitation of disk and network access, it would be difficult to write commercial applications (though through the user of server based file systems, not impossible). However, a Java application has full network and local file system access, and its potential is limited only by the creativity of its developers.

How can I read from, and write to, files in Java?
Stand-alone applications written in Java can access the local file-system, but applets executing under the control of a browser cannot. With this in mind, lets take a look at two simple applications that write a line of text to a file, and read it back.
import java.io.*;

public class MyFirstFileWritingApp
{
// Main method
public static void main (String args[])
{
// Stream to write file
FileOutputStream fout;

try
{
// Open an output stream
fout = new FileOutputStream ("myfile.txt");

// Print a line of text
new PrintStream(fout).println ("hello world!");

// Close our output stream
fout.close();
}
// Catches any error conditions
catch (IOException e)
{
System.err.println ("Unable to write to file");
System.exit(-1);
}
}
}
This simple application creates a FileOutputStream, and writes a line of text to the file. You'll notice that the file writing code is enclosed within a try { .... } catch block. If you're unfamiliar with exception handling in Java, this requires a little explanation.
Certain methods in Java have the potential to throw an error condition, known as an exception. We have to trap these error conditions, so we 'catch' any exceptions that may be thrown.
The task of reading from a file is also just as easy. We create a FileInputStream object, read the text, and display it to the user.
import java.io.*;

public class MyFirstFileReadingApp
{
// Main method
public static void main (String args[])
{
// Stream to read file
FileInputStream fin;

try
{
// Open an input stream
fin = new FileInputStream ("myfile.txt");

// Read a line of text
System.out.println( new DataInputStream(fin).readLine() );

// Close our input stream
fin.close();
}
// Catches any error conditions
catch (IOException e)
{
System.err.println ("Unable to read from file");
System.exit(-1);
}
}
}

What is the difference between request.getAttribute() and request.getParameter()?
In a request object you can store, on the server side, some object that can be useful during the processing of your pages. This uses request.setAttribute() and request.getAttribute().
Remember that the life of the request object lasts through all the include and forwards, and ends when the page has been sent back to the browser.
The getParameter() method, instead, will return you the specific parameter that has been passed to the page through GET or POST.

What is a session? What is the difference between session and cookie?
A session is an object associated with a client connection to the server. it has the ability to carry information related to the client. since http is a connectionless protocol, developers need an ability to "remember" what the client of the application did during the visit to the page. a great example of the need and use of session is a infamous shopping cart. as users browse through products they are interested in, they add products they want to buy to the 'shopping cart' this information needs to be stored somewhere so that when users decides to check-out and purchase the products, the system knows all the products client wants to purchase. so 'shopping cart' is stored in the session which drags along on each client invocation to the server until session expires. The way server handles session is server-specific. the specification does not specify exact implementation of the session. some web servers may use cookies, some may use something else. but overall, it is up to the implementer to decide how this is done.
the difference between session and a cookie is two-fold.

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.

What is a session and why is it required?
HTTP is a connectionless protocol -- meaning that after the request is served the connection between the client and the server is closed. A session allows you to overcome this limitation by storing client activities. It has many, many uses but one example could be shopping cart type application. You can use the session to track items clients have selected.

30 Java Interview Questions
*Q1. How could Java classes direct program messages to the system console, but error messages, say to a file?

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


*Q2. What's the difference between an interface and an abstract class?

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.


*Q4. Explain the usage of the keyword transient?

A. This keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).


*Q5. How can you force garbage collection?

A. You can't force GC, but could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.


*Q6. How do you know if an explicit object casting is needed?

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. Yes. Add a main() method to the applet.


*Q9. What's the difference between constructors and other methods?

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. Yes. Use this() syntax.


*Q11. Explain the usage of Java packages.

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?

A.There's no difference, Sun Microsystems just re-branded this version.


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


*Q15. Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?

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?

A. It's possible if these variables are final.


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


*Q18. What's the main difference between a Vector and an ArrayList

A. Java Vector class is internally synchronized and ArrayList is not.



*Q19. When should the method invokeLater()be used?

A. This method is used to ensure that Swing components are updated through the event-dispatching thread.

*Q20. How can a subclass call a method or a constructor defined in a superclass?

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.
**Q21. What's the difference between a queue and a stack?

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


**Q27. How would you make a copy of an entire Java object with its state?

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?

A. Use object pooling and weak object references.


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




Question : What is MVC architecture
User Answers/Comments Print Question Email Question Comment/Answer
Posted by satyanarayana.k on 2005-06-02 01:09:35hi MVC pattern is a collabaration of three components, model(ejb,jsbc etc.,), view (jsp, html) and a controller(struts-confi.xml, and servlets). the mvc pattern is a sequence of actions interactions starting with view then controler and then to model based on the data persistence. rgds satyanarayana
Posted by madhu on 2005-06-02 01:31:48MVC is an approach for developing interactive applications ie it results in events through user interaction.MVC stands for Model View Controller.Model is responsible for holding the application state,view is for displaying the current model and controller handles the events.
Posted by Mitchel K on 2005-06-27 07:09:24A design pattern describes a proven solution to a recurring design problem, placing particular emphasis on the context and forces surrounding the problem, and the consequences and impact of the solution. There are many good reasons to use design patterns. Here are three: 1) They are proven. You tap the experience, knowledge and insights of developers who have used these patterns successfully in their own work. 2) They are reusable. When a problem recurs, you don't have to invent a new solution; you follow the pattern and adapt it as necessary. 3) They are expressive. Design patterns provide a common vocabulary of solutions, which you can use to express larger solutions succinctly. The goal of the MVC design pattern is to separate the application object (model) from the way it is represented to the user (view) from the way in which the user controls it (controller). The MVC architecture has the following benefits: 1) Multiple views using the same model: The separation of model and view allows multiple views to use the same enterprise model. Consequently, an enterprise application's model components are easier to implement, test, and maintain, since all access to the model goes through these components. 2) Easier support for new types of clients: To support a new type of client, you simply write a view and controller for it and wire them into the existing enterprise model. 3) Clarity of design: By glancing at the model's public method list, it should be easy to understand how to control the model's behavior. When designing the application, this trait makes the entire program easier to implement and maintain. 4) Efficient modularity: of the design allows any of the components to be swapped in and out as the user or programmer desires - even the model! Changes to one aspect of the program aren't coupled to other aspects, eliminating many nasty debugging situations. Also, development of the various components can progress in parallel, once the interface between the components is clearly defined. 5) Ease of growth: Controllers and views can grow as the model grows; and older versions of the views and controllers can still be used as long as a common interface is maintained. 6) Distributable: With a couple of proxies one can easily distribute any MVC application by only altering the startup method of the application.
Question : What design patterns have you used
User Answers/Comments Print Question Email Question Comment/Answer
Posted by satyanarayana.k on 2005-06-02 01:16:52hi all there are basically various patters used based on the stituations we are faced. we have used the following as for the current project. patters like session facade when u want to interact with entity beans with the stateful beans. factory method such as, when u call a create()method, that in terms calls the EjbCreate(). MVC pattern we have used in struts drastically and which interm corresponds to J2ee controller. abstract factory method pattern we use whenever we have various interfaces which needs implementation for certain methods. Thanks and rgds satyanarayana









Question : What is Struts

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 Struts Validator 10.Change to the ORO package 11.Change to Commons logging 12.Removal of Admin actions 13. Deprecation of the GenericDataSource
Question : Explain Struts navigation flow
User Answers/Comments Print Question Email Question Comment/Answer
Posted by Madhu on 2005-03-23 05:53:04A client requests a path that matches the Action URI pattern. The container passes the request to the ActionServlet. If this is a modular application, the ActionServlet selects the appropriate module. The ActionServlet looks up the mapping for the path. If the mapping specifies a form bean, the ActionServlet sees if there is one already or creates one. If a form bean is in play, the ActionServlet resets and populates it from the HTTP request. If the mapping has the validate property set to true, it calls validate on the form bean. If it fails, the servlet forwards to the path specified by the input property and this control flow ends. If the mapping specifies an Action type, it is reused if it already exists or instantiated. The Action’s perform or execute method is called and passed the instantiated form bean (or null). The Action may populate the form bean, call business objects, and do whatever else is needed. The Action returns an ActionForward to the ActionServlet. If the ActionForward is to another Action URI, we begin again; otherwise, it’s off to a display page or some other resource. Most often, it is a JSP, in which case Jasper, or the equivalent (not Struts), renders the page.
Question : What is the difference between ActionForm and DynaActionForm
User Answers/Comments Print Question Email Question Comment/Answer
Posted by vamshi on 2005-03-18 15:21:38In struts 1.0, action form is used to populate the html tags in jsp using struts custom tag.when the java code changes, the change in action class is needed. To avoid the chages in struts 1.1 dyna action form is introduced.This can be used to develop using xml.The dyna action form bloats up with the struts-config.xml based definetion.
Posted by jagadish kumar on 2005-07-13 06:50:22There is no need to write actionform class for the DynaActionForm and all the variables related to the actionform class will be specified in the struts-config.xml where as we have to create Actionform class with getter and setter methods which are to be populated from the form
Question : What is DispatchAction
User Answers/Comments Print Question Email Question Comment/Answer
Posted by Sudhir Patil on 2005-04-22 01:19:19The DispatchAction class is used to group related actions into one class. DispatchAction is an abstract class, so you must override it to use it. It extends the Action class. It should be noted that you dont have to use the DispatchAction to group multiple actions into one Action class. You could just use a hidden field that you inspect to delegate to member() methods inside of your action.
Question : How to call ejb from Struts User Answers/Comments Print Question Email Question Comment/Answer Posted by Suresh Pendyala on 2005-05-07 16:35:00use the Service Locator patter to look up the ejbs. Posted by Suresh Pendyala on 2005-05-07 23:20:01Or You can use InitialContext and get the home interface. Question : What are the various Struts tag librariesUser Answers/Comments Print Question Email Question Comment/Answer Posted by Madhu on 2005-03-23 05:54:28struts-html tag library - used for creating dynamic HTML user interfaces and forms. struts-bean tag library - provides substantial enhancements to the basic capability provided by . struts-logic tag library - can manage conditional generation of output text, looping over object collections for repetitive generation of output text, and application flow management. struts-template tag library - contains tags that are useful in creating dynamic JSP templates for pages which share a common format.Question : What is the difference between ActionErrors and ActionMessages
Posted by Sundar on 2005-03-22 07:16:51
The difference between the classes is zero -- all behavior in ActionErrors was pushed up into ActionMessages and all behavior in ActionError was pushed up into ActionMessage. This was done in the attempt to clearly signal that these classes can be used to pass any kind of messages from the controller to the view -- errors being only one kind of message
Question : How you will handle errors and exceptions using Struts
User Answers/Comments Print Question Email Question Comment/Answer
Posted by abhishek roy on 2005-06-11 13:51:18there are various ways to handle exception: 1) To handle errors server side validation can be used using ActionErrors classes can be used. 2) The exceptions can be wrapped across different layers to show a user showable exception. 3)using validators
Posted by Rahul Pundhir on 2005-07-14 04:15:54Can you suggest me some good Tutorial for Struts available on the Net. With Thanks And Regards Rahul Pundhir
Posted by me on 2005-07-15 09:13:58http://struts.apache.org/userGuide/index.html http://www.coreservlets.com/Apache-Struts-Tutorial/

Question : How you will save the data across different pages for a particular client request using Struts

User Answers/Comments Print Question Email Question Comment/Answer

Posted by Francisco on 2005-04-11 14:39:13
Several ways. The similar to the ways session tracking is enabled. Using cookies, URL-rewriting, SSLSession, and possibilty threw in the database.
Posted by Joseph on 2005-05-04 12:00:29
If the request has a Form object, the data may be passed on through the Form object across pages. Or within the Action class, call request.getSession and use session.setAttribute(), though that will persist through the life of the session until altered.



Question : What are the differences between ArrayList and a Vector

User Answers/Comments Print Question Email Question Comment/Answer
Posted by satyanarayana.k on 2005-06-02 01:38:43hi the basic differences are vector is a old collectiion came with jdk 1.0 or later. so, it comes under legacy classes. it allows synchronized way of accessing the elements. where as arraylist allows elements to be made synchronized as well asynchronized. its is dynamic collectiion. u have more flexibilty of using the arraylist collection. rgds satyanarayana
Posted by Rama Krishna on 2005-06-02 02:42:00Both represent growable array of objects. The difference is Vector is Synchronized and Arraylist is not.
Posted by anoop on 2005-06-02 05:27:06Vector is synchronized but arraylist is not.
Posted by Ramakrishna on 2005-07-09 00:06:17ArrayList will grow half the size what you initialise ..where as vector will grow doble the initial size..
Posted by srikanth on 2005-07-13 00:20:01one more difference apart from this is Vector also stores the objects but arraylist doesn't..........
Posted by Indu K. Vaghasia on 2005-07-15 10:50:32One Difference between Vector and ArrayList is In vector the data is retrive through elementAt() method while in ArrayList through get()

Question : What are the differences between EJB and Java beans User Answers/Comments Print Question Email Question Comment/Answer
Posted by satyanarayana.k on 2005-06-02 02:02:16hi the main difference is Ejb componenets are distributed which means develop once and run anywhere. java beans are not distributed. which means the beans cannot be shared . rgds satyanarayana


Question : How are memory leaks possible in Java

User Answers/Comments Print Question Email Question Comment/Answer
Posted by Nandu on 2005-06-13 10:15:27There is no certainty of memory leaks in java.
Posted by varun kanaujia on 2005-07-05 03:48:22If suggest answerthen much better Thanks in advanced
Posted by nitin k on 2005-07-09 09:55:59send me java projects with source code
Posted by Pankaj Sharma on 2005-07-12 08:13:05If any object variable is still pointing to some object which is of no use, then JVM will not garbage collect that object and object will remain in memory creating memory leak

Question : What are STRUTS
User Answers/Comments Print Question Email Question Comment/Answer
Posted by satyanarayana.k on 2005-06-02 02:08:17hi struts is basically collection of jsp, servlets combined framework. it uses MVC design pattern, which means it is sequential interaction between jsp to servlets and ejb if persistence required. There is another component called Struts-config.xml which controls the whole process. So in controller we can include Servlets and Struts-config.xml. In sequence struts starts with the jsp(view)----->struts-config.xml + actions(controllers)---->Ejb +JDBC (model). Thanks and Rgds Satyanarayana

Question : Explain Servlet and JSP life cycle


User Answers/Comments Print Question Email Question Comment/Answer
Posted by satyanarayana.k on 2005-06-02 02:14:58hi jsp life cycle has three important methods such as init() ->this initalizes the jsp information with the configuration parameters. service : here the business logic starts. that is, all the request and responses goes here. destroy() : once the process is completed, it will be killed. Servlets derived as HttpServlets and GenericServlet in HttpServlets have 3 methods. init() -> servlets confiration parameters are created and passed. doPost(), doGet() : this are the business logic methods. destroy() : ultimately kills the servlets once the process completed. Thanks and Rgds Satyanarayana
Posted by joadavis on 2005-06-03 13:20:36This is not a "core Java" question, rather a servlet/jsp question. Webmaster, can you move this question?
Posted by Sandip on 2005-07-11 02:47:08Servlet Lifecycle: init() ->this initalizes the servlets initialization information with the configuration parameters. service : here the business logic starts. that is, all the request and response services goes here. destroy() : once the process is completed, it will be used to destory all vairables and objects used by servlets. JSP lifecycle is somewhat diff that servlet life cycle. It includes four steps for the same. jspInit:works like servlet init method. jspTransleted: used to translate the JSP into servlet and in case of Tomcat server,thats translated servlets goes in work directory. _jspService: Its works like servlet's service method. jspDestory: same as servlets destory method. Thanks
Question : What would happen if you say this = null
User Answers/Comments Print Question Email Question Comment/Answer
Posted by Yogesh on 2005-06-01 00:22:34this will give a compilation error as follows cannot assign value to final variable this
Question : What do you like most with Ant
User Answers/Comments Print Question Email Question Comment/Answer
Posted by Samuel on 2005-06-03 09:01:46ANT - means Another Neat Tools. ANT is mainly used for build serverside applictions. Regards, Samuel
Posted by smitha on 2005-07-11 14:04:24pls tell me wat is memory leaking in java thanks in advance


No comments: