Times! The current time here is: The current

January 15th, 2007

Times! The current time here is:

The current time in London is:

And the current time in New York is:

The servlet named CurrentTimecan be plugged into any page that needs a time display. The name can be either the servlet’s class name or its registered name. The servlet code is shown in Example 2-4. Example 2-4. A server-side include that prints the current time import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class CurrentTime extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter out = res.getWriter(); Date date = new Date(); DateFormat df = DateFormat.getInstance(); String zone = req.getParameter( zone ); if (zone != null) { TimeZone tz = TimeZone.getTimeZone(zone); df.setTimeZone(tz); } Example 2-4. A server-side include that prints the current time (continued) out.println(df.format(date)); } } The CurrentTimeservlet looks strikingly similar to the Helloservlet. This is not a coincidence. There is no real difference between a servlet that handles full-page GET requests and one that is embedded in a page, except that embedded servlets have limited response capabilities. For example, an embedded servlet cannot set HTTP headers.

Hint: If you are looking for very good and affordable webspace to host and run your java hosting application check Sandzak.com java web hosting provider

* Currently, the tag syntax varies across server

January 14th, 2007

* Currently, the tag syntax varies across server implementations. This section describes the syntax appropriate for the Java Web Server. The CODEattribute specifies the class name or registered name of the servlet to invoke. The CODEBASE attribute is optional. It can refer to a remote location from which the servlet should be loaded. Without a CODEBASEattribute, the servlet is assumed to be local. Any number of parameters may be passed to the servlet using the tag. The servlet can retrieve the parameter values using the getParameter()method of ServletRequest. Any number of initialization (init) parameters may also be passed to the servlet appended to the end of the tag. We’ll cover init parameters in Chapter 3, The Servlet Life Cycle. A server that supports SSI detects the tag in the process of returning the page and substitutes in its place the output from the servlet (as shown in Figure 2-7). The server does not parse every page it returns, just those that are specially tagged. The Java Web Server, by default, parses only pages with an .shtml extension. Note that with the tag, unlike the tag, the client browser never sees anything between and unless the server does not support SSI, in which case the client receives the content, ignores the unrecognized tags, and displays the descriptive text. Figure 2-7. Server-side include expansion Writing a Server-Side Include Server-side includes are useful when a page is primarily static but contains a few distinct dynamic portions. For a simple example, let’s assume we have several pages that need to display the current time. As an extra challenge, let’s assume that sometimes we need the current time in time zones other than our own. The problem is easy with server-side includes. Each page can be written as a static HTML page with one or more SSI directives that call Java code to provide the times. The HTML could look something like this, saved to a file with an .shtml extension:
Quick Hint: If you are looking for cheap and reliable provider to host and run your servlet application check Vision servlet hosting plans

Example 2-3. The Hello servlet modified to return

January 14th, 2007

Example 2-3. The Hello servlet modified to return quickly in response to HEAD requests import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Hello extends HttpServlet { public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // Set the Content-Type header res.setContentType( text/html ); * Jason is proud to report that Sun added this feature in response to comments he made during beta testing. Example 2-3. The Hello servlet modified to return quickly in response to HEAD requests (continued) // Return early if this is a HEAD if (req.getMethod().equals ( HEAD )) return; // Proceed otherwise PrintWriter out = res.getWriter(); String name = req.getParameter ( name ); out.println( ); out.println( Hello, + name + ); out.println( ); out.println( Hello, + name); out.println( ); } } Notice that we set the Content-Typeheader, even if we are dealing with a HEAD request. Headers such as these are returned to the client. Some header values, such as Content-Length, may not be available until the response has already been calculated. If you want to be accurate in returning these header values, the effectiveness of this shortcut is limited. Make sure that you end the request handling with a returnstatement. Do not call System.exit(). If you do, you risk exiting the web server. Server-Side Includes All the servlets you’ve seen so far generate full HTML pages. If this were all that servlets could do, it would still be plenty. Servlets, however, can also be embedded inside HTML pages with something called server-side include (SSI) functionality. In many servers that support servlets, a page can be preprocessed by the server to include output from servlets at certain points inside the page. The tags used for a server-side include look similar to those used for applets:* If you see this text, it means that the web serverproviding this page does not support the SERVLET tag.
Quick Hint: If you are looking for best quality webspace to host and run your tomcat application check Vision tomcat hosting services

You’ve now seen two servlets that implement the

January 14th, 2007

You’ve now seen two servlets that implement the doGet()method. Now let’s change our Helloservlet so that it can handle POST requests as well. Because we want the same behavior with POST as we had for GET, we can simply dispatch all POST requests to the doGet()method with the following code: public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } Now the Hello servlet can handle form submissions that use the POST method:

