February 4th, 2007
getServletContext().getAttribute( attribute )); } private String getServerInfoName(String serverInfo) { int slash = serverInfo.indexOf( / ); if (slash == -1) return serverInfo; else return serverInfo.substring(0, slash); } private String getServerInfoVersion(String serverInfo) { int slash = serverInfo.indexOf( / ); if (slash == -1) return null; else return serverInfo.substring(slash + 1); } } This servlet also directly subclasses GenericServlet, demonstrating that all the information about a server is available to servlets of any type. The servlet outputs simple raw text. When accessed, this servlet prints something like: req.getServerName(): localhost req.getServerPort(): 8080 getServletContext().getServerInfo(): JavaWebServer/1.1.1 getServerInfo() name: JavaWebServer getServerInfo() version: 1.1.1 getServletContext().getAttribute(”attribute”): null Unfortunately, there is no server-independent way to determine the server’s root directory, referred to in this book as server_root. However, some servers including the Java Web Server save the server’s root directory name in the server.rootsystem property, where it can be retrieved using System.getProperty( server.root ). Locking a Servlet to a Server This server information can be put to more productive uses. Let’s assume you’ve written a servlet and you don’t want it running just anywhere. Perhaps you want to sell it and, to limit the chance of unauthorized copying, you want to lock the servlet to your customer’s machine with a software license. Or, alternatively, you’ve written a license generator as a servlet and want to make sure it works only behind your firewall. This can be done relatively easily because a servlet has instant access to the information about its server. Example 4-4 shows a servlet that locks itself to a particular server IP address and port number. It requires an init parameter key that is appropriate for its server IP address and port before it unlocks itself and handles a request. If it does not receive the appropriate key, it refuses to continue. The algorithm used to map the key to the IP address and port (and vice-versa) must be secure. Example 4-4. A servlet locked to a server import java.io.*; import java.net.*; import java.util.*; import javax.servlet.*; public class KeyedServerLock extends GenericServlet { // This servlet has no class or instance variables // associated with the locking, so as to simplify // synchronization issues.
Hint: If you are looking for good and high quality web space to host and run your java application check Vision java web hosting services
Posted in servlet | No Comments »
February 4th, 2007
There are four methods that a servlet can use to learn about its server: two that are called using the ServletRequestobject passed to the servlet and two that are called from the ServletContextobject in which the servlet is executing. A servlet can get the name of the server and the port number for a particular request with getServerName()and getServerPort(), respectively: public String ServletRequest.getServerName() public int ServletRequest.getServerPort() These methods are attributes of ServletRequestbecause the values can change for different requests if the server has more than one name (a technique called virtual hosting). The returned name might be something like www.servlets.com” while the returned port might be something like 8080 . The getServerInfo()and getAttribute()methods of ServletContextprovide information about the server software and its attributes: public String ServletContext.getServerInfo() public Object ServletContext.getAttribute(String name) getServerInfo()returns the name and version of the server software, separated by a slash. The string returned might be something like JavaWebServer/1.1.1 . getAttribute()returns the value of the named server attribute as an Objector nullif the attribute does not exist. The attributes are server- dependent. You can think of this method as a back door through which a servlet can get extra information about its server. Attribute names should follow the same convention as package names. The package names java.* and javax.*are reserved for use by the Java Software division of Sun Microsystems (formerly known as JavaSoft), and com.sun.*is reserved for use by Sun Microsystems. See your server’s documentation for a list of its attributes. Because these methods are attributes of ServletContextin which the servlet is executing, you have to call them through that object: String serverInfo = getServletContext().getServerInfo(); The most straightforward use of information about the server is an “About This Server” servlet, as shown in Example 4-3. Example 4-3. Snooping the server import java.io.*; import java.util.*; import javax.servlet.*; public class ServerSnoop extends GenericServlet { public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { res.setContentType( text/plain ); PrintWriter out = res.getWriter(); out.println( req.getServerName(): + req.getServerName()); out.println( req.getServerPort(): + req.getServerPort()); out.println( getServletContext().getServerInfo(): + getServletContext().getServerInfo()); out.println( getServerInfo() name: + getServerInfoName(getServletContext().getServerInfo())); out.println( getServerInfo() version: + getServerInfoVersion(getServletContext().getServerInfo())); out.println( getServletContext().getAttribute( attribute ): +
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 »
February 3rd, 2007
Example 4-2. Getting init parameter names import java.io.*; import java.util.*; import javax.servlet.*; public class InitSnoop extends GenericServlet { // No init() method needed public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { res.setContentType( text/plain ); PrintWriter out = res.getWriter(); out.println( Init Parameters: ); Enumeration enum = getInitParameterNames(); while (enum.hasMoreElements()) { String name = (String) enum.nextElement(); out.println(name + : + getInitParameter(name)); } } } Notice that this servlet directly subclasses GenericServlet, showing that init parameters are available to servlets that aren’t HTTP servlets. A generic servlet can be used in a web server even though it lacks any support for HTTP-specific functionality. Unfortunately, there’s no server-independent way for a servlet to ask for its registered name or its class file location. This information may be added in a future version of the Servlet API. Until then, although it’s not pretty, this information can be passed using init parameters where necessary. Also, some servers including the Java Web Server provide a back door whereby a servlet can get its registered name. If a servlet defines a method with the following signature, the server calls it and passes it the servlet’s registered name at initialization: public void setServletName(String name); The servlet can save the passed-in name and use it later. You’ll notice this back door was built without changing the Servlet API, a necessary requirement because, by the time it was added, the Servlet API 2.0 had already been frozen. The Server A servlet can find out much about the server in which it is executing. It can learn the hostname, listening port, and server software, among other things. A servlet can display this information to a client, use it to customize its behavior based on a particular server package, or even use it to explicitly restrict the machines on which the servlet will run. Getting Information about the Server
Note: If you are looking for good and quality webspace to host and run your java application check professional java hosting services
Posted in servlet | No Comments »
February 3rd, 2007
Each registered servlet name can have specific initialization (init) parameters associated with it. Init parameters are available to the servlet at any time; they are often used in init ()to set initial or default values for a servlet or to customize the servlet’s behavior in some way. Init parameters are more fully explained in Chapter 3, The Servlet Life Cycle. Getting an Init Parameter A servlet uses the getInitParameter()method to get access to its init parameters: public String ServletConfig.getInitParameter(String name) This method returns the value of the named init parameter or nullif it does not exist. The return value is always a single String. It is up to the servlet to interpret the value. The GenericServletclass implements the ServletConfiginterface and thus provides direct access to the getInitParameter()method.* The method is usually called like this: public void init(ServletConfig config) throws ServletException { super.init(config); String greeting = getInitParameter(”greeting”); } A servlet that needs to establish a connection to a database can use its init parameters to define the details of the connection. We can assume a custom establishConnection()method to abstract away the details of JDBC, as shown in Example 4-1. * The servlet must call super.init(config)in its init()method to get this functionality. Example 4-1. Using init parameters to establish a database connection java.sql.Connection con = null; public void init(ServletConfig config) throws ServletException { super.init(config); String host = getInitParameter( host ); int port = Integer.parseInt(getInitparameter( port )); String db = getInitParameter( db ); String user = getInitParameter( user ); String password = getInitParameter( password ); String proxy = getInitParameter( proxy ); con = establishConnection(host, port, db, user, password, proxy); } Getting Init Parameter Names A servlet can examine all its init parameters using getInitParameterNames(): public Enumeration ServletConfig.getInitParameterNames() This method returns the names of all the servlet’s init parameters as an Enumerationof Stringobjects or an empty Enumerationif no parameters exist. It’s most often used for debugging. The GenericServletclass also makes this method directly available to servlets. Example 4-2 shows a servlet that prints the name and value for all of its init parameters.
Hint: This post is supported by Gama web hosting php mysql provider
Posted in servlet | No Comments »
February 2nd, 2007
More interaction with the server. Once a CGI program begins execution, it is untethered from its server. The only communication path available to the program is its standard output. A servlet, however, can work with the server. As discussed in the last chapter, a servlet operates either within the server (when possible) or as a connected process outside the server (when necessary). Using this connectivity, a servlet can make ad hoc requests for calculated information that only the server can provide. For example, a servlet can have its server do arbitrary path translations, taking into consideration the server’s aliases and virtual paths. If you’re coming to servlets from CGI, Table 4-1 is a ‘’cheat sheet” you can use for your migration. It lists each CGI environment variable and the corresponding HTTP servlet method. Table 4-1. CGI Environment Variables and the Corresponding Servlet Methods CGI Environment Variable HTTP Servlet Method SERVER_NAME req.getServerName() SERVER_SOFTWARE getServletContext().getServerInfo() SERVER_PROTOCOL req.getProtocol() SERVER_PORT req.getServerPort() REQUEST_METHOD req.getMethod() PATH_INFO req.getPathInfo() PATH_TRANSLATED req.getPathTranslated() SCRIPT_NAME req.getServletPath() DOCUMENT_ROOT req.getRealPath(”/”) QUERY_STRING req.getQueryString() REMOTE_HOST req.getRemoteHost() REMOTE_ADDR req.getRemoteAddr() AUTH_TYPE req.getAuthType() REMOTE_USER req.getRemoteUser() CONTENT_TYPE req.getContentType() CONTENT_LENGTH req.getContentLength() HTTP_ACCEPT req.getHeader(”Accept”) HTTP_USER_AGENT req.getHeader(”User-Agent”) HTTP_REFERER req.getHeader(”Referer”) In the rest of this chapter, we’ll see how and when to use these methods and several other methods that have no CGI counterparts. Along the way, we’ll put the methods to use in some real servlets. Initialization Parameters
Quick Hint: If you are looking for cheap and reliable provider to host and run your servlet application check Vision servlet hosting plans
Posted in servlet | No Comments »
February 2nd, 2007
Retrieving Information In this chapter: Initialization Parameters The Server The Client The Request To build a successful web application, you often need to know a lot about the environment in which it is running. You may need to find out about the server that is executing your servlets or the specifics of the client that is sending requests. And no matter what kind of environment the application is running in, you most certainly need information about the requests that the application is handling. Servlets have a number of methods available to gain access to this information. For the most part, each method returns one specific result. If you compare this to the way environment variables are used to pass a CGI program its information, the servlet approach has several advantages: Stronger type checking. In other words, more help from the compiler in catching errors. A CGI program uses one function to retrieve its environment variables. Many errors cannot be found until they cause runtime problems. Let’s look at how both a CGI program and a servlet find the port on which its server is running. A CGI script written in Perl calls: $port = $ENV{’SERVER_PORT’}; where $portis an untyped variable. A CGI program written in C calls: char *port = getenv(”SERVER_PORT”); where portis a pointer to a character string. The chance for accidental errors is high. The environment variable name could be misspelled (it happens often enough) or the data type might not match what the environment variable returns. A servlet, on the other hand, calls: int port = req.getServerPort() This eliminates a lot of accidental errors because the compiler can guarantee there are no misspellings and each return type is as it should be. Delayed calculation. When a server launches a CGI program, the value for each and every environment variable must be precalculated and passed, whether the CGI program uses it or not. A server launching a servlet has the option to improve performance by delaying these calculations and performing them on demand as needed.
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 »
February 2nd, 2007
Before returning this time value, the servlet rounds it down to the nearest second by dividing by 1000 and then multiplying by 1000. All times returned by getLastModified()should be rounded down like this. The reason is that the LastModifiedand If-Modified-Sinceheaders are given to the nearest second. If getLastModified()returns the same time but with a higher resolution, it may erroneously appear to be a few milliseconds later than the time given by If-Modified-Since. For example, let’s assume PrimeSearcherfound a prime exactly 869127442359 milliseconds since the beginning of the Disco Decade. This fact is told to the browser, but only to the nearest second: Thu, 17-Jul-97 09:17:22 GMT * A servlet can directly set its Last-Modifiedheader inside doGet(), using techniques discussed in Chapter 5, Sending HTML Information. However, by the time the header is set inside doGet(), it’s too late to decide whether or not to call doGet(). Now let’s assume that the user reloads the page and the browser tells the server, via the If-Modified- Sinceheader, the time it believes its cached page was last modified: Thu, 17-Jul-97 09:17:22 GMT Some servers have been known to receive this time, convert it to exactly 869127442000 milliseconds, find that this time is 359 milliseconds earlier than the time returned by getLastModified(), and falsely assume that the servlet’s content has changed. This is why, to play it safe, getLastModified()should always round down to the nearest thousand milliseconds. The HttpServletRequestobject is passed to getLastModified()in case the servlet needs to base its results on information specific to the particular request. The generic bulletin board servlet can make use of this to determine which board was being requested, for example.
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 »
February 1st, 2007
Most web servers, when they return a document, include as part of their response a Last-Modifiedheader. An example Last-Modifiedheader value might be: Tue, 06-May-98 15:41:02 GMT This header tells the client the time the page was last changed. That information alone is only marginally interesting, but it proves useful when a browser reloads a page. Most web browsers, when they reload a page, include in their request an If-Modified-Sinceheader. Its structure is identical to the Last-Modifiedheader: Tue, 06-May-98 15:41:02 GMT This header tells the server the Last-Modifiedtime of the page when it was last downloaded by the browser. The server can read this header and determine if the file has changed since the given time. If the file has changed, the server must send the newer content. If the file hasn’t changed, the server can reply with a simple, short response that tells the browser the page has not changed and it is sufficient to redisplay the cached version of the document. For those familiar with the details of HTTP, this response is the 304 “Not Modified” status code. This technique works great for static pages: the server can use the file system to find out when any file was last modified. For dynamically generated content, though, such as that returned by servlets, the server needs some extra help. By itself, the best the server can do is play it safe and assume the content changes with every access, effectively eliminating the usefulness of the Last-Modifiedand If-Modified-Sinceheaders. The extra help a servlet can provide is implementing the getLastModified()method. A servlet should implement this method to return the time it last changed its output. Servers call this method at two times. The first time the server calls it is when it returns a response, so that it can set the response’s Last-Modified header. The second time occurs in handling GETrequests that include the If-Modified-Sinceheader (usually reloads), so it can intelligently determine how to respond. If the time returned by getLastModified()is equal to or earlier than the time sent in the If-Modified-Sinceheader, the server returns the “Not Modified” status code. Otherwise, the server calls doGet()and returns the servlet’s output.* Some servlets may find it difficult to determine their last modified time. For these situations, it’s often best to use the “play it safe” default behavior. Many servlets, however, should have little or no problem. Consider a “bulletin board” servlet where people post carpool openings or the need for racquetball partners. It can record and return when the bulletin board’s contents were last changed. Even if the same servlet manages several bulletin boards, it can return a different modified time depending on the board given in the parameters of the request. Here’s a getLastModified()method for our PrimeSearcherexample that returns when the last prime was found. public long getLastModified(HttpServletRequest req) { return lastprimeModified.getTime() / 1000 * 1000; } Notice that this method returns a longvalue that represents the time as a number of milliseconds since midnight, January 1, 1970, GMT. This is the same representation used internally by Java to store time values. Thus, the servlet uses the getTime()method to retrieve lastprimeModifiedas a long.
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 »
February 1st, 2007
// Try dividing the number by all odd numbers between 3 and its sqrt double sqrt = Math.sqrt(candidate); for (long i = 3; i <= sqrt; i += 2) { if (candidate % i == 0) return false; // found a factor } // Wasn't evenly divisible, so it's prime return true; } public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType( text/plain ); PrintWriter out = res.getWriter(); if (lastprime == 0) { out.println( Still searching for first prime ); } else { out.println( The last prime discovered was + lastprime); out.println( at + lastprimeModified); } } public void destroy() { searcher.stop(); } } The searcher thread begins its search in the init()method. Its latest find is saved in lastprime, along with the time it was found in in lastprimeModified. Each time a client accesses the servlet, the doGet() method reports the largest prime found so far and the time it was found. The searcher runs independently of client accesses; even if no one accesses the servlet it continues to find primes silently. If several clients access the servlet at the same time, they all see the same current status. Notice that the destroy()method stops the searcher thread.* This is very important! If a servlet does not stop its background threads, they continue to run until the virtual machine exits. Even when a servlet is reloaded (either explicitly or because its class file changed), its threads won't be stopped. Instead, it's likely that the new servlet will create extra copies of the background threads. And, at least with the Java Web Server, even explicitly restarting the web server service doesn't stop background threads because the Java Web Server virtual machine continues its execution. * Stopping threads using the stop()method as shown here is deprecated in JDK 1.2 in favor of a safer flag-based system, where a thread must periodically examine a "flag" variable to determine when it should stop, at which point it can clean up and return from its run()method. See the JDK documentation for details. Example source code can be found in an article titled "Scott's Solutions: Programming with threads in Java 1.2", written by Scott Oaks for Java Report Online, found at http://www.sigs.com/jro/features/9711/oaks.htmlf. Last Modified Times By now, we're sure you've learned that servlets handle GETrequests with the doGet()method. And that's almost true. The full truth is that not every request really needs to invoke doGet(). For example, a web browser that repeatedly accesses PrimeSearchershould need to call doGet()only after the searcher thread has found a new prime. Until that time, any call to doGet()just generates the same page the user has already seen, a page probably stored in the browser's cache. What's really needed is a way for a servlet to report when its output has changed. That's where the getLastModified()method comes in.
Note: If you are looking for top 10 and very good webhost to host and run your jsp application check Actions jsp hosting services
Posted in servlet | No Comments »
January 31st, 2007
import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class PrimeSearcher extends HttpServlet implements Runnable { long lastprime = 0; // last prime foundDate lastprimeModified = new Date(); // when it was foundThread searcher; // background search thread public void init(ServletConfig config) throws ServletException { super.init(config); // always! searcher = new Thread(this); searcher.setPriority(Thread.MIN_PRIORITY); // be a good citizensearcher.start(); } public void run() { // QTTTBBBMMMTTTOOO long candidate = 1000000000000001L; // one quadrillion and one // Begin loop searching for primes while (true) { // search forever if (isPrime(candidate)) { lastprime = candidate; // new primelastprimeModified = new Date(); // new prime time } candidate += 2; // evens aren’t prime // Between candidates take a 0.2 second break. // Another way to be a good citizen with system resources. try { searcher.sleep(200); } catch (InterruptedException ignored) { } } } private static boolean isPrime(long candidate) { Example 3-6. On the hunt for primes (continued)
Hint: If you are looking for good and high quality web space to host and run your java application check Vision java web hosting services
Posted in servlet | No Comments »
January 31st, 2007
public class SingleThreadConnection extends HttpServletimplements SingleThreadModel { Connection con = null; // database connection, one per pooled servlet instance public void init(ServletConfig config) throws ServletException { super.init(config); // Establish the connection for this instance con = establishConnection(); con.setAutoCommit(false); } public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType( text/plain ); PrintWriter out = res.getWriter(); // Use the connection uniquely assigned to this instance Statement stmt = con.createStatement(); // Update the database any number of ways // Commit the transaction con.commit(); } public void destroy() { if (con !=null) con.close(); } private Connection establishConnection() { // Not implemented. See Chapter 9. } } Background Processing Servlets can do more than simply persist between accesses. They can also execute between accesses. Any thread started by a servlet can continue executing even after the response has been sent. This ability proves most useful for long-running tasks whose incremental results should be made available to multiple clients. A background thread started in init()performs continuous work while requesthandling threads display the current status with doGet(). It’s a similar technique to that used in animation applets, where one thread changes the picture and another paints the display. Example 3-6 shows a servlet that searches for prime numbers above one quadrillion. It starts with such a large number to make the calculation slow enough to adequately demonstrate caching effects something we need for the next section. The algorithm it uses couldn’t be simpler: it selects odd-numbered candidates and attempts to divide them by every odd integer between 3 and their square root. If none of the integers evenly divides the candidate, it is declared prime. Example 3-6. On the hunt for primes
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 30th, 2007
A server that loads a SingleThreadModelservlet must guarantee, according to the Servlet API documentation, “that no two threads will execute concurrently the service method of that servlet.” To accomplish this, each thread uses a free servlet instance from the pool, as shown in Figure 3-4. Thus, any servlet implementing SingleThreadModelcan be considered thread safe and isn’t required to synchronize access to its instance variables. Figure 3-4. The Single Thread Model Such a life cycle is pointless for a counter or other servlet application that requires central state maintenance. The life cycle can be useful, however, in avoiding synchronization while still performing efficient request handling. For example, a servlet that connects to a database sometimes needs to perform several database commands atomically as part of a single transaction. Normally, this would require the servlet to synchronize around the database commands (letting it manage just one request at a time) or to manage a pool of database connections where it can “check out” and “check in” connections (letting it support multiple concurrent requests). By instead implementing SingleThreadModeland having one “connection” instance variable per servlet, a servlet can easily handle concurrent requests by letting its server manage the servlet instance pool (which doubles as a connection pool). The skeleton code is shown in Example 3-5. Example 3-5. Handling database connections using SingleThreadModel import java.io.*; import java.sql.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; Example 3-5. Handling database connections using SingleThreadModel (continued)
Hint: This post is supported by Gama php5 hosting services
Posted in servlet | No Comments »
January 30th, 2007
Right now you’re probably asking yourself ‘’What happens if the server crashes?” It’s a good question. The answer is that the destroy()method will not be called.** This doesn’t cause a problem for destroy() methods that only have to free resources; a rebooted server does that job just as well (if not better). But it does cause a problem for a servlet that needs to save its state in its destroy()method. For these servlets, the only guaranteed solution is to save state more often. A servlet may choose to save its state after handling each request, such as a “chess server” servlet should do, so that even if the server is restarted, the game can resume with the latest board position. Other servlets may need to save state only after some important value has changed a “shopping cart” servlet needs to save its state only when a customer adds or removes an item from her cart. Last, for some servlets, it’s fine to lose a bit of the recent state changes. These servlets can save state after some set number of requests. For example, in our InitDestroyCounterexample, it should be satisfactory to save state every 10 accesses. To implement this, we can add the following line at the end of doGet(): * The exact location of the current user directory can be found using System.getProperty( user.dir ). ** Unless you’re so unlucky that your server crashes while in the destroy()method. In that case, you may be left with a partially-written state file garbage written on top of your previous state. To be perfectly safe, a servlet should save its state to a temporary file and then copy that file on top of the official state file in one command. if (count % 10 == 0) saveState(); Does this addition make you cringe? It should. Think about synchronization issues. We’ve opened up the possibility for data loss if saveState()is executed by two threads at the same time and the possibility for saveState()not to be called at all if count is incremented by several threads in a row before the check. Note that this possibility did not exist when saveState()was called only from the destroy()method: the destroy()method is called just once per servlet instance. Now that saveState()is called in the doGet()method, however, we need to reconsider. If by some chance this servlet is accessed so frequently that it has more than 10 concurrently executing threads, it’s likely that two servlets (10 requests apart) will be in saveState()at the same time. This may result in a corrupted data file. It’s also possible the two threads will increment countbefore either thread notices it was time to call saveState(). The fix is easy: move the countcheck into the synchronized block where countis incremented: int local_count; synchronized(this) { local_count = ++count; if (count % 10 == 0) saveState(); } out.println(”Since loading, this servlet has been accessed ” + local_count + ” times.”); The moral of the story is harder: always be vigilant to protect servlet code from multithreaded access problems. Even though this series of counter examples demonstrates the servlet life cycle, the counters themselves aren’t particularly useful because they count only the number of times they themselves have been accessed. You can find two truly useful counters that count accesses to other pages in the next chapter. Single-Thread Model Although it is standard to have one servlet instance per registered servlet name, it is possible for a servlet to elect instead to have a pool of instances created for each of its names, all sharing the duty of handling requests. Such servlets indicate this desire by implementing the javax.servlet.SingleThreadModelinterface. This is an empty, tag interface that defines no methods or variables and serves only to flag the servlet as wanting the alternate life cycle.
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 29th, 2007
} public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType( text/plain ); PrintWriter out = res.getWriter(); count++; out.println( Since the beginning, this servlet has been accessed + count + times. ); } public void destroy() { saveState(); } public void saveState() { // Try to save the accumulated count try { FileWriter fileWriter = new FileWriter( InitDestroyCounter.initial ); String initial = Integer.toString(count); fileWriter.write(initial, 0, initial.length()); fileWriter.close(); return; } catch (IOException e) { // problem during write // Log the exception. See Chapter 5. Example 3-4. A fully persistent counter (countinued) } } } Each time this servlet is about to be unloaded, it saves its state in a file named InitDestroyCounter.initial. In the absence of a supplied path, the file is saved in the server process’ current directory, usually the server_root.* This file contains a single integer, saved as a string, that represents the latest count. Each time the servlet is loaded, it tries to read the saved count from the file. If, for some reason, the read fails (as it does the first time the servlet runs because the file doesn’t yet exist), the servlet checks if an init parameter specifies the starting count. If that too fails, it starts fresh with zero. You can never be too careful in init() methods. Servlets can save their state in many different ways. Some may use a custom file format, as was done here. Others may save their state as serialized Java objects or put it into a database. Some may even perform journaling, a technique common to databases and tape backups, where the servlet’s full state is saved infrequently while a journal file stores incremental updates as things change. Which method a servlet should use depends on the situation. In any case, you should always be watchful that the state being saved isn’t undergoing any change in the background.
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 29th, 2007
This second style works even outside of the init()method. Just remember, without the call to super.init(config)in the init()method, any call to the GenericServlet’s implementation of getInitParameter()or any other ServletConfigmethods will throw a NullPointerException. So, let us say it again: every servlet’s init() method should call super.init(config) as its first action. The only reason not to is if the servlet directly implements the javax.servlet.Servletinterface, where there is no super.init(). A Counter with Init and Destroy Up until now, the counter examples have demonstrated how servlet state persists between accesses. This solves only part of the problem. Every time the server is shut down or the servlet is reloaded, the count begins again. What we really want is persistence across loads a counter that doesn’t have to start over. The init()and destroy()pair can accomplish this. Example 3-4 further extends the InitCounter example, giving the servlet the ability to save its state in destroy()and load the state again in init(). To keep things simple, assume this servlet is not registered and is accessed only as http://server:port/servlet/InitDestroyCounter. If it were registered under different names, it would have to save a separate state for each name. Example 3-4. A fully persistent counter import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class InitDestroyCounter extends HttpServlet { int count; public void init(ServletConfig config) throws ServletException { // Always call super.init(config) first (servlet mantra #1) super.init(config); Example 3-4. A fully persistent counter (countinued) // Try to load the initial count from our saved persistent state try { FileReader fileReader = new FileReader( InitDestroyCounter.initial ); BufferedReader bufferedReader = new BufferedReader(fileReader); String initial = bufferedReader.readLine(); count = Integer.parseInt(initial); return; } catch (FileNotFoundException ignored) { } // no saved state catch (IOException ignored) { } // problem during read catch (NumberFormatException ignored) { } // corrupt saved state // No luck with the saved state, check for an init parameter String initial = getInitParameter( initial ); try { count = Integer.parseInt(initial); return; } catch (NumberFormatException ignored) { } // null or non-integer value // Default to an initial count of 0 count = 0;
Hint: This post is supported by Gama php5 hosting services
Posted in servlet | No Comments »
January 28th, 2007
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class InitCounter extends HttpServlet { int count; public void init(ServletConfig config) throws ServletException { super.init(config); String initial = config.getInitParameter( initial ); try { count = Integer.parseInt(initial); } catch (NumberFormatException e) { 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 (and with a possible initialization ); out.println( parameter figured in), this servlet has been accessed ); out.println(count + times. ); } } The init()method accepts an object that implements the ServletConfiginterface. It uses the config object’s getInitParameter()method to get the value for the init parameter named initial. This method takes the name of the parameter as a Stringand returns the value as a String. There is no way to get the value as any other type. This servlet therefore converts the Stringvalue to an intor, if there’s a problem, defaults to a value of O. Take special note that the first thing the init()method does is call super.init(config). Every servlet’s init() method must do this! Why must the init()method call super.init(config)? The reason is that a servlet is passed its ServletConfiginstance in its init()method, but not in any other method. This could cause a problem for a servlet that needs to access its config object outside of init(). Calling super.init(config)solves this problem by invoking the init()method of GenericServlet, which saves a reference to the config object for future use. So, how does a servlet make use of this saved reference? By invoking methods on itself. The GenericServletclass itself implements the ServletConfiginterface, using the saved config object in the implementation. In other words, after the call to super.init(config), a servlet can invoke its own getInitParameter()method. That means we could replace the following call: String initial = config.getInitParameter(”initial”); with: String initial = getInitParameter(”initial”);
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 28th, 2007
This ServletConfigobject supplies a servlet with information about its initialization (init) parameters. These parameters are given to the servlet itself and are not associated with any single request. They can specify initial values, such as where a counter should begin counting, or default values, perhaps a template to use when not specified by the request. In the Java Web Server, init parameters for a servlet are usually set during the registration process. See Figure 3-3. Other servers set init parameters in different ways. Sometimes it involves editing a configuration file. One creative technique you can use with the Java Web Server, but currently by no other servers, is to treat servlets as JavaBeans. Such servlets can be loaded from serialized files or have their init properties set automatically by the server at load time using introspection. See the Java Web Server documentation for more information. Figure 3-3. Setting init parameters in the Java Web Server The ServletConfigobject also holds a reference to a ServletContextobject that a servlet may use to investigate its environment. See Chapter 4, Retrieving Information, for a full discussion of this ability. The server calls a servlet’s destroy()method when the servlet is about to be unloaded. In the destroy() method, a servlet should free any resources it has acquired that will not be garbage collected. The destroy() method also gives a servlet a chance to write out its unsaved cached information or any persistent information that should be read during the next call to init(). A Counter with Init Init parameters can be used for anything. In general, they specify initial values or default values for servlet variables, or they tell a servlet how to customize its behavior in some way. Example 3-3 extends our SimpleCounterexample to read an init parameter (named initial) that stores the initial value for our counter. Example 3-3. A counter that reads init parameters
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 27th, 2007
When a server dispatches a request to a servlet, it first checks if the servlet’s class file has changed on disk. If it has changed, the server abandons the class loader used to load the old version and creates a new instance of the custom class loader to load the new version. Old servlet versions can stay in memory indefinitely (and, in fact, other classes can still hold references to the old servlet instances, causing odd side effects, as explained in Chapter 11, Interservlet Communication), but the old versions are not used to handle any more requests. Servlet reloading is not performed for classes found in the server’s classpath (such as server_root/classes) because those classes are loaded by the core, primordial class loader. These classes are loaded once and retained in memory even when their class files change. It’s generally best to put servlet support classes (such as the utility classes in com.orielly.servlet) somewhere in the server’s classpath (such as server_root/classes) where they don’t get reloaded. The reason is that support classes are not nicely reloaded like servlets. A support class, placed in the default servlets directory and accessed by a servlet, is loaded by the same class loader instance that loaded the servlet. It doesn’t get its own class loader instance. Consequently, if the support class is recompiled but the servlet referring to it isn’t, nothing happens. The server checks only the timestamp on servlet class files.* A frequently used trick to improve performance is to place servlets in the default servlet directory during development and move them to the server’s classpath for deployment. Having them out of the default directory eliminates the needless timestamp comparison for each request. * For the daredevils out there, here’s a stunt you can try to force a support class reload. Put the support class in the servlet directory. Then convince the server it needs to reload the servlet that uses the support class (recompile it or use the Unix utility touch). The class loader that reloads the servlet should also load the new version of the support class. Init and Destroy Just like applets, servlets can define init()and destroy()methods. A servlet’s init(ServletConfig)method is called by the server immediately after the server constructs the servlet’s instance. Depending on the server and its configuration, this can be at any of these times: When the server starts When the servlet is first requested, just before the service()method is invoked At the request of the server administrator In any case, init()is guaranteed to be called before the servlet handles its first request. The init()method is typically used to perform servlet initialization creating or loading objects that are used by the servlet in the handling of its requests. Why not use a constructor instead? Well, in JDK 1.0 (for which servlets were originally written), constructors for dynamically loaded Java classes (such as servlets) couldn’t accept arguments. So, in order to provide a new servlet any information about itself and its environment, a server had to call a servlet’s init()method and pass along an object that implements the ServletConfiginterface. Also, Java doesn’t allow interfaces to declare constructors. This means that the javax.servlet.Servletinterface cannot declare a constructor that accepts a ServletConfigparameter. It has to declare another method, like init(). It’s still possible, of course, for you to define constructors for your servlets, but in the constructor you don’t have access to the ServletConfigobject or the ability to throw a ServletException.
Note: If you are looking for top 10 and very good webhost to host and run your jsp application check Actions jsp hosting services
Posted in servlet | No Comments »
January 27th, 2007
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 instance has been accessed + count + times. ); // Keep track of the instance count by putting a reference to this // instance in a Hashtable. Duplicate entries are ignored. // The size() method returns the number of unique instances stored. instances.put(this, this); out.println( There are currently + instances.size() + instances. ); classCount++; out.println( Across all instances, this servlet class has been + accessed + classCount + times. ); } } This HolisticCountertracks its own access count with the countinstance variable, the shared count with the classCountclass variable, and the number of instances with the instanceshashtable (another shared resource that must be a class variable). Sample output is shown in Figure 3-2. Figure 3-2. Output from HolisticCounter Servlet Reloading If you tried using these counters for yourself, you may have noticed that any time you recompiled one, its count automatically began again at 1. Trust us it’s not a bug, it’s a feature. Most servers automatically reload a servlet after its class file (under the default servlet directory, such as server_root/servlets) changes. It’s an on-the-fly upgrade procedure that greatly speeds up the development-test cycle and allows for long server uptimes. Servlet reloading may appear to be a simple feature, but it’s actually quite a trick and requires quite a hack. ClassLoaderobjects are designed to load a class just once. To get around this limitation and load servlets again and again, servers use custom class loaders that load servlets from the default servlets directory. This explains why the servlet classes are found in server_root/servlets, even though that directory doesn’t appear in the server’s classpath.
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 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 »