Archive for February, 2007

getServletContext().getAttribute( attribute )); } private String getServerInfoName(String serverInfo) { int

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

There are four methods that a servlet can

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

Example 4-2. Getting init parameter names import java.io.*;

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

Each registered servlet name can have specific initialization

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

More interaction with the server. Once a

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

Retrieving Information In this chapter: Initialization Parameters

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

Before returning this time value, the servlet rounds

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

Most web servers, when they return a document,

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

// Try dividing the number by all odd

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