In general, it is best if a servlet implements either doGet()or doPost(). Deciding which to implement depends on what sort of requests the servlet needs to be able to handle, as discussed earlier. The code you write to implement the methods is almost identical. The major difference is that doPost()has the added ability to accept large amounts of input. You may be wondering what would have happened had the Helloservlet been accessed with a POST request before we implemented doPost(). The default behavior inherited from HttpServletfor both doGet() and doPost()is to return an error to the client saying the requested URL does not support that method. Handling HEAD Requests A bit of under-the-covers magic makes it trivial to handle HEAD requests (sent by a client when it wants to see only the headers of the response). There is no doHead()method to write. Any servlet that subclasses HttpServletand implements the doGet()method automatically supports HEAD requests. Here’s how it works. The service()method of the HttpServletidentifies HEAD requests and treats them specially. It constructs a modified HttpServletResponseobject and passes it, along with an unchanged request, to the doGet()method. The doGet()method proceeds as normal, but only the headers it sets are returned to the client. The special response object effectively suppresses all body output.* Figure 2-6 shows how an HTTP servlet handles HEAD requests. Figure 2-6. An HTTP servlet handling a HEAD request Although this strategy is convenient, you can sometimes improve performance by detecting HEAD requests in the doGet()method, so that it can return early, before wasting cycles writing output that no one will see. Example 2-3 uses the request’s getMethod()method to implement this strategy (more properly called a hack) in our Helloservlet.

Hint: If you are looking for very good and affordable webspace to host and run your java hosting application check Sandzak.com java web hosting provider

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

January 13th, 2007

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Hello 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( ); out.println( Hello, + name + ); out.println( ); out.println( Hello, + name); out.println( ); } public String getServletInfo() { return A servlet that knows the name of the person to whom it’s + saying hello ; } } This servlet is nearly identical to the HelloWorldservlet. The most important change is that it now calls req.getParameter( name )to find out the name of the user and that it then prints this name instead of the harshly impersonal (not to mention overly broad) “World”. The getParameter()method gives a servlet access to the parameters in its query string. It returns the parameter’s decoded value or nullif the parameter was not specified. If the parameter was sent but without a value, as in the case of an empty form field, getParameter()returns the empty string. This servlet also adds a getServletInfo()method. A servlet can override this method to return descriptive information about itself, such as its purpose, author, version, and/or copyright. It’s akin to an applet’s getAppletInfo(). The method is used primarily for putting explanatory information into a web server administration tool. You’ll notice we won’t bother to include it in future examples because it is clutter for learning. The servlet’s output looks something like what is shown in Figure 2-5. Figure 2-5. The Hello servlet using form data Handling POST Requests

Note: If you are looking for good and affordable webspace to host and run your servlet application check Sandzak servlet hosting services

* Beware, servlets are placed in a servlets

January 13th, 2007

* Beware, servlets are placed in a servlets (plural) directory but are invoked with a servlet (singular) tag. If you think about it, this makes a certain amount of sense, as servlets go in the servlets directory while a single servlet is referenced with the servlet. Handling Form Data The “Hello World” servlet is not very exciting, so let’s try something slightly more ambitious. This time we’ll create a servlet that greets the user by name. It’s not hard. First, we need an HTML form that asks the user for his or her name. The following page should suffice: Introductions If you don’t mind me asking, what is your name?

Figure 2-4 shows how this page appears to the user. Figure 2-4. An HTML form When the user submits this form, his name is sent to the Helloservlet because we’ve set the ACTIONattribute to point to the servlet. The form is using the GET method, so any data is appended to the request URL as a query string. For example, if the user enters the name “Inigo Montoya,” the request URL is http://server:8080/servlet/Hello?name=Inigo+Montoya. The space in the name is specially encoded as a plus sign by the browser because URLs cannot contain spaces. A servlet’s HttpServletRequestobject gives it access to the form data in its query string. Example 2-2 shows a modified version of our Helloservlet that uses its request object to read the “name” parameter. Example 2-2. A servlet that knows to whom it’s saying hello
Note: If you are looking for cheap and inexpensive provider to host and run your tomcat application check professional tomcat hosting services

If you are using the Java Web Server,

January 12th, 2007

If you are using the Java Web Server, you should put the source code for the servlet in the server_root/servlets directory (where server_rootis the directory where you installed your server). This is the standard location for servlet class files. Once you have the “Hello World” source code in the right location, you need to compile it. The standard javac compiler (or your favorite graphical Java development environment) can do the job. Just be sure you have the javax.servletand javax.servlet.httppackages in your classpath. With the Java Web Server, all you have to do is include server_root/lib/jws.jar (or a future equivalent) somewhere in your classpath. Now that you have your first servlet compiled, there is nothing more to do but start your server and access the servlet! Starting the server is easy. Look for the httpd script (or httpd.exe program under Windows) in the server_root/bin directory. This should start your server if you’re running under Solaris or Windows. On other operating systems, or if you want to use your own Java Runtime Environment (JRE), you’ll need to use httpd.nojre. In the default configuration, the server listens on port 8080. There are several ways to access a servlet. For this example, we’ll do it by explicitly accessing a URL with /servlet/ prepended to the servlet’s class name.* You can enter this URL in your favorite browser: http://server:8080/servlet/HellWorld. Replace serverwith the name of your server machine or with localhost if the server is on your local machine. You should see a page similar to the one shown in Figure 2-3. Figure 2-3. The Hello World servlet If the servlet were part of a package, it would need to be placed in server_root/servlets/package/name and referred to with the URL http://server:8080/servlet/package.name.HelloWorld. An alternate way to refer to a servlet is by its registered name. This does not have to be the same as its class name, although it can be. With the Java Web Server, you register servlets via the JavaServer Administration Tool, an administration applet that manages the server, usually available at http://server:9090/. Choose to manage the Web Service, go to the Servlets section, and then Add a new servlet. Here you can specify the name of the new servlet and the class associated with that name (on some servers the class can be an HTTP URL from which the servlet class file will be automatically loaded). If we choose the name “hi” for our HelloWorldservlet, we can then access it at the URL http://server:8080/servlet/hi. You may wonder why anyone would bother adding a servlet to her server. The short answer appropriate for Chapter 2 is that it allows the server to remember things about the servlet and give it special treatment. A third way to access a servlet is through a servlet alias. The URL of a servlet alias looks like any other URL. The only difference is that the server has been told that the URL should be handled by a particular servlet. For example, we can choose to have http://server:8080/hello.html invoke the HelloWorldservlet. Using aliases in this way can help hide a site’s use of servlets; it lets a servlet seamlessly replace an existing page at any given URL. To create a servlet alias, choose to manage the Web Service, go to the Setup section, choose Servlet Aliases, and then Add the alias.
Hint: If you are looking for high quality webhost to host and run your jsp application check Vision web hosting jsp services

