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...
Multilingual Support
Most of us cringe at the thought of supporting user groups that are in one of several possible locales. In many cases, however, once an application has been installed and localized, it's like any other single-locale application. The users that access the application are either all from the same locale or are from locales similar enough that the language and cultural differences are insignificant. Multilingual applications, on the other hand, take internationalization to the next level by...
The UserContainer and ApplicationContainer Classes
I've mentioned the UserContainer and 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 HttpSession and ServletContext objects, respectively. One of the problems with storing data in the HttpSession is that the...
Figure Login screen for the online banking application
If the proper credentials are entered for an account, the user is taken to the account information screen. This screen shows all of the accounts that the user has with the financial institution, as well as the current balance for each account. For this example, we are not going to provide a robust, full-fledged security service and security realm. Handling security in a web application can be complicated, and there's no reason to muddy the waters with it at the moment. For the purposes of this...
Example The LoginAction class from the Storefront application
package import java.util.Locale import javax.servlet.http. import org.apache.struts.action. on import import Implements the logic to authenticate a user for the Storefront application. public class LoginAction extends StorefrontBaseAction Called by the controller when the user attempts to log in to the public ActionForward execute ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response The email and password should have already been validated by the...
Creating an Event Listener
The steps for creating an event listener are similar to those of creating filters. There are three primary steps to perform 1. Create a Java class that implements the event-listener interface for which you are interested in receiving events. This class must contain a no-argument constructor. 2. Declare the event listener in the web application deployment descriptor using the listener element. 3. Package the event listener class along with the rest of the web application resources. 15.2.4.1...
The globalforwards element
Every action that is executed finishes by forwarding or redirecting to a view. This view is a JSP page or static HTML page, but might be another type of resource. Instead of referring to the view directly, the Struts framework uses the concept of a forward to associate a logical name with the resource. So, instead of referring to login.jsp directly, a Struts application may refer to this resource as the login forward, for example. The global-forwards section allows you to configure forwards...
Using the synchronized Keyword
Synchronization is used to control the access of multiple threads to a shared resource. There are many situations where synchronization makes sense and is absolutely necessary to keep multiple threads from interfering with one another, which can lead to significant application errors. Struts applications are inherently multithreaded, and you might think that certain parts of the web application should be synchronized. However, using the synchronized keyword inside of your Struts applications...
The globalexceptions element
The global-exceptions section allows you to configure exception handlers declaratively. The global-exceptions element can contain zero or more exception elements lt ELEMENT global-exceptions exception gt Later in this chapter, when action mappings are discussed, you will see that the exception element also can be specified in the action element. If an exception element is configured for the same type of exception both in the global-exceptions element and in the action element, the action level...
Using Programmatic Exception Handling
The alternate approach to the declarative exception handling provided by Struts is to build the application-specific exception handling into the code itself. This means that you will have to extend the framework with behavior specific to your application. As mentioned earlier in this chapter, there are two basic courses of action when an exception is thrown within an Action class. If the exception is an application exception, the course of action is to log the exception, create and store an...
Creating Multithreaded Action Classes
A single Action instance is created for each Action class in the framework. Every client request will share the same instance, just as every client request shares the same ActionServlet instance. Thus, as with servlets, you must ensure that your Action classes operate properly in a multithreaded environment. To be thread-safe, it's important that your Action classes do not use instance variables to hold client-specific state. You may use instance variables to hold state information it just...
Using Event Listeners
Web application event listeners are Java classes that implement one or more of the servlet event-listener interfaces. Event listeners support event notifications for changes in state in the ServletContext and HttpSession objects. Event listeners that are bound to the ServletContext support changes at the application level, while those that are bound to the HttpSession objects are notified for state changes at the session level. Multiple listeners can be set up for each event type, and the...
Stateless Session Bean Implementation
Without getting into anything too elaborate, we next want to come up with an implementation of our session fa ade. We'll make a few decisions here to simplify things, but the result will be all we need to illustrate how to interface the web and application tiers. It will also be good enough for you to deploy in an EJB container and use to test your Struts interface. If you were given the task of implementing the application tier of the Storefront application using EJB, you probably would...
Performing Validation with the DynaActionForm
The DynaActionForm doesn't provide any default behavior for the validate method. Unless you subclass the DynaActionForm class and override the validate method, there's no easy way to validate using the DynaActionForm. Fortunately, the framework comes to your aid again with a feature called the Struts Validator. The Struts Validator was created by David Winterfeldt and is now in the main Struts distribution. The Validator is a framework that was intended to work with Struts from the beginning....
Example Using Commons Logging in a JSP page
lt -- Get a reference to the logger for this class -- gt lt Log logger LogFactory.getLog this.getClass gt lt logger.debug This is a debug message from a jsp gt lt title gt Using Commons Logging in a JSP page lt title gt lt head gt lt logger.info This is another log message in the jsp There should be two log messages in the log file. lt body gt lt html gt You must have the Commons Logging environment configured properly for this to work, just as when using it in the Java classes. Any JSP page...
Example ServletContextListener interface
import javax.servlet.ServletContext import javax.servlet.ServletContextEvent import javax.servlet.ServletContextListener initializes a logging service. LoggingListener implements ServletContextListener private ServletContext context null Called by the container before the first request is processed. This is a good time to initialize public void contextInitialized ServletContextEvent event this.context event.getServletContext Initialize the logging service here Log a message that the listener...
The Business Delegate and DAO Patterns in Action
The final piece of the puzzle is to create a service interface that the Storefront Action classes can use instead of interacting with the persistence framework directly. Again, the idea is to decouple the persistence from as much of the application as possible. Before we show the details of how we are going to accomplish this for the Storefront example, we need to briefly discuss the Data Access Object DAO pattern. The purpose of the DAO pattern is to decouple the business logic of an...
The Data Transfer Object pattern
Chapter 6 discussed one approach to building the model components for a Struts application. The one thing that was intentionally left out was exactly how the view accesses the data from the model. To understand this, it will help to understand the Data Transfer Object DTO pattern sometimes referred to as the Value Object or Replicate Object pattern . The DTO pattern is used quite frequently in J2EE applications, where distributed components making remote calls can suffer serious performance...
Example Determining the users locale information in a servlet
import javax.servlet.http.HttpServletResponse Prints out information about a user's preferred locales public class LocaleServlet extends HttpServlet private static final String CONTENT_TYPE text html public void init ServletConfig config throws ServletException public void doGet HttpServletRequest request, HttpServletResponse response throws ServletException, IOException response.setContentType CONTENT_TYPE PrintWriter out response.getWriter Example Locale Retrieve and print out the user's...
Modifying the validationrulesxml File
In the earlier section Section 11.4, you saw how to extend the Validator framework with your own customized rules. You'll have to do this here as well, but the method signatures will be different. The method signature in Example 11-3 included parameters that are part of the Servlet and Struts APIs. You will need to use different arguments to keep from being coupled to the Servlet API or the Struts framework. First, the methodParams attribute needs to be modified to support the alternate...
Example Using the Validator outside of Struts
import java.util. import java.io. private final static String RESOURCE_DELIM , protected ValidatorResources resources null private String pathnames null public ValidatorLoader throws IOException loadPathnames initResources public ValidatorResources getResources return resources public String getPathnames return pathnames public void setPathnames String pathnames this.pathnames pathnames protected void loadPathnames Set a default just in case String paths InputStream stream null Load some...
Example The ActionServlet process method
protected void process HttpServletRequest request,HttpServletResponse response throws IOException, ServletException RequestUtils.selectApplication request, getServletContext getApplicationConfig request .getProcessor .process requ The process method might not look complicated, but the methods invoked within it are. First, the static selectApplication method in the org.apache.struts.util.RequestUtils class is called and passed the current request and the ServletContext for the web application....
Maverick
The Maverick MVC framework offers the ability to render views using JSP, the Velocity scripting language, or XSLT. Maverick is an MVC-type architecture, but it actually provides a view template mechanism. One neat feature of Maverick is that it can use reflection on JavaBeans in the presentation layer to create a DOM interface, so no XML generation or parsing is required. This allows for a little less clutter and probably better performance when using XSLT to generate the views. You can find...
Example Dynamic proxy implementation of the Storefront service
package import java.lang.reflect. import java.rmi.RemoteException import java.util. import javax.ejb.CreateException import javax.naming. import javax.rmi.PortableRemoteObject import import import This class is a dynamic proxy implementation of the IStorefrontService interface. It implements two of the IStorefrontService methods itself and delegates the others to the methods declared by the IStorefront business interface with the same name. public class DynamicStorefrontEJBDelegate implements...
The Client Tier
The client tier provides a way for users to interact with the application. This interaction may be through a web browser, or it may be programmatic, through a web services interface. Regardless of the type of client, the interaction includes submitting a request and receiving some type of response from the middle tier. In the case of the Struts framework, the most common type of client is a web browser. However, it is also possible to have clients such as wireless devices and Java applets.
Example The UserView DTO
package Mutable data representing a user of the system. public class UserView extends BaseView private String lastName private String firstName private String emailAddress private String creditStatus public String getFirstName return firstName public void setFirstName String firstName this.firstName firstName public void setLastName String lastName this.lastName lastName public String getEmailAddress return emailAddress public void setEmailAddress String emailAddress this.emailAddress...
Barracuda
The Barracuda presentation framework is a type of Model 2 architecture similar to Struts, but it goes a step further and provides a model event-notification mechanism. Unlike a strictly JSP approach, the Barracuda framework has created a template engine component, which is supposed to allow for more flexibility and extensibility. The framework leverages code-content separation provided by the XMLC approach of creating user interfaces. XMLC is a Java-based compiler that uses either an HTML or...
Organization
This book begins with a preliminary discussion that lays the groundwork for the rest of the material. This discussion will be a refresher for some and completely new for others. From there, we explore the components of Struts's MVC implementation, including a look at the JSP custom tags that are included as part of the framework. Then, to round out your understanding of the value of the Struts framework, we look at several complicated but important topics related to building web-based...
Example Using the Log tag library to dump information
lt taglib uri WEB-INF log.tld prefix logger gt lt title gt Using the Log Tag in a JSP page lt title gt lt head gt lt logger dump scope page gt lt logger dump scope request gt scope scope session gt application gt The page, request, session, and application dumps should be in the log file. Unfortunately, the Log tag doesn't yet work with the Commons Logging package. It depends on the log4j implementation. Still, it's a valuable tag if you need to provide additional debugging in your JSP pages.
Example The shoppingcart functionality is put into a single DispatchAction
package import java.io.IOException import java.text.Format import java.text.NumberFormat import java.util. import javax.servlet.ServletException import import import import import import import Implements all of the functionality for the shopping cart. public class ShoppingCartActions extends This method just forwards to the success state, which should represent the shoppingcart.jsp page. public ActionForward view ActionMapping mapping, ActionForm form, HttpServletRequest request,...
Example The LoginAction used by the banking application
package com.oreilly.struts.banking.action import import import javax.servlet.http.HttpSession import org.apache.struts.action.Action import import import import import import import This Action is called by the ActionServlet when a login attempt is made by the user. The ActionForm should be an instance of a LoginForm and contain the credentials needed by the SecurityService. public class LoginAction extends Action public ActionForward execute ActionMapping mapping, ActionForm form,...
Example The security service used by the example banking application
package com.oreilly.struts.banking.service Used by the example banking application to simulate a security service. public class SecurityService implements IAuthentication public UserView login String accessNumber, String pin throws InvalidLoginException A real security service would check the login against a security realm. This example is hardcoded to let in only 123 456. if 123.equals accessNumber amp amp 456.equals pin Dummy a UserView for this example. This data object would typically come...
Example Customized RequestProcessor that overrides the default Locale processing
package com.oreilly.struts.framework import javax.servlet.http. import java.util.Locale import org.apache.struts.action.Action import A customized RequestProcessor that checks the user's preferred locale from the request each time. If a Locale is not in the session or the one in the session doesn't match the request, the Locale in the request is set in the session. public class CustomRequestProcessor extends RequestProcessor protected void processLocale HttpServletRequest request, Are we...
Example The Struts ActionServlet can be extended to perform custom
package import javax.servlet.ServletException import javax.servlet.UnavailableException import org.apache.struts.action.ActionServlet import import import import Extend the Struts ActionServlet to perform your own special public class ExtendedActionServlet extends ActionServlet public void init throws ServletException Make sure to always call the super's init first super.init Initialize the persistence service try Create an instance of the service interface IStorefrontService serviceImpl new...
Example A business delegate for the Storefront session bean
package import java.rmi.RemoteException import java.util.Hashtable import java.util.List import javax.ejb.CreateException import javax.naming.Context import javax.naming.InitialContext import javax.naming.NamingException import javax.rmi.PortableRemoteObject import import This class is a business delegate that supports the implementation of the IStorefrontService interface using the Storefront session bean. public class StorefrontEJBDelegate implements IStorefrontService public...
Example A partial webxml file that illustrates how to configure multiple
lt servlet- lt init-param gt lt init-param gt lt init-param gt lt init-param gt lt servlet gt Notice that the param-name value for the nondefault application module in Example 4-6 begins with config . All nondefault application modules' param-name elements must begin with config the default application's param-name element contains the config value alone. The part that comes after config is known as the application module prefix and is used throughout the framework for intercepting requests...
Example Creating ActionErrors from the execute method
public ActionForward execute ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response Get the user's email and password, which should already have been validated by the ActionForm. String email LoginForm form .getEmail String password LoginForm form .getPassword Log in through the security service IStorefrontService servicelmpl getStorefrontService userView serviceImpl.authenticate email, password catch InvalidLoginException ex ActionErrors errors new...
Example The resource bundle for the banking application
label.accessnumber Access Number label.pinnumber Pin Number label.accounts Accounts label.balance Balance label.totalassets Total Assets label.account Account label.balance Available Balance label.description Description label.amount Amount label.deposits Deposits label.withdrawls Withdrawls label.openingbalance Opening Balance link.customeragreement Customer Agreement link.viewaccountdetail View Account Detail title.login Struts Online Banking - Account Login title.accountinfo Struts Online...
Example The processActionPerform method
request, HttpServletResponse response, Action action, ActionForm form, ActionMapping throws IOException, ServletException try return action.execute mapping, form, request, response return processException request, response, e, form, The processActionPerform method is responsible for calling the execute method on the Action instance. In earlier versions of the Struts framework, the Action class contained only a perform method. The perform method has been deprecated in favor of the execute...
Freemarker Velocity and WebMacro
These three products are grouped together because they all represent similar types of template engines. Freemarker is an open source HTML template engine for Java servlets. With Freemarker, you store the HTML in templates, which eventually get compiled into template objects. These template objects then generate HTML dynamically, using data provided by servlets. Freemarker uses its own template language and claims speeds approaching those of static HTML pages. The software is free and licensed...
Alternatives to Struts
Before we get too far into our discussion of the Struts framework, this section will briefly introduce some alternatives to Struts. Because versions and features may change with each new release, you should conduct your own research. This list of alternatives is by no means exhaustive, but it will provide you with a launching pad. I could have saved this section for the end of the book, but I wanted to familiarize you with some other frameworks so that you can compare them with Struts as you...



