Popular Posts

Showing posts with label SERVLETS. Show all posts
Showing posts with label SERVLETS. Show all posts

Monday, April 13, 2009

Generating the Server Response: HTTP Status Codes

Generating the Server Response: HTTP Status Codes :

When a Web server responds to the request from the browser or other Web client, the response typically consists of a status line, some response headers, a blank line, and the document

Specifying Status Codes

As described above, the HTTP response status line consists of the HTTP version, a status code, and an associated message. Since the message is directly associated with the status code and the HTTP version is determined by the server, all the servlet needs to do is to set status code. The way to do that is by the setStatus method of the HttpServletResponse.

The setStatus method takes the int (the status code) as an argument, but instead of using explicit numbers, it is clearer and more reliable to use the constants defined in HttpServletResponse. The name of each constant is derived from standard HTTP 1.1 message for each constant, all uppercase with a prefix of SC(for Status Code) and spaces changed to underscores. Thus, since the message for 404 is Not Found, the equivalent constant in the HttpServletResponse is SC_NOT_FOUND There are two exceptions however. For some odd reason the constant for code 302 is derived from the HTTP 1.0 message, not the HTTP 1.1 message, and the constant for the code 307 is missing altogether.

Setting the status code does not always mean that you don't need to the return a document. For example, although most servers will generate the small "File Not Found" message for 404 responses, a servlets might want to customize this response. However, if you do this, you need to be sure to call response.setStatus before sending any content via PrintWriter.

Although the general method of setting status codes is simply to the call response.setStatus(int), there are two common cases where a shortcut method in the HttpServletResponse is provided. The sendError method generates the 404 response along with a short message formatted inside an HTML document. And the sendRedirect method generates the 302 response along with a Location header indicating the URL of the new document.


HTTP 1.1 Status Codes and Their Meaning

Following is the list of all the available HTTP 1.1 status codes, along with their associated message and interpretation. You should be cautious in using status codes that are available only in HTTP 1.1, since many browsers still only support HTTP 1.0. If you do use the status codes specific to HTTP 1.1, in most cases you want to either explicitly check the HTTP version of request (via the getProtocol method of the HttpServletRequest) or reserve it for situations when no HTTP 1.0 status code would be particularly meaningful to the client anyhow.















100 Continue Continue with partial request. (New in HTTP 1.1)
101 Switching Protocols

Server will comply with Upgrade header and change to different protocol. (New in HTTP 1.1)
200 OK

Everything's fine; document follows for GET and POST requests. This is the default for servlets; if you don't use setStatus, you'll get this.
201 Created

Server created a document; the Location header indicates its URL.
202 Accepted Request is being acted upon, but processing is not completed.
203 Non-Authoritative Information Document is being returned normally, but some of the response headers might be incorrect since a document copy is being used. (New in HTTP 1.1)
204 No Content

No new document; browser should continue to display previous document. This is a useful if the user periodically reloads a page and you can determine that the previous page is already up to date. However, this does not work for pages that are automatically reloaded via the Refresh response header or the equivalent header, since returning this status code stops future reloading. JavaScript-based automatic reloading could still work in such a case, though
205 Reset Content

No new document, but browser should reset document view. Used to force browser to clear CGI form fields. (New in HTTP 1.1)
206 Partial Content

Client sent a partial request with a Range header, and server has fulfilled it. (New in HTTP 1.1)
300 Multiple Choices

Document requested can be found several places; they'll be listed in the returned document. If server has a preferred choice, it should be listed in the Location response header.
301 Moved Permanently

Requested document is elsewhere, and the URL for it is given in the Location response header. Browsers should automatically follow the link to the new URL.
302 Found