The HttpServletResponserepresents the servlet’s response. A servlet can

January 12th, 2007

The HttpServletResponserepresents the servlet’s response. A servlet can use this object to return data to the client. This data can be of any content type, though the type should be specified as part of the response. A servlet can also use this object to set HTTP response headers. Chapter 5 and Chapter 6, Sending Multimedia Content, explain everything a servlet can do as part of its response. Our servlet first uses the setContentType()method of the response object to set the content type of its response to “text/html”, the standard MIME content type for HTML pages. Then, it uses the getWriter()method to retrieve a PrintWriter, the international-friendly counterpart to a PrintStream. PrintWriterconverts Java’s Unicode characters to a locale-specific encoding. For an English locale, it behaves same as a PrintStream. Finally, the servlet uses this PrintWriterto send its “Hello World” HTML to the client. That’s it! That’s all the code needed to say hello to everyone who “surfs” to our servlet. Running Hello World When developing servlets you need two things: the Servlet API class files, which are used for compiling, and a servlet engine such as a web server, which is used for deployment. To obtain the Servlet API class files, you have several options: Install the Java Servlet Development Kit (JSDK), available for free at http://java.sun.com/products/servlet/. JSDK Version 2.0 contains the class files for the Servlet API 2.0, along with their source code and a simple web server that acts as a servlet engine for HTTP servlets. It works with JDK 1.1 and later. (Note that the JSDK is the Servlet API reference implementation, and as such its version number determines the Servlet API version number.) Install one of the many full-featured servlet engines, each of which typically bundles the Servlet API class files. There are dozens of servlet engines available for servlet deployment, several of which are listed in Chapter 1, Introduction. Why not use the servlet engine included in JSDK 2.0? Because that servlet engine is bare-bones simple. It implements the Servlet API 2.0 and nothing more. Features like robust session tracking, server-side includes, servlet chaining, and JavaServer Pages have been left out because they are technically not part of the Servlet API. For these features, you need to use a full-fledged servlet engine like the Java Web Server or one of its competitors. So, what do we do with our code to make it run in a web server? Well, it depends on your web server. The examples in this jsp blog use Sun’s Java Web Server 1.1.1, unofficially considered the reference implementation for how a web server should support servlets. It’s free for educational use and has a 30-day trial period for all other use. You can download a copy from http://java.sun.com/products or, for educational use, http://www.sun.com/products-n-solutions/edu/java/. The Java Web Server includes plenty of documentation explaining the use of the server, so while we discuss the general concepts involved with managing the server, we’re leaving the details to Sun’s documentation. If you choose to use another web server, these examples should work for you, but we cannot make any guarantees.
Hint: If you are looking for high quality webhost to host and run your jsp application check Vision web hosting jsp services

The remainder in the javax.servletand javax.servlet.httppackages are largely

January 11th, 2007

The remainder in the javax.servletand javax.servlet.httppackages are largely support classes. For example, the ServletRequestand ServletResponseclasses in javax.servletprovide access to generic server requests and responses, while HttpServletRequestand HttpServletResponsein javax.servlet.httpprovide access to HTTP requests and responses. The javax.servlet.httppackage also contains an HttpSessionclass that provides built-in session tracking functionality and a Cookieclass that allows you to quickly set up and process HTTP cookies. Page Generation The most basic type of HTTP servlet generates a full HTML page. Such a servlet has access to the same information usually sent to a CGI script, plus a bit more. A servlet that generates an HTML page can be used for all the tasks where CGI is used currently, such as for processing HTML forms, producing reports from a database, taking orders, checking identities, and so forth. Writing Hello World Example 2-1 shows an HTTP servlet that generates a complete HTML page. To keep things as simple as possible, this servlet just says ‘’Hello World” every time it is accessed via a web browser.* Example 2-1. A servlet that prints “Hello World” import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType ( text/html ); PrintWriter out = res.getWriter(); * Fun trivia: the first instance of a documented “Hello World” program appeared in A Tutorial Introduction to the Language B, written by Brian Kernighan in 1973. For those too young to remember, B was a precursor to C. You can find more information on the B programming language and a link to the tutorial at http://cm.bell-labs.com/who/dmr/bintro.html. Example 2-1. A servlet that prints “Hello World” (continued) out.println(”“); out.println(”Hello World“); out.println(”“); out.println(”Hello World“); out.println(”“); } } This servlet extends the HttpServletclass and overrides the doGet()method inherited from it. Each time the web server receives a GET request for this servlet, the server invokes this doGet()method, passing it an HttpServletRequestobject and an HttpServletResponseobject. The HttpServletRequestrepresents the client’s request. This object gives a servlet access to information about the client, the parameters for this request, the HTTP headers passed along with the request, and so forth. Chapter 4 explains the full capabilities of the request object. For this example, we can completely ignore it. After all, this servlet is going to say “Hello World” no matter what the request!

