Archive for July, 2007

Web design tools - original exception thrown may be IOExceptionor SQLException, but

Tuesday, July 31st, 2007

original exception thrown may be IOExceptionor SQLException, but the user doesn’t need to know or care about this level of detail; all he needs to know is that the update function failed. Although the end user doesn’t care about the specific exception thrown, the system administrator or the developers who will be assigned the task of debugging and fixing the problem do. That’s why you don’t want to throw away the root cause of the problem when you rethrow a different exception. Prior to Version 1.4, Java didn’t provide a built-in mechanism to wrap the original exception with a new one. Developers were left to their own devices to solve the problem. Most homegrown solutions looked something like the exception class in Example 10-1. Example 10-1. An exception class that supports chained exceptions import java.io.PrintStream; import java.io.PrintWriter; /** * This is the common superclass for all applicationexceptions. This * class and its subclasses support the chained exceptionfacility that allows * a root cause Throwable to be wrapped by this class or oneof its * descendants. */ public class BaseException extends Exception { protected Throwable rootCause = null; protected BaseException( Throwable rootCause ) { this.rootCause = rootCause; } public void setRootCause(Throwable anException) { rootCause = anException; } public Throwable getRootCause( ) { return rootCause; } public void printStackTrace( ) { printStackTrace(System.err); } public void printStackTrace(PrintStream outStream) { printStackTrace(new PrintWriter(outStream)); } public void printStackTrace(PrintWriter writer) { super.printStackTrace(writer); if ( getRootCause( ) != null ) {
Searching for affordable and proven webhost to host and run your servlet applications? Go to Linux Web Hosting services and you will find it.

Of course, rules are (Web space) always somewhat subjective, and

Tuesday, July 31st, 2007

Of course, rules are always somewhat subjective, and what is a valid reason to one developer may not be to another. You should be aware of the drawbacks and avoid using try/catch blocks other than for actual error conditions. 10.2 System Versus Application Exceptions Exceptions can be further classified into either system exceptions or application exceptions. System exceptions are more serious in nature. These are typically low-level problems that aren’t related to the application logic and from which end users are not expected to recover. In many cases, system exceptions are unchecked, and your application isn’t supposed to catch them because they are either non-programming errors or are so severe that nothing can be done about them. Application exceptions are errors that occur because of a violation of a business rule or some other condition in the application logic. For example, you might throw an application exception when a user attempts to log in to the application but the account has been locked. This isn’t a catastrophic error, but it is a problem that needs to be reported and handled. Within Struts applications (and web applications in general), there are essentially two approaches you can take when an exception occurs. If the exception is an application exception from which the end user may be able to recover, you typically want to return control back to the input page and display a user-friendly statement of the problem and some action that can be taken to resolve it. Continuing with the locked account example, you could throw an AccountLockedExceptionback to the action class, which would forward control back to the login page and inform the user that the account is locked. If the thrown exception is a low-level exception such as a RemoteException, the only meaningful action the application can take is to display a system error page. There’s nothing the user can do to fix the problem. It may be a programming error or some type of network issue, but the point is that you don’t want to let the user see the stack trace of the exception. Instead, forward to a system error page that’s more user-friendly to look at and optionally informs the user to notify the system administrator. The exception should also be logged to aid the developer in determining the root cause of the problem. Later in this chapter, you’ll see examples of how to return control back to the input page and show a localized message to the user. You will also learn ways of dealing with system errors by forwarding control to a system error page, all of which will add value to the application and to the user experience. 10.3 Using Chained Exceptions It’s often suitable to catch a particular type of exception and rethrow a different one. This is sometimes necessary because a client might not know or care to handle the original exception. For example, say that a client invokes an action on a Struts application to upload an image file to a database. Let’s further assume the Action class calls an update method whose signature looks like the following: public void updateImageFile( String imagePath ) throwsUploadException; When the method is called with an image to upload and a problem occurs, an UploadExceptionwill be thrown. However, the underlying problem will be more specific for example, the filesystem is full or the database already has the image, depending on the destination of the image upload. The
Check Tomcat Web Hosting services for best quality webspace to host your web application.

10.1.4 Checked and Unchecked Exceptions (Web hosting comparison) Java exceptions can

Tuesday, July 31st, 2007

10.1.4 Checked and Unchecked Exceptions Java exceptions can be separated into two distinct groups: checked and unchecked. A checked exception signals an abnormal condition that the client must handle. All checked exceptions must either be caught and handled within the calling method or be declared in the throws clause following the method signature. This is why they are called “checked.” The compiler and the JVM will verify that all checked exceptions that can occur in a method are handled. The compiler and JVM don’t care if unchecked exceptions are ignored, because these are exceptions that the client usually cannot handle anyway. Unchecked exceptions, such as java.lang.ClassCastException, are typically the result of incorrect logic or programming errors. The determination of whether an exception is checked or unchecked is based simply on its location in the exception hierarchy. All classes that are descendants of the java.lang.Exception class, except for subclasses of RuntimeException , are checked exceptions; the compiler will ensure that they are either handled by the method or listed in the throws clause. RuntimeExceptionand its descendants are unchecked exceptions, and the compiler will not complain about these not being listed in a throws clause for a method or being handled in a try/catch block. This is why they are referred to as “unchecked.” 10.1.5 Performance Impact of Exception Handling In general, wrapping your Java code with try/catch blocks doesn’t have a significant performance impact on your applications. Only when exceptions actually occur is there a negative performance impact, which is due to the lookup the JVM has to perform to locate the proper handler for the exception. If the catch block for the exception is located in the same method, the impact is not so bad. However, the further down the call stack the JVM has to go to find the exception handler, the greater the impact becomes. This is why you should use a try/catch block only for error conditions. You should never use exceptions for things such as controlling program flow. The following use of a try/catch block is probably fine, but it’s getting very close to improper use of exception handling: Double basePrice = null; String basePriceStr = request.getParameter( “BASE_PRICE_AMOUNT” ); // Use a try/catch to make sure the value is a number try{ basePrice = Double.valueOf( basePriceStr ); }catch( NumberFormatException ex ){ // The value could not be converted to a valid Double; setthe default basePrice = ApplicationDefaults.DEFAULT_BASE_PRICE; } The previous code fragment shows a try/catch block determining an error condition and taking corrective action. The error condition is an invalid price value, and the corrective action is to assign a default value. There are other ways to determine whether a string is a valid Double value, but using this approach is fairly popular. Fortunately, the exception handler is located in the same method, and the JVM doesn’t incur a large penalty for this occurrence.
From our experience, we are can tell you that you can find a reliable and cheap webhost service at Java Web Hosting services.

When a Java (Ftp web hosting) method completes normally, the JVM

Monday, July 30th, 2007

When a Java method completes normally, the JVM pops the current method’s stack frame from the stack and continues processing in the previous method where it left off. When an exception condition occurs, however, the JVM must find a suitable exception handler. It first checks to see if the current method catches the exception or one of its parent exceptions. If so, execution will continue in that catch clause. If the current method doesn’t provide a catch clause to handle the exception raised, the JVM will start popping method frames off the call stack until it finds a handler for the exception or one of its parent exceptions. Eventually, if it pops all the way back to the main( )method and still doesn’t find a handler for the exception, the thread will terminate. If that thread is the main thread and there are no other non-daemon threads running, the application itself will terminate. If the JVM does find an exception handler along the way, that method frame will become the top of the stack and execution will continue from there. It’s important to know how the JVM handles exceptions because there is plenty going on underneath the hood when exceptions occur in your applications. It can be a lot of work for the JVM to locate an exception handler for a particular exception, especially if the handler is located far down the call stack. It’s very important that you provide sufficient exception handlers at the appropriate levels. If you let exceptions go, they are likely to halt your application. 10.1.3 What About the throws Clause? When determining the method signatures for classes that are part of an application, you should give as much attention to deciding which exceptions the methods will throw as to what the parameters are and what the return type is. You might have heard of the concept “design by contract.” The idea behind this principle is that the set of public methods that a class exposes represents a virtual contract between a client and the class itself. The client has certain obligations in the way in which it invokes the method, and there may also be requirements on the class itself as part of the contract. When something abnormal occurs and an exception is thrown from a method in the class, the contract, in a sense, has been broken. The class is informing the client that it can’t fulfill its terms of the contract. It’s entirely up to the caller to decide how to handle the exception. This is why the throws clause of a method signature is so important it forces a client to decide what it will do when one of these abnormal conditions occurs. However, as you’ll see in the next section, all Java exceptions are not equal.
If you are looking for cheap and quality webhost to host and run your website check Jboss Web Hosting services.

Figure 10-1. A partial class hierarchy for the (Web hosting plans)

Monday, July 30th, 2007

Figure 10-1. A partial class hierarchy for the Throwable class Space does not permit all of the descendants of the Throwable class to be shown, as there are more than 100 direct and indirect subclasses in the core Java library alone. Normally, members of the Exceptionbranches of the tree are thrown to indicate abnormal conditions that can usually be handled by the application. All of the exceptions your Struts application creates and throws should be subclasses of the Exception class. The other branch of Throwable, the Error class and its descendants, is reserved for more serious problems that occur during an application’s lifecycle. For example, if there’s no more memory available for an application, an OutOfMemoryErrorwill occur, and there’s typically nothing a client can do about it. Therefore, clients generally don’t worry about handling the subclasses of Error. In most cases, it’s the JVM itself that throws instances of Error or its subclasses. 10.1.2 The Method Invocation Stack The JVM uses a method invocation stack, also referred to as a call stack, to keep track of the succession of method invocations of each thread. The stack holds local information about each method that has been called, going all the way back to the original main( )method of the application. When each new method is invoked, a new stack frame is pushed onto the top of the stack, and the new method becomes the executing method. The local state of each method is also saved with each stack frame. Figure 10-2 illustrates an example Java call stack. Figure 10-2. An example of a Java method invocation stack
Searching for affordable and reliable webhost to host and run your web applications? Go to our java web server services and you will be pleased.

framework. The Struts framework, for example, underwent (Java web server) some

Saturday, July 28th, 2007

framework. The Struts framework, for example, underwent some significant changes to its APIs between Versions 1.0 and 1.1. In particular, the perform( )method is no longer the controller’s preferred method for invoking the Action; instead, it uses the execute( ) method. Fortunately, the developers working on the Struts framework were careful and ensured that the new functionality was compatible with applications built using earlier versions. You should take that same care when building your applications. If, for example, you override methods of the Struts framework to achieve specialized behavior, it’s not out of the realm of possibility that the method will be deprecated or removed in future Struts versions. In fact, several comments in the framework source indicate that certain portions of the Struts framework eventually will be retired. Although it’s nearly impossible to protect your application from all potential changes, it’s best that you go into developing it with your eyes wide open. Using a framework, even one that is as good and as complete as Struts, is not a silver bullet. You will have the same upgrade issues whether you build your own framework or use one provided by another source. Chapter 10. Exception Handling Throwing exceptions is Java’s way of informing dependent clients that something abnormal occurred during the processing of a method. The client is notified of the type of problem by an instance of a specific exception being thrown, and it’s entirely up to the client what course of action to take when an exception occurs. In some cases, the client may even choose not to take any action, which causes the JVM to continue to search for a handler for the exception. Handling exceptions within your Struts applications is not much different. When an abnormal condition occurs, an exception is thrown to the calling client to notify it of the abnormality. What is different for web applications, and specifically the Struts framework, is what action is taken on behalf of the client and how these exceptions are reported back to the end user. This chapter looks at how you can properly use the Java exception-handling mechanism within your Struts applications to help make your applications more robust and allow them to gracefully respond when things do not go as expected. Special attention is given to the differences between performing the exception handling programmatically and using the new declarative feature added to the Struts framework in Version 1.1. 10.1 Java Exception Handling Before we dive into how best to handle exceptions in the Struts framework, you should have a picture in your mind of what actually occurs when a method throws an exception. An understanding of the processes taking place in the JVM when an exception occurs may enlighten you as to the importance of throwing exceptions for the right reason, as well as the importance of throwing the right exceptions. Because there is additional overhead for the JVM to handle an exception, you should always take care to use exceptions correctly. 10.1.1 Java Exceptions In Java, exceptions are objects that are created when an abnormal condition, often referred to as an exception condition, occurs during the execution of an application. When a Java application throws an exception, it creates an object that is a descendant of java.lang.Throwable. The Throwable class has two direct subclasses: java.lang.Errorand java.lang.Exception. Figure 10-1 shows a partial hierarchy tree for the Throwableclass.
If you are in need for chaep and reliable webhost to host your website, our recommendation is http web server services.

public UserView getUserView( ) { return userView; (Web design seattle) }

Saturday, July 28th, 2007

public UserView getUserView( ) { return userView; } public void setUserView(UserView newView) { userView = newView; } /** * Initialize all of the required resources */ private void initialize( ) { // Create a new shopping cart for this user cart = new ShoppingCart( ); } /** * Clean up any open resources. The shopping cart is leftintact * intentionally. */ public void cleanUp( ) { setUserView( null ); } } One thing to notice is that the UserContainer class in Example 9-5 implements the HttpSessionBindingListener interface. The methods of this interface allow the UserContainer to be notified when it is bound to and unbound from the session. This allows it to perform any necessary cleanup on the object. An instance of the UserContainer is created for each new user at the time the user enters the application. The UserContainer object itself is stored in the session, and it must have the duration of the session. If the user exits and re-enters the site, a new UserContainer typically is created for that user. The ApplicationContainer is used for a similar purpose, but at the application level, not the session level. It’s useful for storing or caching information that is needed by all users across the application. Things such as selection lists, configuration properties, and other non-client-specific data that you need to get once and hold on to are candidates for the ApplicationContainer class. This class is created when the application is first started and destroyed when the application exits. 9.6 Downsides to Extending the Framework There are a few downsides to customizing or extending a framework. Although I’ve suggested that customization is a forecasted goal of using a framework, as with other things in software development, there are trade-offs. When extending a framework, one of the biggest issues that you may face is what to do when newer versions of the framework are made available. Unless the framework developers paid careful attention to backward compatibility, your application may no longer work correctly with a newer version of the
We recommend cheap and reliable webhost to host and run your web applications: Coldfusion Web Hosting services.

* The Locale object for the user. Although (Dedicated web hosting)

Friday, July 27th, 2007

* The Locale object for the user. Although Struts stores aLocale for * each user in the session, the locale is also maintainedhere. */ private Locale locale; public UserContainer( ) { super( ); initialize( ); } public ShoppingCart getCart( ) { return cart; } public void setCart(ShoppingCart newCart) { cart = newCart; } public void setLocale(Locale aLocale) { locale = aLocale; } public Locale getLocale( ) { return locale; } /** * The container calls this method when it is being unboundfrom the * session. */ public void valueUnbound(HttpSessionBindingEvent event) { // Perform resource cleanupcleanUp( ); } /** * The container calls this method when it is being bound tothe * session. */ public void valueBound(HttpSessionBindingEvent event) { // Don’t need to do anything, but still have to implementthe // interface method. }
Please visit Domain Name Hosting services for high quality webhost to host and run your jsp applications.

One of the problems with storing data in (Web hosting account)

Friday, July 27th, 2007

One of the problems with storing data in the HttpSession is that the interface to store and retrieve data from the session object is not strongly typed. In other words, the interface for any data is: public void setAttribute( “permissionsKey”, permissions ); public Object getAttribute( “permissionsKey” ); The client must be aware of the key at which the data is stored in order to put an object into or retrieve an object from storage. Some programmers prefer a more strongly typed interface instead: userContainer.setPermissions( permissions ); userContainer.getPermissions( ); Here, the client doesn’t have to worry about what key the object is being stored under or how it’s being stored. It can be an HttpSession object or some other data store; the client is not made aware of this because it’s not forced to use the methods of the HttpSession directly. There’s nothing really complicated about the UserContainer class itself. It’s an ordinary JavaBean that contains instance variables, along with public getters and setters for the properties. Example 9-5 illustrates a basic UserContainer class. Example 9-5. A basic UserContainer class package com.oreilly.struts.storefront.framework; import java.util.Locale; import javax.servlet.http.HttpSessionBindingListener; import javax.servlet.http.HttpSessionBindingEvent; import com.oreilly.struts.storefront.customer.view.UserView; /** * Used to store information about a specific user. This classis used * so that the information is not scattered throughout theHttpSession. * Only this object is stored in the session for the user. This class * implements the HttpSessionBindingListener interface so thatit can * be notified of session timeout and perform the propercleanup. */ public class UserContainer implementsHttpSessionBindingListener { // The user’s shopping cart private ShoppingCart cart = null; // Data about the user that is cached private UserView userView = null; /**
Go visit our java server pages services for a reliable, lowcost webhost to satisfy all your needs.

the executeAction( )method. Each subclass implements the abstract (Web design software)

Friday, July 27th, 2007

the executeAction( )method. Each subclass implements the abstract executeAction( ) method and has the UserContainer passed in, instantiated, and guaranteed not to be null. This is only a trivial example of what you can do. Any behavior that all actions need to perform is a candidate for being implemented in the Action superclass, so that when the time comes to modify the implementation, only the behavior in the superclass needs to change. 9.4 Extending View Components There generally is less reason or need to extend components located within the view layer than there is to extend components in the controller layer. Typically, views are written exclusively for an application; for example, it’s unlikely that a JSP page written for one application will be used within a different application. This is not always the case, but differences between look-and-feel and content make such reuse improbable. The one area within the Struts view layer where extensions often are created, however, is in the JSP tag libraries. 9.4.1 Extending Struts Custom Tags The custom tags provided by the Struts framework can be reused across applications and application domains. Therefore, it makes sense that customization and extensions are more likely with these components than with JSP pages. Because the tag handlers are regular Java classes, specialization is achieved through subclassing. Although you can extend any tag, the HTML tag library is the one that you’ll most likely need to customize (mainly because the custom tags within this library have the greatest impact on the view content). Regardless of which tags you extend, you’ll need to create your own tag library to hold your tag extensions. You could modify the Struts tag libraries and include your new tag class, but that would make upgrading to newer versions of the Struts framework much harder. You’re better off creating your own tag library that contains just your application’s tags. Once you’ve created a .tld file for your extensions and registered it with the web application deployment descriptor, you are free to use your tags just as you would any others. 9.5 Extending Model Components Because the Struts framework doesn’t provide a great deal of components for the model layer, extensions to these components are better discussed in other Java programming books. However, there are two classes that might be placed into the category of extensible model components. They aren’t the best representations of what a model component is, but they are responsible for holding model state. 9.5.1 The UserContainer and ApplicationContainer Classes I’ve mentioned the UserContainerand ApplicationContainer classes in previous chapters without defining exactly what they are. These two classes are not part of the Struts framework I created them as part of the example Storefront application. The purpose of these classes is to store user and application-specific information in instances of these classes, rather than in the HttpSessionand ServletContext objects, respectively.
We would like to recommend you tested and proved virtual web hosting services, which you will surely find to be of great quality.