Similar to 301, except that the new URL should be interpreted as a temporary replacement, not a permanent one. Note: the message was "Moved Temporarily" in HTTP 1.0, and the constant in HttpServletResponse is SC_MOVED_TEMPORARILY, not SC_FOUND.Very useful header, since browsers automatically follow the link to the new URL. This status code is so useful that there is a special method for it, sendRedirect. Using response.sendRedirect(url) has a couple of advantages over doing response.setStatus(response.SC_MOVED_TEMPORARILY) and response.setHeader("Location", url). First, it is easier. Second, with sendRedirect, the servlet automatically builds a page containing the link (to show to older browsers that don't automatically follow redirects). Finally, sendRedirect can handle relative URLs, automatically translating them to absolute ones.

Note that this status code is sometimes used interchangeably with 301. some servers will send 301 and others will send 302.

Technically, browsers are only supposed to automatically follow the redirection if the original request was GET. See the 307 header for details.





Accessing the Standard CGI Variables

Accessing the Standard CGI Variables:

To build the successful web application, you often need to know a lot about the environment in which it is running.

You may need to find out about server that is executing your servlets or the specifics of the client that is sending requests. And no matter what kind of environment the application is running in, you most certainly need the information about the requests that the application is handling.

Advantages of Using Servlets Over CGI

* Stronger type checking. In other words, more help from compiler in catching errors. A CGI program uses one function to retrieve its environment variable. Many errors cannot be found until they cause runtime problem. Let's look at how both a CGI program and servlets find the port on which its server is running.

A CGI script written in Perl call: $port = $ENV{'SERVER_PORT'}; port is an untyped variable. A CGI program written in C call: The chance for accidental errors is also high. The environment variable name could be misspelled or the data type might not match what the environment variable returns.

A servlet, on the other hand, call:

int port = req.getServerPort()

This eliminates a lot of the accidental errors because the compiler can guarantee there are no misspellings and each return type is as it should be.
*

Delayed calculation. When the server launches a CGI program, the value for each and every environment variable must be precalculated and passed, whether the CGI program uses it or not. A server launching the servlets has the option to improve performance by delaying these calculations and performing them on demand as needed.
*

More interaction with server. Once the CGI program begins execution, it is untethered from its server. The only communication path available to program is its standard output. A servlet, however, can also work with the server. As discussed in the last chapter, a servlet operates either within the server (when possible) or as connected process outside the server (when necessary). Using this connectivity, a servlet can make ad hoc requests for calculated the information that only the server can provide. For example, a servlet can have its server do arbitrary path translation, taking into consideration the server's aliases and virtual paths.



CGI Environment Variables and the Corresponding Servlet Methods











CGI Environment VariableHTTP Servlet Method
SERVER_NAMEreq.getServerName()
SERVER_SOFTWAREgetServletContext().getServerInfo()
SERVER_PROTOCOLreq.getProtocol()
SERVER_PORTreq.getServerPort()
REQUEST_METHODreq.getMethod()
PATH_INFOreq.getPathInfo()
PATH_TRANSLATEDreq.getPathTranslated()
SCRIPT_NAMEreq.getServletPath()
DOCUMENT_ROOTreq.getRealPath("/")

Sunday, April 12, 2009

Handling the Client Request: HTTP Request Headers

*When the HTTP client (e.g. a browser) sends a request, it is required to supply a request line (usually GET or POST).

* If it wants to, it can also send the number of headers, all of which are optional except for Content-Length, which is required only for POST requests

HTTP Request Header Methods Available in Servlets

General:

-getHeader (header name is not case sensitive)
-getHeaderNames
-getHeaders
Specialized

-getCookies
-getAuthType and getRemoteUser
-getContentLength
-getContentType
-getMethod
-getRequestURI
-getQueryString
-getDateHeader
-getIntHeader
-Related info
-getProtocol


An Overview of Request Headers

When the HTTP client (e.g. a browser) sends a request, it is required to supply a request line (usually GET or POST). If it wants to, it can also send the number of headers, all of which are optional except for Content-Length, which is required only for POST requests. Here are the most common headers:

* Accept The MIME types that the browser prefers.
* Accept-Charset The character set that the browser expects.
*

Accept-Encoding The types of data encodings (such as gzip) that the browser knows how to decode. Servlet can explicitly check for gzip support and return gzipped HTML pages to browsers that support them, setting the Content-Encoding response header to indicate that they are gzipped. In many cases, this can reduce page download times by a factor of five or ten.
*

Accept-Language The language the browser is expecting, in case the server has versions in more than the one language.
*

Authorization Authorization info, usually in response to the WWW-Authenticate header from the server.
*

Connection Use persistent connection? If a servlet get a Keep-Alive value here, or gets a request line indicating HTTP 1.1 (where persistent connections are the default), it may be able to take advantage of persistent connections, saving significant time for Web pages that include several small pieces (images or applet classes). To do this, it needs to send the Content-Length header in the response, which is most easily accomplished by writing into a ByteArrayOutputStream, then looking up the size just before writing it out.
*

Content-Length (for POST messages, how much the data is attached)
*

Cookie (one of most important headers; see separate section in this tutorial on handling cookies)
*

From (email address of the requester; only used by Web spiders and other custom clients, not by browsers)
* Host (host and the port as listed in the original URL)
*

If-Modified-Since (only return documents newer than this, otherwise send the 304 "Not Modified" response)
*

Pragma (the no-cache value indicates that the server should return the fresh document, even if it is a proxy with a local copy)
*

Referer (the URL of the page containing the link the user followed to get to the current page)
*

User-Agent (type of the browser, useful if servlet is returning browser-specific content)
*

UA-Pixels, UA-Color, UA-OS, UA-CPU (nonstandard header sent by some Internet Explorer versions, indicating screen size, color depth, operating system, and cpu type used by the browser's system)



Reading Request Headers from Servlets

Reading headers is the very straightforward; just call the getHeader method of the HttpServletRequest, which returns a String if the header was supplied on this request, null otherwise. However, there are the couple of headers that are so commonly used that they have special access methods. The getCookies method returns contents of the Cookie header, parsed and stored in an array of Cookie objects. See the separate section of this tutorial on cookies. The getAuthType and getRemoteUser methods break Authorization header into its component pieces. The getDateHeader and getIntHeader methods read the specified header and then convert them to Date and int values, respectively.

Rather than looking up one of the particular header, you can use the getHeaderNames to get an Enumeration of all header names received on this particular request.

Finally, in addition to looking up request headers, you can get information on the main request line itself. The getMethod method returns the main request method (normally GET or POST, but things like HEAD, PUT, and DELETE are possible). The getRequestURI method returns URI (the part of the URL that came after the host and port, but before the form data). The getRequestProtocol returns third part of the request line, which is generally "HTTP/1.0" or "HTTP/1.1".

Sunday, April 5, 2009

Handling the Client Request:Form Data

# When the user submits form, his information is sent to the corresponding servlet file because we've set the ACTION attribute to point to the servlet.
* The form can use the GET method or POST method.
* In GET method, if the user enter the name "Inigo Montoya," the request URL is http://server:8080/servlet/Hello?name=Inigo+Montoya in the form of querystring which is visible to the user.
* The space in the name is specially encoded as a plus sign by the browser because URLs cannot contain space.
* A servlet's HttpServletRequest object gives it access to form data in its query string.

Difference between GET and POST Method
When the user enters information in a form and clicks Submit , there are two ways the information can be sent from browser to server: in the URL, or within the body of the HTTP request.

The GET method, which was used in example earlier, appends name/value pairs to the URL. Unfortunately, the length of URL is limited, so this method only works if there are only a few parameters. The URL could be truncated if the form uses a large number of parameter or if the parameters contain large amounts of data. Also, parameters passed on URL are visible in the address field of the browsernot the best place for a password to be displayed.

The alternative to the GET method is POST method. This method packages the name/value pairs inside the body of HTTP request, which makes for a cleaner URL and imposes no size limitation on the forms output. It is more secure.


Overriding service, doGet, and doPost

When a request is made, Servlet Engine hands on the incoming data to the Servlet engine, which processes the request, including form data, cookies, session information, and URL name-value pairs, into an object of type HttpServletRequest called the request object. Client metadata is encapsulated as the object of type HttpServletResponse and is called the response object. The Servlet engine passes both objects as parameters to Servlets service() method.

The default service() method in an HTTP servlets routes the request to another method based on the HTTP transfer method (POST, GET, etc.) For example, HTTP POST requests are routed to doPost() method, HTTP GET requests are routed to the doGet() method, and so on. This enables the Servlet to perform different processing on request data depending on the transfer method. Since routing takes place in service(), you generally do not override service() in an HTTP Servlet. Instead, override doGet() and/or doPost(), etc., depending on type of request you expect.

The automatic routing in an HTTP Servlets is based simply on a call to request.getMethod(), which provides the HTTP transfer method. In Servlets Engine, request data is already preprocessed into a name-value list by the time the Servlet sees the data, so you could simply override the service() method in an HTTP Servlet without losing any functionality. However, this does make the Servlet less portable, since it is now dependent on preprocessed request data.

You must override service() method (for generic Servlets) or the doGet() and/or doPost() methods (for HTTP servlets) to perform the tasks needed to answer the request. Very often, this means accessing EJBs to perform the business transactions, collating the needed information (in the request object or in a JDBC ResultSet object), and then passing the newly generated content to the JSP for formatting and delivery back to the client.

Most operations that involve the forms use either a GET or a POST operation, so for most servlets you override either doGet() or doPost(). Note that you can implement both the methods to provide for both types of input, or simply pass the request object to a central processing method


Syntax of Using doGet
public void doGet (HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
...servlet code goes here...
}


Syntax of Using doPost
public void doPost (HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
...servlet code goes here...
}

All of the actual request-by-request traffic in an HTTP Servlets is handled in the appropriate doOperation() method, including session management, user authentication, dispatching EJBs and JSPs, and accessing iAS features.

If you have a Servlets that you intend to also call using a RequestDispatcher method include() or forward() , be aware that the request information is no longer sent as HTTP POST, GET, etc. RequestDispatcher methods always call the service(). In other words, if a servlet overrides doPost(), it may not process anything if another servlet calls it, if the calling servlet happens to have received its data via HTTP GET. For this reason, be sure to implement routines for all possible types of the input, as explained above.

Note Arbitrary binary data, like uploaded files or images, can be problematic, since web connector translates incoming data into name-value pairs by default. You can program web connector to properly handle this kind of data and package it correctly in the request object. Accessing Parameters and Storing the Data

Incoming data is encapsulated in the request object. For HTTP servlet, the request object is of type HttpServletRequest. For generic servlet, the request object is of type ServletRequest. The request object contains all the parameters in a request, and you can also set your own values in the request. The latter is called attribute.

You can access all the parameters in an incoming request by using getParameter() method.


The following example describe the use of getParameter()
String username = request.getParameter("accountNumber");
You can also set and retrieve values in the request object using setAttribute() and getAttribute(), respectively.
The following example describe the use of setAttribute()
request.setAttribute("accountNumber", "3284766");


A complete example showing the use of doGet Method in Servlets

Step1:Make the HTML form

Step2:Make the corresponding Servlets Page
Step1:Make the HTML form
Here we are make a HTML form called form.html which is given below:


Step2:Make the corresponding Servlets Page
Here we are make a Servlets filr called name.java as we have given in the action attribute path in the form.html as name which is given below:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class name extends HttpServlet
{

public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();

String name = req.getParameter("name");
out.println("");
}

public String getServletInfo()
{
return "A servlet that knows the name of the person to whom it's" +
"saying hello";
}
}

Life Cycle of Servlets

Servlets Life Cycle
have the following Components:

* Handled by the servlets container.
* Create and initialize the servlets.
* Handle zero or more service call.
* Destroy and garbage collect the servlets.
* A single servlets instance to handle every request

The Basic Servlet Architecture or Life Cycle



Servlet container create only one instance of each servlet but the request of each user is handled with a separate thread. Each thread then calls the doGet or doPost methods. This idea is shown in the above Figure-5.

1.The init method of the servlets is called when the servlets is first created and each time the server receives a request for a servlets, the server spawns a new thread calls service method.

2.The service method check the HTTP request type (GET,SET, PUT, DELETE, etc.) and calls doGet, doPost, doPut,doDelete, etc. method as appropriate.

3.Finally, the server may decide to remove a previous loaded servlet. In this case, the server calls destroy method of the servlets.

HTTP

Before we can start writing the first Servlets, we need to know some basics of HTTP ("HyperText Transfer Protocol"), the protocol which is used by a WWW client (e.g. a browser) to send a request to a Web Server.

HTTP is the request-response oriented protocol. An HTTP request consist of a request method, a URI, header fields and a body (which can be empty). An HTTP response contain a result and again header fields and a body.

The service method of HttpServlet dispatch a request to different Java methods for different HTTP request methods. It recognize the standard HTTP/1.1 methods and should not be overridden in subclasses unless you need to implement additional methods. The recognized methods are GET, PUT,HEAD, POST, DELETE, OPTIONS and TRACE. Other methods are answered with a Bad Request HTTP error. An HTTP method XXX is dispatched to the Java method doXxx, e.g. GET -> doGet. All these method expect the parameters "(HttpServletRequest req, HttpServletResponse res)". The method doOptions and doTrace have suitable default implementations and are usually not overridden. The HEAD method (which is supposed to return the same header lines that a GET method would return, but doesn't include a body) is performed by calling the doGet and ignoring any output that is written by this method. That leaves us with the method doGet doPut doPost and doDelete whose default implementations in HttpServlet return a Bad Request HTTP error. A subclass of HttpServlet overrides one or more of these method to provide a meaningful implementation.

The request data is passed to all the methods through the first argument of type HttpServletRequest (which is a subclass of the more general ServletRequest class). The response can be created with the methods of the second argument of type HttpServletResponse (a subclass of ServletResponse).

When you request a URL in the Web Browser, the GET method is used for the request. A GET request does not have the body (i.e. the body is empty). The response should contain the body with the response data and header fields which describe the body (especially Content-Type and Content-Encoding). When you send an HTML form, either GET or POST action can be used. With the GET request the parameters are end in the URL, with a POST request they are transmited in the body. HTML editors and upload tools use PUT requests to the upload resources to a Web Server and DELETE requests to delete resources.


Servlet Types
# Classic Servlets-service() Method
# JSP's-Java Embeded in HTML Templates
# Http Servlets-doGet & doPost()
# Visual Servlets-Generated by Visual Age

Packages in Servlets
There are two types of package available in servlets which are as follows:

1.javax.servlet.*

2.javax.servlet.http.*

Interfaces in javax.servlet.*

# RequestDispatcher
# Servlet
# ServletRequest
# ServletResponse
# ServletConfig
# ServletContext
# SingleThreadModel

classes in javax.servlet.*

# GenericServlet
# ServletInputStream
# ServletOutputStream
# ServletException
# UnavailableException



Interfaces in javax.servlet.http.*

# HttpServletRequest
# HttpServletResponse
# HttpSessionBindingListener
# HttpSessionContext
# HttpSession



classes in javax.servlet.http.*

# Cookie
# HttpServlet
# HttpUtils
# HttpSessionBindingEvent



Servlet Scope Objects

The indicator specify the minimum number of time an element can occur:

There are four scope objects in servlets which enables the sharing information between web components. The scope objects and their corresponding Java classes are listed below:

# Web Context javax.servlet.ServletContext
# Request javax.servlet.HttpServletRequest
# Session javax.servlet.http.HttpSession
# Page javax.servlet.jsp.PageContext

You can get the attribute values from servlet scope objects using getAttribute method and set new values of attributes using setAttribute method. For example, you can get the client’s IP address by calling the getRemoteAddr method of HttpServletRequest class.


Following Examples prints the Hello World in the browser

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

To be a servlet, a class should extend the 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 the incoming information such as FORM data, HTTP request headers, and the like.

The HttpServletResponse has method 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 servlet, most of the effort is spent in println statements that generate the desired page. Note that doGet and doPost throw two exception, so you are required to include them in the declaration. Also note that you have to import classes in the 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 service method, and sometimes you may want to override service directly, e.g. for a servlet that handles both GET and POST request.

Compiling and Installing the Servlet
Note that the specific details for installing servlet vary from Web server to Web server. Please refer to your Web server documentation for the definitive directions. The on-line examples are running on Java Web Server (JWS) 2.0, where servlet are expected to be in a directory called servlets in the JWS installation hierarchy. However, I placed this servlets 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 the "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 servlets 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 the packages before, there are two main ways to compile classes that are in packages.

One way is to set your CLASSPATH to point to 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 the 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 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 CLASSPATH to point to servlet.jar and jsp.jar. On Windows NT, you'd go to 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 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 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 directory name. This is fixed in JDK 1.2, but since many Web servers are configured to use the JDK 1.1, many servlet authors stick with JDK 1.1 for portability.

Finally, another advanced option is to keep 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.

Running the Servlet
With the Java Web Server, servlet 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 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 server 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 the details.


A Servlet that Generates HTML

Most servlet 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 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 the response headers before actually returning any of the content via the PrintWriter. Here's an example:

The following program called HelloWWW.java will print Hellow WWW in the browser in the HTML format.
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" +
"\n" +
"\n" +
"

Hello WWW

\n" +
"");
}
}