Hint: If you are looking for very good and affordable webspace to host and run your java hosting application check Sandzak.com java web hosting provider

Every servlet must implement the javax.servlet.Servletinterface. Most servlets

January 11th, 2007

Every servlet must implement the javax.servlet.Servletinterface. Most servlets implement it by extending one of two special classes: javax.servlet.GenericServletor javax.servlet.http.HttpServlet. A protocol-independent servlet should subclass GenericServlet, while an HTTP servlet should subclass HttpServlet, which is itself a subclass of GenericServletwith added HTTP-specific functionality. Unlike a regular Java program, and just like an applet, a servlet does not have a main()method. Instead, certain methods of a servlet are invoked by the server in the process of handling requests. Each time the server dispatches a request to a servlet, it invokes the servlet’s service()method. A generic servlet should override its service()method to handle requests as appropriate for the servlet. The service()method accepts two parameters: a request object and a response object. The request object tells the servlet about the request, while the response object is used to return a response. Figure 2-1 shows how a generic servlet handles requests. Figure 2-1. A generic servlet handling a request In contrast, an HTTP servlet usually does not override the service()method. Instead, it overrides doGet() to handle GET requests and doPost()to handle POST requests. An HTTP servlet can override either or both of these methods, depending on the type of requests it needs to handle. The service()method of HttpServlethandles the setup and dispatching to all the doXXX()methods, which is why it usually should not be overridden. Figure 2-2 shows how an HTTP servlet handles GET and POST requests. Figure 2-2. An HTTP servlet handling GET and POST requests An HTTP servlet can override the doPut()and doDelete()methods to handle PUT and DELETE requests, respectively. However, HTTP servlets generally don’t touch doHead(), doTrace(), or doOptions(). For these, the default implementations are almost always sufficient.
Note: If you are looking for good and quality webspace to host and run your java application check professional java hosting services

When a client connects to a server and

January 10th, 2007

When a client connects to a server and makes an HTTP request, the request can be of several different types, called methods. The most frequently used methods are GET and POST. Put simply, the GET method is designed for getting information (a document, a chart, or the results from a database query), while the POST method is designed for posting information (a credit card number, some new chart data, or information that is to be stored in a database). To use a bulletin board analogy, GET is for reading and POST is for tacking up new material. The GET method, although it’s designed for reading information, can include as part of the request some of its own information that better describes what to get such as an x, y scale for a dynamically created chart. This information is passed as a sequence of characters appended to the request URL in what’s called a query string. Placing the extra information in the URL in this way allows the page to be book-marked or emailed like any other. Because GET requests theoretically shouldn’t need to send large amounts of information, some servers limit the length of URLs and query strings to about 240 characters. The POST method uses a different technique to send information to the server because in some cases it may need to send megabytes of information. A POST request passes all its data, of unlimited length, directly over the socket connection as part of its HTTP request body. The exchange is invisible to the client. The URL doesn’t change at all. Consequently, POST requests cannot be bookmarked or emailed or, in some cases, even reloaded. That’s by design information sent to the server, such as your credit card number, should be sent only once. In practice, the use of GET and POST has strayed from the original intent. It’s common for long parameterized requests for information to use POST instead of GET to work around problems with overly-long URLs. It’s also common for simple forms that upload information to use GET because, well why not, it works! Generally, this isn’t much of a problem. Just remember that GET requests, because they can be bookmarked so easily, should not be allowed to cause damage for which the client could be held responsible. In other words, GET requests should not be used to place an order, update a database, or take an explicit client action in any way. Other Methods In addition to GET and POST, there are several other lesser-used HTTP methods. There’s the HEAD method, which is sent by a client when it wants to see only the headers of the response, to determine the document’s size, modification time, or general availability. There’s also PUT, to place documents directly on the server, and DELETE, to do just the opposite. These last two aren’t widely supported due to complicated policy issues. The TRACE method is used as a debugging aid it returns to the client the exact contents of its request. Finally, the OPTIONS method can be used to ask the server which methods it supports or what options are available for a particular resource on the server. The Servlet API Now that you have a basic understanding of HTTP, we can move on and talk about the Servlet API that you’ll be using to create HTTP servlets, or any kind of servlets, for that matter. Servlets use classes and interfaces from two packages: javax.servletand javax.servlet.http. The javax.servletpackage contains classes to support generic, protocol-independent servlets. These classes are extended by the classes in the javax.servlet.httppackage to add HTTP-specific functionality. The top-level package name is javaxinstead of the familiar java, to indicate that the Servlet API is a standard extension.
Quick Hint: If you are looking for best quality webspace to host and run your tomcat application check Vision tomcat hosting services

GET /intro.html HTTP/1.0 This request uses the GET

January 10th, 2007

