January 26th, 2007
Our third option is to create a synchronized block that performs all the work that needs to be done serially, then use the results outside the synchronized block. For our counter servlet, we can increment the count in a synchronized block, save the incremented value to a local variable (a variable declared inside a method), then print the value of the local variable outside the synchronized block: PrintWriter out = res.getWriter(); int local_count; synchronized(this) { local_count = ++count; } out.println(”Since loading, this servlet has been accessed” + local_count + ” times.”); This change shrinks the synchronized block to be as small as possible, while still maintaining a consistent count. Our last option is to decide that we are willing to suffer the consequences of ignoring synchronization issues. Sometimes the consequences are quite acceptable. For this example, ignoring synchronization means that some clients may receive a count that’s a bit off. Not a big deal, really. If this servlet were supposed to return unique numbers, however, it would be a different story. Although it’s not possible with this example, an option that exists for other servlets is to change instance variables into local variables. Local variables are not available to other threads and thus don’t need to be carefully protected from corruption. At the same time, however, local variables are not persistent between requests, so we can’t use them to store the persistent state of our counter. A Holistic Counter Now, the “one instance per servlet” model is a bit of a gloss-over. The truth is that each registered name for a servlet (but not each alias) is associated with one instance of the servlet. The name used to access the servlet determines which instance handles the request. This makes sense because the impression to the client should be that differently named servlets operate independently. The separate instances are also a requirement for servlets that accept initialization parameters, as discussed later in this chapter. Our SimpleCounterexample uses the countinstance variable to track the number of times it has been accessed. If, instead, it needed to track the count for all instances (and thus all registered aliases), it can in some cases use a class, or static, variable. These variables are shared across all instances of a class. Example 3-2 demonstrates with a servlet that counts three things: the times it has been accessed, the number of instances created by the server (one per name), and the total times all of them have been accessed. Example 3-2. A more holistic counter import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class HolisticCounter extends HttpServlet { static int classCount = 0; // shared by all instances int count = 0; // separate for each servlet static Hashtable instances = new Hashtable(); // also shared Example 3-2. A more holistic counter (continued)
Hint: If you are looking for high quality and reliable webspace provider to host and run your jsp hosting application check Sandzak jsp web hosting provider
Posted in servlet | No Comments »
January 25th, 2007
If your servlets only read from the request, write to the response, and save information in local variables (that is, variables declared within a method), you needn’t worry about the interaction among these threads. Once any information is saved in nonlocal variables (that is, variables declared within a class but outside any specific method), however, you must be aware that each of these client threads has the ability to manipulate a servlet’s nonlocal variables. Without precautions, this may result in data corruption and inconsistencies. For example, the SimpleCounterservlet makes a false assumption that the counter incrementation and output occur atomically (immediately after one another, uninterrupted). It’s possible that if two requests are made to SimpleCounteraround the same time, each will print the same value for count. How? Imagine that one thread increments the count and just afterward, before the first thread prints the count, the second thread also increments the count. Each thread will print the same count value, after effectively increasing its value by 2.* The order of execution goes something like this count++ // Thread 1 count++ // Thread 2 out.println // Thread 1 out.println // Thread 2 Now, in this case, the inconsistency is obviously not a problem, but many other servlets have more serious opportunities for errors. To prevent these types of problems and the inconsistencies that come with them, we can add one or more synchronized blocks to the code. Anything inside a synchronized block or a synchronized method is guaranteed not to be executed concurrently by another thread. Before any thread begins to execute synchronized code, it must obtain a monitor (lock) on a specified class. If another thread already has that monitor because it is already executing the same synchronized block or some other block with the same monitor the first thread must wait. All this is handled by the language itself, so it’s very easy to use. Synchronization, however, should be used only when necessary. On some platforms, it requires a fair amount of overhead to obtain the monitor each time a synchronized block is entered. More importantly, during the time one thread is executing synchronized code, the other threads may be blocked waiting for the monitor to be released. * Odd factoid: if count were a 64-bit long instead of a 32-bit int, it would be theoretically possible for the increment to be only half performed at the time it is interrupted by another thread. This is because Java uses a 32-bit wide stack. For SimpleCounter, we have four options to deal with this potential problem. First, we could add the keyword synchronizedto the doGet()signature: public synchronized void doGet (HttpServletRequest req, HttpServletResponse res) This guarantees consistency by synchronizing the entire method, using the servlet class as the monitor. In general, though, this is not the right approach because it means the servlet can handle only one GET request at a time. Our second option is to synchronize just the two lines we want to execute atomically: PrintWriter out = res.getWriter(); synchronized (this) { count++; out.println (”Since loading, this servlet has been accessed” + count + ” times.”); } This approach works better because it limits the amount of time this servlet spends in its synchronized block, while accomplishing the same goal of a consistent count. Of course, for this simple example, it isn’t much different than the first option.
Note: If you are looking for best hosting provider to host and run your tomcat application check Astra tomcat hosting services
Posted in servlet | No Comments »
January 25th, 2007
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SimpleCounter extends HttpServlet { int count = 0; public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType( text/plain ); PrintWriter out = res.getWriter(); count++; out.println( Since loading, this servlet has been accessed + count + times. ); } } The code is simple it just prints and increments the instance variable named count but it shows the power of persistence. When the server loads this servlet, the server creates a single instance to handle every request made of the servlet. That’s why this code can be so simple. The same instance variables exist between invocations and for all invocations. A Simple Synchronized Counter From the servlet-developer’s perspective, each client is another thread that calls the servlet via the service(), doGet(), or doPost()methods, as shown in Figure 3-1.* * Does it seem confusing how one servlet instance can handle multiple requests at the same time? If so, it’s probably because when we picture an executing program we often see object instances performing the work, invoking each other’s methods and so on. But, although this model works for simple cases, it’s not how things actually work. In reality, all real work is done by threads. The object instances are nothing more than data structures manipulated by the threads. Therefore, if there are two threads running, it’s entirely possible that both are using the same object at the same time. Figure 3-1. Many threads, one servlet instance
Note: If you are looking for best hosting provider to host and run your tomcat application check Astra tomcat hosting services
Posted in servlet | No Comments »
January 24th, 2007
A Single Java Virtual Machine Most servlet engines want to execute all servlets in a single JVM. Where that JVM itself executes can differ depending on the server, though. With a server written in Java, such as the Java Web Server, the server itself can execute inside a JVM right alongside its servlets. With a single-process, multithreaded web server written in another language, the JVM can often be embedded inside the server process. Having the JVM be part of the server process maximizes performance because a servlet becomes, in a sense, just another low-level server API extension. Such a server can invoke a servlet with a lightweight context switch and can provide information about requests through direct method invocations. A multiprocess web server (which runs several processes to handle requests) doesn’t really have the choice to embed a JVM directly in its process because there is no one process. This kind of server usually runs an external JVM that its processes can share. With this approach, each servlet access involves a heavyweight context switch reminiscent of FastCGI. All the servlets, however, still share the same external process. Fortunately, from the perspective of the servlet (and thus from your perspective, as a servlet author), the server’s implementation doesn’t really matter because the server always behaves the same way. Instance Persistence We said above that servlets persist between requests as object instances. In other words, at the time the code for a servlet is loaded, the server creates a single class instance. That single instance handles every request made of the servlet. This improves performance in three ways: It keeps the memory footprint small. It eliminates the object creation overhead that would otherwise be necessary to create a new servlet object. A servlet can be already loaded in a virtual machine when a request comes in, letting it begin executing right away. It enables persistence. A servlet can have already loaded anything it’s likely to need during the handling of a request. For example, a database connection can be opened once and used repeatedly thereafter. It can even be used by a group of servlets. Another example is a shopping cart servlet that loads in memory the price list along with information about its recently connected clients. Yet another servlet may choose to cache entire pages of output to save time if it receives the same request again. Not only do servlets persist between requests, but so do any threads created by servlets. This perhaps isn’t useful for the run-of-the-mill servlet, but it opens up some interesting possibilities. Consider the situation where one background thread performs some calculation while other threads display the latest results. It’s quite similar to an animation applet where one thread changes the picture and another one paints the display. A Simple Counter To demonstrate the servlet life cycle, we’ll begin with a simple example. Example 3-1 shows a servlet that counts and displays the number of times it has been accessed. For simplicity’s sake, it outputs plain text. Example 3-1. A simple counter
Hint: This post is supported by Gama web hosting php services
Posted in servlet | No Comments »
January 24th, 2007
The Servlet Life Cycle In this chapter: The Servlet Alternative Servlet Reloading Init and Destroy Single-Thread Model Background Processing Last Modified Times The servlet life cycle is one of the most exciting features of servlets. This life cycle is a powerful hybrid of the life cycles used in CGI programming and lower-level NSAPI and ISAPI programming, as discussed in Chapter 1, Introduction. The Servlet Alternative The servlet life cycle allows servlet engines to address both the performance and resource problems of CGI and the security concerns of low-level server API programming. A servlet engine may execute all its servlets in a single Java virtual machine (JVM). Because they are in the same JVM, servlets can efficiently share data with each other, yet they are prevented by the Java language from accessing one another’s private data. Servlets may also be allowed to persist between requests as object instances, taking up far less memory than full-fledged processes. Before we proceed too far, you should know that the servlet life cycle is highly flexible. Servers have significant leeway in how they choose to support servlets. The only hard and fast rule is that a servlet engine must conform to the following life cycle contract: 1. Create and initialize the servlet. 2. Handle zero or more service calls from clients. 3. Destroy the servlet and then garbage collect it. It’s perfectly legal for a servlet to be loaded, created, and instantiated in its own JVM, only to be destroyed and garbage collected without handling any client requests or after handling just one request. Any servlet engine that makes this a habit, however, probably won’t last long on the open market. In this chapter we describe the most common and most sensible life cycle implementations for HTTP servlets.
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
Posted in servlet | No Comments »
January 23rd, 2007
Figure 2-13. Saying Hello using JavaServer pages in cooperation with a JavaBeans component Moving on We realize this chapter has been a whirlwind introduction to HTTP servlets. By now, we hope you have a sense of the different ways you can use servlets to handlea variety of web development tasks. Of course, servlets can do far more than say ‘’Hello World,” tell the time, and remove
Posted in servlet | No Comments »
January 23rd, 2007
<%@ import = HelloBean %>
Hello Hello, <%= hello.getName() %>
As you can see, using a JavaBeans component with JavaServer Pages greatly reduces the amount of code necessary in the page. This allows a clean separation of content (the functionality the bean provides) from presentation (the HTML structure of the page). By using a well-defined API to interact with the bean, even nonprogrammers can write JSP pages. The code for HelloBeanis shown in Example 2-12. Its class file should be placed in the server’s classpath (something like server_root/classes, although for the Java Web Server you need to first create this directory). Example 2-12. The HelloBean class public class HelloBean { private String name = World ; public void setName(String name) { this.name = name; } public String getName() { return name; } } This is about as simple a bean as you’ll ever see. It has a single nameproperty that is set using setName() and retrieved using getName(). The default value of nameis “World”, but when a request comes in that includes a NAMEparameter, the property is set automatically by the server with a call to setName(). To test the mechanism, try browsing to http://server:port/hellobean.jsp. You should see something similar to the screen shot in Figure 2-13.
Note: If you are looking for cheap and inexpensive provider to host and run your tomcat application check professional
tomcat hosting services
Posted in servlet | No Comments »
January 22nd, 2007
VARNAME=”prefs” If not given, the variable name of the bean is set to the value of its name attribute. TYPE Specifies the name of the bean’s class or interface type. For example: TYPE=”UserPreferencesBean” The type defaults to java.lang.Object. INTROSPECT Specifies if the server should set the bean’s properties using the parameter values in the client’s request. Its value must be “yes” or “no”. The default is “yes”. BEANNAME Specifies the serialized file or class file that contains the bean, used when first creating the bean. This is an optional attribute. For example: BEANNAME=”hellobean.ser” CREATE Specifies if the bean should be created if it doesn’t already exist. Its value must be “yes” or “no”. The default is “yes”. If createis set to “no” and a preexisting instance isn’t found, an error is returned to the client. SCOPE Specifies if the bean should be assigned to a specific request (where it is used once and destroyed or recycled) or to a client session (where it’s automatically made available every time the same client reconnects, within a certain time frame). Its value must be “request” or “session”. The default is “request”. Parameters can be passed to a bean as a list using a tags placed between the opening tag and the closing tag. The parameter values are used to set the bean’s properties using introspection. Example 2-11 demonstrates the use of a JavaBeans component with a JSP page; it says Hello with the help of a HelloBean. Example 2-11. Saying Hello using a JavaBean
Hint: If you are looking for high quality webhost to host and run your jsp application check Vision web hosting jsp services
Posted in servlet | No Comments »
January 20th, 2007
} JavaServer Pages and JavaBeans One of the most interesting and powerful ways to use JavaServer Pages is in cooperation with JavaBeans components. JavaBeans are reusable Java classes whose methods and variables follow specific naming conventions to give them added abilities. They can be embedded directly in a JSP page using tags. A JavaBean component can perform a well-defined task (execute database queries, connect to a mail server, maintain information about the client, etc.) and make its resulting information available to the JSP page through simple accessor methods.* The difference between a JavaBeans component embedded in a JSP page and a normal third-party class used by the generated servlet is that the web server can give JavaBeans special treatment. For example, a server can automatically set a bean’s properties (instance variables) using the parameter values in the client’s request. In other words, if the request includes a nameparameter and the server detects through introspection (a technique in which the methods and variables of a Java class can be programatically determined at runtime) that the bean has a nameproperty and a setName(String name)method, the server can automatically call setName()with the value of the nameparameter. There’s no need for getParameter(). * For more information on JavaBeans, see http://java.sun.com/bean/ and the book Developing Java Beans by Robert Englander (O’Reilly). A bean can also have its scope managed automatically by the server. A bean can be assigned to a specific request (where it is used once and destroyed or recycled) or to a client session (where it’s automatically made available every time the same client reconnects). Sessions and session tracking are covered in depth in Chapter 7, Session Tracking. A bean can even be implemented as a servlet! If the server detects that a bean implements the javax.servlet.Servletinterface (either directly or by extending GenericServletor HttpServlet), it will call the bean’s service()method once for each request and the bean’s init() method when the bean is first created. The utility of this functionality is debatable, but it can be used by beans that need to prepare somehow before handling requests. Beans are embedded in a JSP page using the tag. It has the following syntax: You can set the following attributes of the tag: NAME Specifies the name of the bean. This is the key under which the bean is saved if its scope extends across requests. If a bean instance saved under this name already exists in the current scope, that instance is used with this page. For example: NAME=”userPreferences” VARNAME Specifies the variable name of the bean. This is the name used by the page to refer to the bean and invoke its methods. For example:
Quick Hint: If you are looking for best quality webspace to host and run your tomcat application check Vision tomcat hosting services
Posted in servlet | No Comments »
January 20th, 2007
Example 2-9. Saying Hello using a JSP declaration
Hello Hello, <%= getName(request) %>
The background servlet created to generate this page might look like the servlet shown in Example 2-10. Example 2-10. The workhorse servlet for a JSP page with a declaration import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class _hello3_xjsp extends HttpServlet { public void service(HttpServletRequest request, HttpServletResponse response) Example 2-10. The workhorse servlet for a JSP page with a declaration (continued) throws ServletException, IOException { response.setContentType( text/html ); PrintWriter out = response.getWriter(); BufferedReader in = request.getReader(); out.printIn( ); out.printIn(
Hello ); out.printIn( ); out.printIn(
); out.printIn( Hello, + getName(request)); out.printIn(
); out.printIn( ); } private static final String DEFAULT_NAME = World ; private String getName(HttpServletRequest req) { String name = req.getParameter( name ); if (name == null) return DEFAULT_NAME; else return name; }
Note: If you are looking for cheapest and affordable webspace to host and run your servlet application check Astra
j2ee hosting services
Posted in servlet | No Comments »
January 20th, 2007
<%@ extends = "CustomHttpServletSuperclass" %> The default superclass is HttpServlet. implements Specifies a list of interfaces the servlet should implement. Multiple interfaces can be given in a comma- separated list or given through multiple import directives. For example: <%@ implements = "Serializable" %> The default behavior is to not implement anything. method Specifies the servlet method that should contain the generated code and handle client requests. The default is “service”, which handles all requests. For example: <%@ method = "doPost" %> language Specifies the scripting language used by the back-end. The default language is “java”. Some servers can choose to allow other languages. For example: <%@ language = "java" %> Example 2-8 shows a revised version of the Hello page that uses JSP expressions and directives. It uses a method directive to indicate it should handle POST requests, and it uses an expression to simplify its display of the nameparameter. Example 2-8. Saying Hello using JSP expressions and directives <%@ method = doPost %>
Hello <% if (request.getParameter( name ) == null) { %> Hello World <% } else { %> Hello, <%= request.getParameter( name ) %> <% } %>
The background workhorse servlet for this JSP page should look nearly identical to Example 2-7, with the only difference that this servlet implements doPost()instead of service(). Declarations Sometimes it’s necessary for a JSP page to define methods and nonlocal variables in its workhorse servlet. For this there is a construct called a JSP declaration. A declaration begins with a tag. In between the tags, you can include any servlet code that should be placed outside the servlet’s service method. Example 2-9 demonstrates this with a JSP page that uses a declaration to define the getName()method.
Note: If you are looking for cheapest and affordable webspace to host and run your servlet application check Astra
j2ee hosting services
Posted in servlet | No Comments »
January 19th, 2007
Figure 2-12. Generating JavaServer Pages Expressions and Directives In addition to scriptlets, JavaServer Pages allow the use of expressions and directives. A JSP expression begins with <%=and ends with %>. Any Java expression between the two tags is evaluated, the result is converted to a String, and the text is included directly in the page. This technique eliminates the clutter of an out.println()call. For example, <%= foo %>includes the value of the foovariable. A JSP directive begins with <%@and ends with %>. A directive allows a JSP page to control certain aspects of its workhorse servlet. Directives can be used to have the workhorse servlet set its content type, import a package, extend a different superclass, implement an interface, and handle either GET or POST requests. A directive can even specify the use of a non-Java scripting language. In between the directive tags certain key variables can be assigned values using the following syntax: <%@ varname = "value" %> Here are the six variables you can set: content_type Specifies the content type of the generated page. For example: <%@ content_type = "text/plain" %> The default content type is “text/html”. import Specifies a list of classes the servlet should import. Multiple classes can be given in a comma-separated list or given through multiple importdirectives. For example: <%@ import = "java.io.*,java.util.Hashtable" %> extends Specifies the superclass the servlet should extend. For example:
Note: If you are looking for cheap and inexpensive provider to host and run your tomcat application check professional tomcat hosting services
Posted in servlet | No Comments »
January 18th, 2007
How does JSP work? Behind the scenes, the server automatically creates, compiles, loads, and runs a special servlet to generate the page’s content, as shown in Figure 2-12. You can think of this special servlet as a background, workhorse servlet. The static portions of the HTML page are generated by the workhorse servlet using the equivalent of out.println() calls, while the dynamic portions are included directly. For example, the servlet shown in Example 2-7 might be the background workhorse for hello1.jsp.* Example 2-7. The workhorse servlet for hello1.jsp* import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class _hello1_xjsp extends HttpServlet { public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType( text/html ); PrintWriter out = response.getWriter(); BufferedReader in = request.getReader(); out.println( ); out.printIn(
Hello ); out.println( ); out.println(
); if (request.getParameter( name ) == null) { out.println( Hello World ); } else { out.println( Hello, + request.getParameter( name )); } out.println(
); out.println( ); } } The first time you access a JSP page, you may notice that it takes a short time to respond. This is the time necessary for the server to create and compile the background servlet. Subsequent requests should be as fast as ever because the server can reuse the servlet. The one exception is when the .jsp file changes, in which case the server notices and recompiles a new background servlet. If there’s ever an error in compiling, you can expect the server to somehow report the problem, usually in the page returned to the client. * If you’re interested in seeing the true servlet source code for a JSP page, poke around the directories under your server root. After all, the server needs to save the Java source code somewhere before compiling it! If you find the true servlet source, you’re likely to see that it is far more complicated and convoluted than what is shown here.
Note: If you are looking for inexpensive but high quality provider to host and run your serlvet application check Astra
servlet hosting services
Posted in servlet | No Comments »
January 18th, 2007
response The servlet response, an HttpServletResponseobject out The output writer, a PrintWriterobject in The input reader, a BufferedReaderobject Example 2-6 shows a simple JSP page that says ‘’Hello” in a manner similar to Example 2-2, though with a lot less code. It makes use of the predefined requestand outvariables. * An earlier technology, called Page Compilation, uses and tags and a different internal syntax. Page Compilation has been deprecated in favor of JavaServer Pages. If you have a server that supports JavaServer Pages and want to test this page, you should place the file under the server’s document root (probably server_root/public_html) and save it with a special extension. By default, this extension for JSP pages is .jsp. Assuming you have saved the page as hello1.jsp, you can then access it at the URL http://server:port/hello1.jsp. A screen shot is shown in Figure 2-11. Example 2-6. Saying Hello with JSP
Hello <% if (request.getParameter( name ) == null) { out.printIn( Hello World ); } else { out.printIn( Hello, + request.getParameter( name )); } %>
Figure 2-11. Saying Hello using JavaServer Pages Behind the Scenes
Note: If you are looking for cheap and quality provider to host and run your java application check Astra
java hosting services
Posted in servlet | No Comments »
January 18th, 2007
This directive indicates that all responses with a Content-Typeheader of java-internal/parsedhtmlshould be passed to the ssinclude(server-side include) servlet. Why is this necessary? Without it, the ssincludeservlet would handle only static files with the .shtml extension. It would suffer from the same loophole: dynamically created pages containing the tag would be ignored. With this directive, any servlet can set its content type to java-internal/parsed-html, which causes the ssincludeservlet to handle its output. To specify that all text/htmlcontent is passed through Deblink, we need to add our own directive: text/html=Deblink You need to restart your server before this change can take effect. After making this change, all HTML content served by the server has its
Posted in servlet | No Comments »
January 17th, 2007
Figure 2-10. Standard servlet aliases These mappings provide some insight into how the Java Web Server uses its core servlets. You can see / invokes file, *.shtml invokes ssinclude, and /servlet invokes invoker. The most specific wildcard pattern is used, which is why /servlet uses the invokerservlet to launch a servlet instead of using the file servlet to return a file. You can change the default aliases or add new aliases. For example, changing the /servlet prefix would change the URL used to access servlets. Right now, we’re interested in adding another alias. You should add an alias that specifies that *.html invokes file, Deblink. After making this change, any file ending in .html is retrieved by the fileservlet and passed to Deblink. Try it yourself. Create a blinky.html file in server_root/public_html that is sprinkled with a few blink tags and try surfing to http://server:8080/blinky.html. If everything’s set up right, all evidence of the blink tags is removed. The Loophole This technique has one large loophole: not all HTML comes from files with the .html extension. For example, HTML can come from a file with the .htm extension or from some dynamically created HTML. We can work around multiple file extensions with more aliases. This, however, still doesn’t catch dynamic content. We need our second technique for creating a servlet chain to plug that hole. We really want to specify that all text/htmlcontent should pass through the Deblinkservlet. The JavaServer Administration Tool does not yet include a graphical way to do this. Instead, we can make the change with a simple edit of a properties file. The properties file can be found at server_root/properties/server/javawebserver/webpageservice/mimeservlets.properties. It contains directives like this: java-internal/parsed-html=ssinclude
Hint: If you are looking for high quality webhost to host and run your jsp application check Vision web hosting jsp services
Posted in servlet | No Comments »
January 17th, 2007
Example 2-5. A servlet that removes the tag from HTML pages (continued) line = line.substring(0, index) + newString + line.substring(index + oldString.length()); index += newString.length(); } return line; } } This servlet overrides both the doGet()and doPost()methods. This allows it to work in chains that handle either type of request. The doGet()method contains the core logic, while doPost()simply dispatches to doGet(), using the same technique as the Helloexample. Inside doGet(), the servlet first fetches its print writer. Next, the servlet calls req.getContentType()to find out the content type of the data it is receiving. It sets its output type to match, or if getContentType() returned null, it realizes there is no incoming data to deblink and simply returns. To read the incoming data, the servlet fetches a BufferedReaderwith a call to req.getReader(). The reader contains the HTML output from the previous servlet in the chain. As the servlet reads each line, it removes any instance of or with a call to replace()and then returns the line to the client (or perhaps to another servlet in the chain). Note that the replacement is case-sensitive and inefficient; a solution to this problem that uses regular expressions is included in Chapter 13, Odds and Ends. A more robust version of this servlet would retrieve the incoming HTTP headers and pass on the appropriate headers to the client (or to the next servlet in the chain). Chapter 4 and Chapter 5 explain the handling and use of HTTP headers. There’s no need to worry about it now, as the headers aren’t useful for simple tasks like the one we are doing here. Running Deblink If you’re using the Java Web Server, before running Deblinkyou have to first tell the web server you want servlet chains enabled. Go to managing the Web Service, go to the Setup section, select Site, and then select Options. Here you can turn servlet chaining on. By default it’s turned off to improve performance. As we said before, there are two ways to trigger a servlet chain. A chain can be explicitly specified for certain requests, or it can be created on the fly when one servlet returns a content type that another servlet is registered to handle. We’ll use both techniques to run Deblink. First, we’ll explicitly specify that all files with a name matching the wildcard pattern *.html should be handled by the fileservlet followed by the Deblinkservlet. The fileservlet is a core Java Web Server servlet used to retrieve files. Normally it is the only servlet invoked to return an HTML file. But here, we’re going to pass its output to Deblinkbefore returning the HTML to the client. Go back to managing the Web Service, go to the Setup section, and select Servlet Aliases. Here you will see which servlets are invoked for different kinds of URLs, as shown in Figure 2-10.
Note: If you are looking for reliable and quality webspace company to host and run your servlet application check professional servlet hosting services
Posted in servlet | No Comments »
January 16th, 2007
They can easily be undone, so when users riot against your tyranny of removing their freedom, you can quickly reverse the change and appease the masses. They handle dynamically created content, so you can trust that your restrictions are maintained, your special tags are replaced, and your dynamically converted PostScript images are properly displayed, even in the output of a servlet (or a CGI script). They handle the content of the future, so you don’t have to run your script every time new content is added. Creating a Servlet Chain Our first servlet chain example removes tags from HTML pages. If you’re not familiar with the tag, be thankful. It is a tag recognized by many browsers in which any text between the and tags becomes a flashing distraction. Sure, it’s a useful feature when used sparingly. The problem is that many page authors use it far too often. It has become the joke of HTML. Example 2-5 shows a servlet that can be used in a servlet chain to remove the tag from all of our server’s static HTML pages, all its dynamically created HTML pages, and all the pages added to it in the future. This servlet introduces the getReader()and getContentType()methods. Example 2-5. A servlet that removes the tag from HTML pages import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Deblink extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String contentType = req.getContentType(); // get the incoming type if (contentType == null) return; // nothing incoming, nothing to do res.setContentType(contentType); // set outgoing type to be incoming type PrintWriter out = res.getWriter(); BufferedReader in = req.getReader(); String line = null; while ((line = in.readLine()) != null) { line = replace (line, , ); line = replace (line, , ); out.printin(line); } } public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } private String replace(String line, String oldString, String newString) { int index = 0; while ((index = line.indexOf(oldString, index)) >= 0) { // Replace the old string with the new string (inefficiently)
Note: If you are looking for good and affordable webspace to host and run your servlet application check Sandzak servlet hosting services
Posted in servlet | No Comments »
January 16th, 2007
There are two common ways to trigger a chain of servlets for an incoming request. First, you can tell the server that certain URLs should be handled by an explicitly specified chain. Or, you can tell the server to send all output of a particular content type through a specified servlet before it is returned to the client, effectively creating a chain on the fly. When a servlet converts one type of content into another, the technique is called filtering. Servlet chaining can change the way you think about web content creation. Here are some of the things you can do with it: Quickly change the appearance of a page, a group of pages, or a type of content. For example, you can improve your site by suppressing all tags from the pages of your server, as shown in the next example. You can speak to those who don’t understand English by dynamically translating the text from your pages to the language read by the client. You can suppress certain words that you don’t want everyone to read, be they the seven dirty words or words not everyone knows already, like the unreleased name of your secret project. You could also suppress entire pages in which these words appear. You can enhance certain words on your site, so that an online news magazine could have a servlet detect the name of any Fortune 1000 companies and automatically make each company name a link to its home page. * A web server could implement servlet chaining differently than described here. There is no reason the initial content must come from a servlet. It could come from a static file fetched with built-in server code or even from a CGI script. The Java Web Server does not have to make this distinction because all its requests are handled by servlets. Figure 2-9. Servlet chaining Take a kernel of content and display it in special formats. For example, you can embed custom tags in your page and have a servlet replace them with HTML content. Imagine an tag whose query contents are executed against a database and whose results are placed in an HTML table. This is, in fact, similar to how the Java Web Server supports the tag. Support esoteric data types. For example, you can serve unsupported image types with a filter that converts nonstandard image types to GIF or JPEG. You may be asking yourself, why you would want to use a servlet chain when you could instead write a script that edits the files in place especially when there is an additional amount of overhead for each servlet involved in handling a request? The answer is that servlet chains have a threefold advantage:
Note: If you are looking for cheap and quality provider to host and run your java application check Astra java hosting services
Posted in servlet | No Comments »
January 15th, 2007
The only method CurrentTimeimplements is the doGet()method. All SSI servlets use either doGet() or service()to handle requests. Inside the method, the servlet first retrieves its PrintWriter.* This early retrieval is perhaps unnecessary; it could be retrieved as late as the next to last line. Still, we recommend fetching it first thing. It will save time later when you find you need to begin sending output sooner than you expected. Then the servlet gets the current Dateand a DateFormatinstance with which to display the time. This servlet’s ability to hop time zones is based on functionality in DateFormat. The servlet simply tells the DateFormatwhich time zone to use, and the date is displayed appropriately. The time zone is specified by the tag in the HTML file. The servlet gains access to this parameter with the getParameter()method of HttpServletRequest. This technique is identical to the one we used to retrieve form data. The servlet uses the value of the “zone” parameter to create a TimeZoneobject that can be passed to the DateFormatobject. If the “zone” parameter is not specified, as is the case with the first SSI example on our page, getParameter()returns nulland the DateForamtuses the default time zone. Finally, the servlet outputs the Stringcreated when the DateFormatobject formats the current date. The output of the HTML page is shown in Figure 2-8. Servlet Chaining and Filters Now you’ve seen how an individual servlet can create content by generating a full page or by being used in a server-side include. Servlets can also cooperate to create content in a process called servelt chaining. * The Java Web Server 1.1.1 has a bug where the PrintWriterreturned by the getWriter()method of ServletRequestdoes not generate output for a servlet used as a server side include. This means that to run the SSI examples shown in the book you need to use another servlet engine; or you can change the examples to manually create a PrintWriteras follows: PrintWriter out = new PrintWriter(res.getOutputStream(), true); Figure 2-8. At the beep the current time will be In many servers that support servlets, a request can be handled by a sequence of servlets. The request from the client browser is sent to the first servlet in the chain. The response from the last servlet in the chain is returned to the browser. In between, the output from each servlet is passed (piped) as input to the next servlet, so each servlet in the chain has the option to change or extend the content, as shown in Figure 2-9.*
Note: If you are looking for inexpensive but high quality provider to host and run your serlvet application check Astra servlet hosting services
Posted in servlet | No Comments »