Introduction To servlets

*Servlets are Java programs running on a web server that produce results viewed remotely on web server.

*Servlets has the same purpose that PHP or CGI had in the past.

*We shall describe how Servlet works with some examples.

*You will also learn about Servlet Response and Request Model, Servlet Life Cycle, Servlet Scope Objects and Error Handling.

What are Java Servlets?

Servlets are Java technology's answer to the CGI programming. They are programs that run on a Web server and build Web page. Building Web pages on the fly is useful (and commonly done) for a number of reason:

* The Web page is based on the data submitted by the user. For example the result pages from search engines are generated this way, and programs that process orders for e-commerce sites do this as well.
* The data alsp changes frequently. For example, a weather-report or news headlines page might build the page dynamically, perhaps returning a previously built page if it is still up to the date.
* The Web page uses information from corporate databases or other such source. For example, you would use this for making a Web page at an on-line store that lists current prices and number of items in the stock.

What are the Advantage of Servlets Over "Traditional" CGI?

Java servlets are more efficient, easier to use, more powerful, more portable, and cheaper than traditional CGI and than many alternative CGI-like technology. (More importantly, servlet developers get paid more than Perl programmers :-).

* Efficient. With traditional CGI, a new process is started for the each HTTP request. If the CGI program does a relatively fast operation, the overhead of starting the process can dominate the execution of time. With servlets, the Java Virtual Machine stays up, and each request is handled by a lightweight Java thread, not the heavyweight operating system process. Similarly, in traditional CGI, if there are N simultaneous request to the same CGI program, then the for the CGI program is loaded into memory N time. With servlets, however, there are N threads but only a single copy of the servlets class. Servlets also have more alternatives than do regular CGI programs for optimizations such as caching previous computations, keeping the database connections open, and the like.