GET /intro.html HTTP/1.0 This request uses the GET method to ask for the document named intro.html, using HTTP Version 1.0. After sending the request, the client can send optional header information to tell the server extra information about the request, such as what software the client is running and what content types it understands. This information doesn’t directly pertain to what was requested, but it could be used by the server in generating its response. Here are some sample request headers: User-Agent: Mozilla/4.0 (compatible; MSIE 4.0; Windows 95) Accept: image/gif, image/jpeg, text/*, */* The User-Agent header provides information about the client software, while the Accept header specifies the media (MIME) types that the client prefers to accept. (We’ll talk more about request headers in the context of servlets in Chapter 4, Retrieving Information.) After the headers, the client sends a blank line, to indicate the end of the header section. The client can also send additional data, if appropriate for the method being used, as it is with the POST method that we’ll discuss shortly. If the request doesn’t send any data, it ends with an empty line. After the client sends the request, the server processes it and sends back a response. The first line of the response is a status line that specifies the version of the HTTP protocol the server is using, a status code, and a description of the status code. For example: HTTP/1.0 200 OK This status line includes a status code of 200, which indicates that the request was successful, hence the description “OK”. Another common status code is 404, with the description “Not Found” as you can guess, this means that the requested document was not found. Chapter 5, Sending HTML Information, discusses common status codes and how you can use them in servlets, while Appendix C, HTTP Status Codes, provides a complete list of HTTP status codes. After the status line, the server sends response headers that tell the client things like what software the server is running and the content type of the server’s response. For example: Date: Saturday, 23-May-98 03:25:12 GMT Server: JavaWebServer/1.1.1 MIME-version: 1.0 Content-type: text/html Content-length: 1029 Last-modified: Thursday, 7-May-98 12:15:35 GMT The Server header provides information about the server software, while the Content-type header specifies the MIME type of the data included with the response. (We’ll also talk more about response headers in Chapter 5.) The server sends a blank line after the headers, to conclude the header section. If the request was successful, the requested data is then sent as part of the response. Otherwise, the response may contain human-readable data that explains why the server couldn’t fulfill the request. GET and POST
Note: If you are looking for cheapest and affordable webspace to host and run your servlet application check Astra j2ee hosting services

HTTP Servlet Basics In this chapter: HTTP

January 10th, 2007

HTTP Servlet Basics In this chapter: HTTP Basics The Servlet API Page Generation Server-Side Includes Servlet Chaining and Filters JavaServer Pages Moving On This chapter provides a quick introduction to some of the things an HTTP servlet can do. For example, an HTTP servlet can generate an HTML page, either when the servlet is accessed explicitly by name, by following a hypertext link, or as the result of a form submission. An HTTP servlet can also be embedded inside an HTML page, where it functions as a server-side include. Servlets can be chained together to produce complex effects one common use of this technique is for filtering content. Finally, snippets of servlet code can be embedded directly in HTML pages using a new technique called JavaServer Pages. Although the code for each of the examples in this chapter is available for down-load (as described in the Preface), we would suggest that for these first examples you deny yourself the convenience of the Internet and type in the examples. It should help the concepts seep into your brain. Don’t be alarmed if we seem to skim lightly over some topics in this chapter. Servlets are powerful and, at times, complicated. The point here is to give you a general overview of how things work, before jumping in and overwhelming you with all of the details. By the end of this jsp blog, we promise that you’ll be able to write servlets that do everything but make tea. HTTP Basics Before we can even show you a simple HTTP servlet, we need to make sure that you have a basic understanding of how the protocol behind the Web, HTTP, works. If you’re an experienced CGI programmer (or if you’ve done any serious server-side web programming), you can safely skip this section. Better yet, you might skim it to refresh your memory about the finer points of the GET and POST methods. If you are new to the world of server-side web programming, however, you should read this material carefully, as the rest of the book is going to assume that you understand HTTP. For a more thorough discussion of HTTP and its methods, see Web Client Programming by Clinton Wong (O’Reilly). Requests, Responses, and Headers HTTP is a simple, stateless protocol. A client, such as a web browser, makes a request, the web server responds, and the transaction is done. When the client sends a request, the first thing it specifies is an HTTP command, called a method, that tells the server the type of action it wants performed. This first line of the request also specifies the address of a document (a URL) and the version of the HTTP protocol it is using. For example:
Note: If you are looking for good and quality webspace to host and run your java application check professional java hosting services

The elegance of servlet code is striking. Servlet

January 9th, 2007

The elegance of servlet code is striking. Servlet code is clean, object oriented, modular, and amazingly simple. One reason for this simplicity is the Servlet API itself, which includes methods and classes to handle many of the routine chores of servlet development. Even advanced operations, like cookie handling and session tracking, are abstracted into convenient classes. A few more advanced but still common tasks were left out of the API, and, in those places, we have tried to step in and provide a set of helpful classes in the com.oreilly.servletpackage. Integration Servlets are tightly integrated with the server. This integration allows a servlet to cooperate with the server in ways that a CGI program cannot. For example, a servlet can use the server to translate file paths, perform logging, check authorization, perform MIME type mapping, and, in some cases, even add users to the server’s user database. Server-specific extensions can do much of this, but the process is usually much more complex and error-prone. Extensibility and Flexibility The Servlet API is designed to be easily extensible. As it stands today, the API includes classes that are optimized for HTTP servlets. But at a later date, it could be extended and optimized for another type of servlets, either by Sun or by a third party. It is also possible that its support for HTTP servlets could be further enhanced. Servlets are also quite flexible. As you’ll see in the next chapter, an HTTP servlet can be used to generate a complete web page; it can be added to a static page using a tag in what’s known as a server-side include; and it can be used in cooperation with any number of other servlets to filter content in something called a servlet chain. In addition, just before this jsp blog went to press, Sun introduced JavaServer Pages, which offer a way to write snippets of servlet code directly within a static HTML page, using a syntax that is curiously similar to Microsoft’s Active Server Pages (ASP). Who knows what they (or you) will come up with next.
Note: If you are looking for best hosting provider to host and run your tomcat application check Astra tomcat hosting services

Power Servlets can harness the full power of

January 9th, 2007

Power Servlets can harness the full power of the core Java APIs: networking and URL access, multithreading, image manipulation, data compression, database connectivity, internationalization, remote method invocation (RMI), CORBA connectivity, and object serialization, among others. If you want to write a web application that allows employees to query a corporate legacy database, you can take advantage of all of the Java Enterprise APIs in doing so. Or, if you need to create a web-based directory lookup application, you can make use of the JNDI API. As a servlet author, you can also pick and choose from a plethora of third-party Java classes and JavaBeans components. In the future, you’ll even be able to use newly introduced Enterprise JavaBeans components. Today, servlets can use thirdparty code to handle tasks such as regular expression searching, data charting, advanced database access, and advanced networking. Servlets are also well suited for enabling client/server communication. With a Javabased applet and a Java- based servlet, you can use RMI and object serialization to handle client/server communication, which means that you can leverage the same custom code on the client as on the server. Using CGI for the same purpose is much more complicated, as you have to develop your own custom protocol to handle the communication. Efficiency and Endurance Servlet invocation is highly efficient. Once a servlet is loaded, it generally remains in the server’s memory as a single object instance. Thereafter, the server invokes the servlet to handle a request using a simple, lightweight method invocation. Unlike with CGI, there’s no process to spawn or interpreter to invoke, so the servlet can begin handling the request almost immediately. Multiple, concurrent requests are handled by separate threads, so servlets are highly scalable Servlets, in general, are naturally enduring objects. Because a servlet stays in the server’s memory as a single object instance, it automatically maintains its state and can hold on to external resources, such as database connections, that may otherwise take several seconds to establish. Safety Servlets support safe programming practices on a number of levels. Because they are written in Java, servlets inherit the strong type safety of the Java language. In addition, the Servlet API is implemented to be type-safe. While most values in a CGI program, including a numeric item like a server port number, are treated as strings, values are manipulated by the Servlet API using their native types, so a server port number is represented as an integer. Java’s automatic garbage collection and lack of pointers mean that servlets are generally safe from memory management problems like dangling pointers, invalid pointer references, and memory leaks. Servlets can handle errors safely, due to Java’s exception-handling mechanism. If a servlet divides by zero or performs some other illegal operation, it throws an exception that can be safely caught and handled by the server, which can politely log the error and apologize to the user. If a C++-based server extension were to make the same mistake, it could potentially crash the server. A server can further protect itself from servlets through the use of a Java security manager. A server can execute its servlets under the watch of a strict security manager that, for example, enforces a security policy designed to prevent a malicious or poorly written servlet from damaging the server file system. Elegance

Note: If you are looking for good and affordable webspace to host and run your servlet application check Sandzak servlet hosting services

Embeddable Servlet Engines An embeddable engine is generally

January 8th, 2007

Embeddable Servlet Engines An embeddable engine is generally a lightweight servlet deployment platform that can be embedded in another application. That application becomes the true server. Embeddable servlet engines include the following: Sun’s JavaServer Engine, a high-quality, high-end framework for designing and building Java servers. Sun’s Java Web Server and IBM’s WebSphere Application Server were built using the Java Server Engine. See http://java.sun.com/products/javaserverengine/. Jef Poskanzer’s Acme.Serve, a freely available, simple web server that runs servlets “more or less compatible” with the Servlet API. See http://www.acme.com/java/software/Package-Acme. Serve.html. Paralogic’s WebCore, a freely available but unsupported embeddable web server, written entirely in Java. It incorporates parts of Acme.Serve. See http://www.paralogic.com/webcore/. Anders Kristensen’s Nexus Web Server, a freely available servlet runner that implements most of the Servlet API and can be easily embedded in Java applications. See http://www-uk.hpl.hp.com/people/ak/java/nexus/. Additional Thoughts Before proceeding, we feel obliged to point out that not all servlet engines are created equal. So, before you choose a servlet engine (and possibly a server) with which to deploy your servlets, take it out for a test drive. Kick its tires a little. Check the mailing lists. Always verify that your servlets behave as they do in the Java Web Server implementation. With servlets, you don’t have to worry about the lowestcommon-denominator implementation, so you should pick a servlet engine that has the functionality that you want. For a complete, up-to-date list of available servlet engines, see the official list maintained by Sun at: http://jserv.java.sun.com/products/java-server/servlets/environments.html The Power of Servlets So far, we have portrayed servlets as an alternative to other dynamic web content technologies, but we haven’t really explained why we think you should use them. What makes servlets a viable choice for web development? We believe that servlets offer a number of advantages over other approaches, including: portability, power, efficiency, endurance, safety, elegance, integration, extensibility, and flexibility. Let’s examine each in turn. Portability Because servlets are written in Java and conform to a well-defined and widely accepted API, they are highly portable across operating systems and across server implementations. You can develop a servlet on a Windows NT machine running the Java Web Server and later deploy it effortlessly on a high-end Unix server running Apache. With servlets, you can truly “write once, serve everywhere.” Servlet portability is not the stumbling block it so often is with applets, for two reasons. First, servlet portability is not mandatory. Unlike applets, which have to be tested on all possible client platforms, servlets have to work only on the server machines that you are using for development and deployment. Unless you are in the business of selling your servlets, you don’t have to worry about complete portability. Second, servlets avoid the most error-prone and inconsistently implemented portion of the Java language: the Abstract Windowing Toolkit (AWT) that forms the basis of Java graphical user interfaces.
Note: If you are looking for cheapest and affordable webspace to host and run your servlet application check Astra j2ee hosting services