* Convenient. Hey, you already know Java. Why learn Perl too? Besides the convenience of being able to use a familiar language, servlets have an extensive infrastructure for automatically parsing and decoding the HTML form data, reading and setting HTTP headers, handling cookies, tracking sessions, and many other such utilities.

* Powerful. Java servlets let you easily do several things that are difficult or impossible with the regular CGI. For one thing, servlets can talk directly to Web server (regular CGI programs can't). This simplifies operations that need to look up images and other data stored in the standard places. Servlets can also share data among each other, making the useful things like database connection pools easy to implement. They can also maintain information from request to request, simplifying things like session tracking and caching of previous computation.

* Portable. Servlets are written in Java and followsss a well-standardized API. Consequently, servlets written for, say I-Planet Enterprise Server can alsp run virtually unchanged on Apache, Microsoft IIS, or WebStar. Servlets are supported directly or via a plugin on the almost every major Web server.

* Inexpensive. There are also a number of free or very inexpensive Web servers available that are good for "personal" use or low-volume Web sites. However, with major exception of Apache, which is free, most commercial-quality Web servers are relatively expensive. Nevertheless, once you have a Web server, no matter the cost of that server, adding servlets support to it (if it doesn't come preconfigured to support servlets) is generally free or cheap.

Advantages of servlets over CGI processes

Servlets:
# have significantly less overhead than CGI
# can inherit processing state between invocation
# can use concurrency control in the Java to share state at server.


# Servlets compared to CGI programs: are slower only when being initially it is loaded
# rather faster to run when it is loaded.


# Servlets can: open a database connection when initially it is loaded
# share open DB connection with successive invocation
# CGI programs have to renew the DB connection each time they're run.


# Servlets can: store state information in the static variables in servlet
# share access to the state data each time servlet is run
# control concurrent access to the shared state easily
# CGI programs lack the common address space to share state easily.

Disadvantages of servlets over CGI processes

# cruder model of concurrency
# less robust - share common address space in the JVM process
# more complex to handle, write and configure



What You Should Already Know?

Before you goes to this tutorial you should have a basic understanding of the following:

* HTML
* A basic understanding of JAVA

If you are going to study these subjects first, find the tutorial on our Home page