Netscape’s Enterprise Server (Version 3.51 and later),

January 8th, 2007

Netscape’s Enterprise Server (Version 3.51 and later), the most popular web server to provide built-in servlet support. Unfortunately, Version 3.51 supports only the early Servlet API 1.0 and suffers from a number of bugs so significant it’s almost unusable. For the time being, use an add-on servlet engine with Netscape servers instead. See http://home.netscape.com/download. Lotus’s Domino Go Webserver (Version 4.6 and later), another popular web server with built-in servlet support. Version 4.6.x supports only the early Servlet API 1.0; however, Lotus claims to be replacing its proprietary GWAPI server extension technology with Java servlets, so it’s likely that future versions of the Domino Go Webserver will include robust servlet support. See http://www.lotus.com/dominogowebserver/. Application servers are a fertile new area of development. An application server offers server-side support for developing enterprise-based applications. Here are two application servers that include servlet engines: WebLogic’s Tengah Application Server, a high-end server written entirely in Java. See http://www.weblogic.com/products/tengahindex.html. ATG’s Dynamo Application Server 3, another high-end server written entirely in Java. See http://www.atg.com/. Add-on Servlet Engines An add-on servlet engine functions as a plug-in to an existing server it adds servlet support to a server that was not originally designed with servlets in mind. Add-on servlet engines have been written for many servers including Apache, Netscape’s FastTrack Server and Enterprise Server, Microsoft’s Internet Information Server and Personal Web Server, O’Reilly’s WebSite, Lotus Domino’s Go Webserver, StarNine’s WebSTAR, and Apple’s AppleShare IP. This type of engine acts as a stopgap solution until a future server release incorporates servlet support. A plug-in also can be used with a server that provides a poor or outdated servlet implementation. Add-on servlet engines include these: The Java-Apache project’s JServ module, a freely available servlet engine that adds servlet support to the extremely popular Apache server. See http://java.apache.org/. Live Software’s JRun, a freely available plug-in designed to support the full Servlet API on all the popular web servers on all the popular operating systems. The latest version even features a basic web server for development purposes. See http://www.livesoftware.com/products/jrun/. IBM’s WebSphere Application Server (formerly known as ServletExpress), a plug-in that is being called an application server. It is designed to support the full Servlet API on several popular web servers on several popular operating systems. See http://www.software.ibm.com/webservers/. New Atlanta’s ServletExec, a plug-in designed to support the full Servlet API on several web servers on several operating systems. See http://www.newatlanta.com/. Gefion Software’s WAICoolRunner, a freely available plug-in that supports most of the Servlet API on Netscape’s FastTrack Server and Enterprise Server versions 3.x and later, written in Java using Netscape’s WAI interface. See http://www.gefionsoftware.com/WAICoolRunner/. Unicom’s Servlet CGI Development Kit, a freely available framework that supports servlets on top of CGI. What it lacks in efficiency it makes up for in ubiquity. See http://www.unicom.net/java/.
Note: If you are looking for good and quality webspace to host and run your java application check professional java hosting services

Like Java itself, servlets were designed for portability.

January 7th, 2007

Like Java itself, servlets were designed for portability. Servlets are supported on all platforms that support Java, and servlets work with all the major web servers.* Java servlets, as defined by the Java Software division of Sun Microsystems (formerly known as JavaSoft), are the first standard extension to Java. This means that servlets are officially blessed by Sun and are part of the Java language, but they are not part of the core Java API. Therefore, although they may work with any Java Virtual Machine (JVM), servlet classes need not be bundled with all JVMs. More information about the Java Extension Framework is available at http//java.sun.com/products/jdk/1.2/docs/guide/extensions. To make it easy for you to develop servlets, Sun has made publicly available a set of classes that provide basic servlet support. The javax.servletand javax.servlet.httppackages constitute this Servlet API. Version 2.0 of these classes comes bundled with the Java Servlet Development Kit (JSDK) for use with the Java Development Kit version 1.1 and above; the JDSK is available for download from http://java.sun.com/products/servlet/.** Many web server vendors have incorporated these classes into their servers to provide servlet support, and several have also provided additional functionality. Sun’s Java Web Server, for instance, includes a proprietary interface to the server’s security features. It doesn’t much matter where you get the servlet classes, as long as you have them on your system, since you need them to compile your servlets. In addition to the servlet classes, you need a servlet engine, so that you can test and deploy your servlets. Your choice of servlet engine depends in part on the web server(s) you are running. There are three flavors of servlet engines: standalone, add-on, and embeddable. * Note that several web server vendors have their own server-side Java implementations, some of which have also been given the name ‘’servlets”. These are generally incompatible with Java servlets as defined by Sun. Most of these vendors are converting their Java support to standard servlets, or are introducing standard servlet support in parallel, to allow backward compatibility. ** At one point it was planned the contents of the JSDK would come bundled as part of JDK 1.2. However, it was later decided to keep the servlet classes separate from the JDK, to better allow for timely revisions and corrections to the JSDK. Standalone Servlet Engines A standalone engine is a server that includes built-in support for servlets. Such an engine has the advantage that everything works right out of the box. One disadvantage, however, is that you have to wait for a new release of the web server to get the latest servlet support. Because servlets are still fairly new, this sort of server is still a bit of a rarity. As the various vendors upgrade their web servers, we expect that many of the servers will provide built-in support for servlets. Standalone engines in web servers include the following: Sun’s Java Web Server (formerly called “Jeeves”), unofficially considered the reference implementation for how a servlet engine should support servlets. Written entirely in Java (except for two native code libraries that enhance its functionality but are not needed). See http://java.sun.com/products/. The World Wide Web Consortium’s Jigsaw Server, freely available and also written entirely in Java. See http://www.w3.org/Jigsaw. O’Reilly’s WebSite Professional (Version 2.1 and later), the first server not written in Java to provide built-in servlet support. See http://website.oreilly.com.
Note: If you are looking for good and quality webspace to host and run your java application check professional java hosting services

Java Servlets Enter Java servlets. As was said

January 7th, 2007

Java Servlets Enter Java servlets. As was said earlier, a servlet is a generic server extension a Java class that can be loaded dynamically to expand the functionality of a server. Servlets are commonly used with web servers, where they can take the place of CGI scripts. A servlet is similar to a proprietary server extension, except that it runs inside a Java Virtual Machine (JVM) on the server (see Figure 1 4), so it is safe and portable. Servlets operate solely within the domain of the server: unlike applets, they do not require support for Java in the web browser. Figure 1-4. The servlet life cycle Unlike CGI and FastCGI, which use multiple processes to handle separate programs and/or separate requests, servlets are all handled by separate threads within the web server process. This means that servlets are also efficient and scalable. Because servlets run within the web server, they can interact very closely with the server to do things that are not possible with CGI scripts. Another advantage of servlets is that they are portable: both across operating systems as we are used to with Java and also across web servers. As you’ll see shortly, all of the major web servers support servlets. We believe that Java servlets offer the best possible platform for web application development, and we’ll have much more to say about this later in the chapter. Although servlets are most commonly used as a replacement for CGI scripts on a web server, they can extend any sort of server. Imagine, for example, a Java-based FTP server that handles each command with a separate servlet. New commands can be added by simply plugging in new servlets. Or, imagine a mail server that allows servlets to extend its functionality, perhaps by performing a virus scan on all attached documents or handling mail filtering tasks. this jsp blog emphasizes the use of servlets as a replacement for CGI programs. We believe that, at least in the near term, most servlet developers will design and deploy servlets for use with HTTP servers. In the long term, however, other uses are likely to catch on, so this jsp blog takes pains to point out what functionality is applicable to generic servlets and what applies only to HTTP servlets. Whatever you hope to do with servlets, this jsp blog can help you with your task. Support for Servlets

Hint: If you are looking for very good and affordable webspace to host and run your tomcat hosting application check Sandzak.com tomcat web hosting provider

Because server-specific APIs use linked C or C++

November 22nd, 2006

Because server-specific APIs use linked C or C++ code, server extensions can run extremely fast and make full use of the server’s resources. Server extensions, however, are not a perfect solution by any means. Besides being difficult to develop and maintain, they pose significant security and reliability hazards: a crashed server extension can bring down the entire server. And, of course, proprietary server extensions are inextricably tied to the server API for which they were written and often tied to a particular operating system as well. Figure 1-3. The server extension life cycle Active Server Pages Microsoft has developed a technique for generating dynamic web content called Active Server Pages, or sometimes just ASP. With ASP, an HTML page on the web server can contain snippets of embedded code (usually VBScript or JScript although it’s possible to use nearly any language). This code is read and executed by the web server before it sends the page to the client. ASP is optimized for generating small portions of dynamic content. Support for ASP is built into Microsoft Internet Information Server Version 3.0 and above, available for free from http://www.microsoft.com/iis. Support for other web servers is available as a commercial product from Chili!Soft at http://www.chilisoft.com. For more information on programming Active Server Pages, see http://www. microsoft.com/workshop/server/default.asp and http://www.activeserverpages.com/. Server-side JavaScript Netscape too has a technique for server-side scripting, which it calls server-side JavaScript, or SSJS for short. Like ASP, SSJS allows snippets of code to be embedded in HTML pages to generate dynamic web content. The difference is that SSJS uses JavaScript as the scripting language. With SSJS, web pages are precompiled to improve performance. Support for server-side JavaScript is available only with Netscape FastTrack Server and Enterprise Server Version 2.0 and above. For more information on programming with server-side JavaScript, see http://developer.netscape.com/tech/javascript/ssjs/ssjs.html.
Note: If you are looking for cheapest and affordable webspace to host and run your servlet application check Astra servlet hosting services