Wrapping it up in finally
What happens if you absolutely, positively have to do something regardless of whether or not an exception is thrown You can use a third block for that purpose called the finally block, which can be used only in the try catch block. The finally block is guaranteed to always execute regardless of whether or not an exception was thrown. To see how you might use the finally block, suppose that you're performing some database operation in the try block that throws a SQLException. Before making the...
Step Defining the realms
The second step is to define a realm in the Web container's server.xml file. A realm identifies a set of users, their passwords, and their associated roles. Four types of realms are possible, depending on how you set up your user information I UserDatabaseRealm The simplest but least flexible and secure choice. In this scenario, usernames, passwords, and roles are kept in a static file that is loaded into the Web container's memory at startup. For Tomcat, this file defaults to tomcat-users.xml....
Table of Contents
About This How to Use This Book Foolish Assumptions Conventions Used in This Book How This Book Is Part I Getting to Know Jakarta Struts Part II Starting from the Part III Expanding Your Development Options 4 Part IV Putting It All Part V The Part of Part VI Icons Used in This Where to Go from Part I Getting to Know Jakarta Struts 7 Chapter 1 Starting with the Basics 9 What Is Jakarta Struts Structuring a Web Application Using Java Creating JavaServer Pages Using JavaBeans Understanding the...
Notifying Users of Problems
Whether validating a form or testing logical operations, you need a common way to notify the user of the problem when an error arises. ActionError and ActionErrors are Struts classes created for that purpose. ActionError is a subclass of ActionMessage that holds an error message that will be returned to the user. You specify the message by using a key of a message resource. If the message is parameterized, you can add the values for the parameters to ActionError. A message can have up to four...
Implicit Objects
The EL engine has numerous objects available that you can use in expressions to retrieve values. You reference the implicit objects by name. Here are their names and descriptions l pageContext The PageContext object l pageScope A Map object that maps page-scoped attributes to their values I requestScope A Map object that maps request-scoped attributes to their values I sessionScope A Map object that maps session-scoped attributes to their values I applicationScope A Map object that maps...
Icons Used in This Book
If you see little pictures in the margins, you've found an icon. Icons highlight special information in the text and let you know if you need to look more carefully or if you can just skip to more important parts. This icon alerts you to information that you need to keep in mind to avoid wasting time or falling on your face. Jakarta Struts has some advanced features you may want to know about or not. This icon lets you know when we get into some heavy details Tips help you complete a task more...
Trycatch block
In a try catch block, the try block contains the code that may throw a checked exception. The catch block contains the reference to the exception that could be thrown. The catch block contains also the code that reacts to the exception. Here is an example of a simple try catch block some code that could throw the ExceptionType If your code in the try block performs some action that causes an exception to be thrown, control moves immediately to the code in the catch block. You're not required to...
Working with MySQL
So far in this chapter, we've explained how to install a database server and add some class libraries to your project. These steps are necessary but by themselves don't change anything. Before your Web application can connect to your database, you need to do the following 3. Put some data into the table. In this section, we use MySQL to explain how to do the following 1 Start the MySQL database server t Create a database called musiccollection 1 Create a table called users 1 Insert three...
Formatting library
The tags available in the Formatting library, especially the internationalization tags, provide the page author with a simple mechanism to internationalize the page. The prefix used for the Formatting library is most commonly fmt. We discuss I18N issues in Chapters 3 and 6, so we won't discuss them in detail here. The six tags in the internationalization grouping deal explicitly with I18N issues. These tags use Locales and Resource Bundles to do their work, as we discuss in Chapter 6 i lt fmt...
Listing Defining the Title loggedinTitlejsp
lt include file taglibs.jsp gt lt fmt setBundle gt lt fmt message key loggedin.title gt To make use of the Tiles configuration file, you need to adjust the Struts configuration a little bit by adding a new plug-in. The TilesPlugin processes definitions in a centralized file. In its simplest form, the TilesPlugin takes no parameters. The plug-in assumes that the Tiles configuration XML file is named tileDefinitions.xml. Here is the line to add to the struts-config.xml file After you decide to...
About This Book
As if you didn't know, Jakarta Struts For Dummies covers Jakarta Struts, the popular, open-source framework for creating Web applications in Java. We comprehensively explain the features in Jakarta Struts, including the following How Jakarta Struts structures Web application code into three groups Model, View, and Controller and how this helps make your code easier to write and maintain How Struts works with a Web container, JavaServer Pages, and Java servlets Integrating Struts into a Web...
Adding helper classes
In addition to defining business objects that represent real-world entities, you need to create additional classes, called helper classes. These classes perform the various business functions in the Model layer. Helper classes are implementations of objects that you add during the design phase. These classes do not directly represent real-world concepts that business people can relate to. Their purpose is to improve the flexibility and structure of the programming code. Some examples of helper...
Step Specifying authorization areas
The third step in the process is to declare the areas in the application that you want to protect by modifying the application's web.xml file. When using Struts applications, you can make these declarations in two areas in the struts-config.xml file to protect Struts actions and in the web.xml file to protect other resources, such as JSP, HTML, and image files. Struts use of user roles for authorization You can protect a Struts Action in the container-based security scheme using the roles...
Meeting requirements for business objects
Sun Microsystems has defined a set of guidelines for developing enterprise architectures with Java called the J2EE Blueprints java.sun.com blueprints . The Enterprise JavaBeans EJB technology, which is an ideal platform for implementing business objects, addresses all of Sun's requirements. However, not all Web applications are complex enough to justify the investment in expertise and money to include an EJB application server. EJB is definitely worth investigating further, however, if you plan...
Asserting Yourself
Another form of defensive programming is the use of assertions. Assertions can be characterized as lazy exceptions, in the sense that an assertion behaves somewhat like an exception yet takes a lot less code on the part of the programmer. The following example clarifies this technique. Suppose that you've written a method that gets a reference to a poList object and then uses the reference to update information in the list do something here to get a reference to a poList object assert that we...
Retrieving multiple records
LoginBean, in line 27 of Listing 5-1, accesses ResultSet but does not retrieve any data. In that case it was not necessary because the users table doesn't provide any other fields than the ones we're using in the query. In Listing 5-2, we add another method called getAllUsers to the LoginBean class to demonstrate how you can retrieve data from ResultSet and pass it back to the View. We also wanted two more fields age and status to add more personal information about the user. If you want to...
Configuring the Validator plugin in the config file
The next step in setting up the Validator plug-in is to configure the plug-in in the struts-config.xml file. The configuration is just like the previous plugin definition see the Configuring Plug-ins section with one addition you need to add one parameter to pass to the plug-in. The Validator needs to know the context-relative paths so it can find the validation.xml and validator-rules.xml configuration files. You typically place these files in the WEB-INF folder. Here is the configuration...
Declaring Security in Your Web Container
The J2EE specification defines a declarative security mechanism in which application security is expressed in a declarative syntax in the configuration files. Using declarative security, Web containers can provide both authentication and authorization services for Web applications running in the Web container. You can use these services with Struts applications. Four basic steps need to happen for the container's declarative security to work. We discuss each of these steps in detail in this...
The ServletContext configuration tag
Each Web container provides an implementation of the ServletContext interface for each Web application running in the Web container. Any servlet can reference the ServletContext object, which can store and reference objects by any servlet in the application. The ServletContext has a lifetime as long as the application is running. Store in the ServletContext any data elements that need to be available on a global basis for the life of the application. The tag for inserting values into the...
Configuring the Validator plugin
The Validator requires two xml configuration files validation.xml and validator-rules.xml. You might think that the validation.xml file is more interesting because that is where you define the forms and fields to validate as well as the rules to use when validating those fields. The actual rules that perform the validation are defined in validator-rules.xml. The validation.xml and validator-rules.xml files share the same DTD. For details on DTD, see Editing the Web Container Configuration File...
Implementing and Configuring Your Own Plugin
You can create your own plug-in simply by implementing the destroy and i nit methods of the PlugIn interface. Listing 9-2 shows an example of how to implement a plug-in for the MusicCollection Web application in Chapter 14. Don't worry if you don't understand what's happening in the two methods, because they're specific to this particular application. What is important to know is that i nit is called at startup and destroy is called at shutdown. Listing 9-2 Plug-in for a Purchase Order Web...
Customizing the RequestProcessor Class
For larger Web applications, another approach is to centralize the authentication process in one class. The RequestProcessor class is one of the key classes in the Controller layer. For more information about the RequestProcessor class, see Processing Requests in Chapter 4. This class handles all requests for the Struts application and is therefore an ideal location to place an authentication function. The Struts developers must have had this use in mind when they added an extension point a...
Listing Simplified JSP Using includes
- begin the taglib definitions -- gt include file taglibs.jsp gt 4 lt html html locale true gt lt -- begin the header for the application -- gt lt title gt lt fmt message lt -- begin the logo for the application -- gt lt c import url logo.jsp gt lt fmt message key loggedin.msg gt lt fmt param value ' requestScope.userName ' gt lt -- begin the footer for the application -- gt lt c import url footer.jsp gt You can use includes to refactor all the JSP pages in the application that have a similar...
Formbean configuration
You need to define the formbean in the struts-config file. We also discussed formbeans extensively in Chapters 3 and 6. The tag for inserting formbeans is lt form-beans gt . The DTD syntax for the tag follows The tag for inserting formbeans is lt form-beans gt . The DTD syntax for the tag follows lt ELEMENT form-bean icon , display-name , description , lt ELEMENT form-bean icon , display-name , description , ATTLIST ATTLIST ATTLIST ATTLIST form-bean form-bean form-bean form-bean , form-property...
Configuring the formbean
Listing 6-2 contains the configuration file for the example Login application. For more information on this application, see Chapter 3, where we discuss how to configure formbeans in the struts-config file. In this section, we explain the file from the angle of how it mediates between the View and the Controller. 1 lt xml version 1.0 encoding ISO-8859-1 gt 2 lt DOCTYPE struts-config PUBLIC 3 - Apache Software Foundation DTD Struts Configuration 1.1 EN 5 lt -- This is the Struts configuration...
The loggedinjsp page
The loggedin.jsp page is just a validation to the user that the system has accepted the username and password combination. This page is even simpler that the login.jsp page. The only interesting feature of the page is the insertion of the user's name in the welcome message. Figure 3-10 shows what the page looks like when displayed. The complete listing for loggedin.jsp is shown in Listing 3-2. 1 lt page language java gt 2 lt -- JSTL tag libs -- gt 3 lt taglib prefix fmt uri WEB-INF fmt.tld gt 4...
Global exceptions
You need to declare any global exceptions in the struts-config file. In this section, we discuss how to set up the configuration for global exceptions. For a full discussion of the ins and outs of declarative exception handling, see Chapter 8. The tag for inserting global exceptions is lt global-exceptions gt . The DTD syntax for the tag is ELEMENT global-exceptions exception gt lt ELEMENT exception icon , display-name , description , ATTLIST ATTLIST ATTLIST ATTLIST ATTLIST ATTLIST ATTLIST You...
Creating the project in Eclipse
When you start to create a program, the first task is to create a project. Creating a project specifies the folder that contains all the files for your Web application. To create a project, follow these steps For information on starting Eclipse, see Downloading and Installing Eclipse in Chapter 2. If you're using a different development environment, look at the end of this section for instructions on how the final application structure should look. 2. To set up the most appropriate display in...
Examples of declaring authorization and authentication
To integrate the information in this chapter, this section provides two examples of authorization and authentication. Protecting the entire application with BASIC authentication In the first example, we assume that every page of the application is protected from all users, except those who have the role of admin. We use the BASIC form of authentication, letting the browser display the login form. Here is the code snippet from web.xml lt web-resource-collection gt lt web-resource-name gt All of...
Importing the Struts files
At this point you need to bring the Struts files into your project structure. In this phase, you do the following i Import all the library files into the WEB-INF lib folder. i Import the tag library description files into the WEB-INF f older. You don't absolutely have to import these files, because you're going to inform Eclipse about the files in a different but related step. However, having the parts to your Web application in the proper folder structure makes it easier to deploy the...
Listing JDBCRealm Definition for MySQL in serverxml
roleNameCol role_name gt Note the following lines from Listing 12-2 Note the following lines from Listing 12-2 i Line 1 Specifies the fully qualified class name of the realm that we're defining in this case, JDBCRealm. i Line 2 Sets the debug level to the lowest possible setting. i Lines 3 and 4 Specify the database driver and connection URL, respectively. i Lines 5 and 6 Specify the username and password used to connect to the database. i Line 7 Names the table that contains the username and...
Generalpurpose tags
The general-purpose tags consists of four tags that you use to manipulate scoped variables variables that exist in one of the four scopes page, request, session, or application . They are i lt c out gt The out tag evaluates an expression and outputs the result to the current JSPWriter responsible for writing out the page contents . The following example outputs the value of the vendorName property found in the po object stored in the session The vendor is lt c out i lt c set gt The set tag sets...
Configuring Tiles
You need to attend to a few configuration issues to use the Tiles framework with Struts. The Tiles library is already included in the Struts framework, so that is one less thing to worry about. But you do need to perform the following steps 1. Put the tiles TLD file struts-tiles.tld in with all the other TLD files, usually in the WEB-INF folder. You can find this file in the tiles-documentation.war file that comes with the Struts 1.1 distribution. 2. Update the web.xml file to include a...
Using Tag Libraries
You need to follow several generic steps to take to make use of any tag library. These steps are as follows 1. Move the TLD file for the library into the WEB-INF folder. You could place the TLD file into any folder in the Web application's folder. However, most users place it in the WEB-INF folder. 2. Move the library's JAR file into the WEB-INF lib folder. 3. Define the tag library in the web.xml file. To define the tag library, use the JSP directive tag lt taglib-uri gt could be any distinct...
ActionSerVlet configuration
In a Struts application, you always have at least one servlet to declare and possibly others. The servlet definition section of web.xml allows you to define many of the key features of the servlet, in particular the fully qualified class name and how the servlet will be referenced. The tag that defines a servlet is lt servlet gt . The syntax for the tag is lt ELEMENT servlet icon , servlet-name, display-name , description , servlet-class jsp-file , i nit-param , load-on-startup , run-as ,...
Working with the Controllers Helper RequestProcessor
We've all seen work sites where a bunch of people are digging a ditch. One person is standing around watching and making a few comments, while the others are down in the hole feverishly digging with their shovels. That's the relationship between ActionServlet and RequestProcessor. Action Servlet tells RequestProcessor, dig here, and RequestProcessor does most of the work. ActionServlet calls the RequestProcessor's process method to handle the incoming request. The process method then performs a...
XML tools
The advantage of an XML document is that you can use XSL stylesheets to transform the document into virtually any other type of document for presentation. This transformation process is advantageous for sites that need to offer many forms of display to the user. For example, you may want to let the user view a purchase order in HTML, PDF, or plain text. This section describes two tools that integrate with Struts to provide XML and XSL services. The StrutsCX framework replaces JSP with XSLT...
Using Commons Logging
Fortunately, Struts provides the developer with a lot of flexibility when it comes to logging through the inclusion of the Commons Logging library another of the many Jakarta projects in the Struts library files. Commons Logging is a lightweight framework that provides a common logging interface to any one of the many actual logging packages, such as Log4J and Java 1.4. This common interface enables you, the developer, to pick and choose the logging package that you want to use without having...
Connecting the Model to the Database
In Chapter 3, for simplicity, we used an example of a JavaBean containing hard-coded data. Hard-coding data is not a useful way to implement a Web application or any application for that matter. To make the Login application practical, you need to add a persistent data repository a database and make LoginBean work with that database. To upgrade the Login application, you need to implement a new version of the LoginBean. The View and Controller components of this application do not have to...
Using Java Logging
By default, the configuration file for Java 1.4 logging is logging.properties in the JRE lib directory. You can use an alternative means of reading the configuration file by specifying the file location and name in the java.util. logging.config.file system property. Look at the Java API documentation for the java.util.logging.LogManager class for further information on logging configuration. You can set the following features in the configuration file 1 The priority level to log messages. INFO...
Jakarta Commons DBCP
The Jakarta Commons DBCP database connection pooling project provides an implementation of the JDBC 2.0 connection pool specification. Jakarta Commons DBCP is built on another project, the Jakarta Commons Pool. The Jakarta Commons Pool implements a general object pooling mechanism that can pool any kind of object. Commons DBCP reuses this generalized object pooling implementation to provide a data source connection pooling mechanism. Each project has its respective home page, where you can find...
Using message resources
Message resources are a means to separate text from the application's code. Keeping the text separate from the code makes it easier to change the text later, which makes the application easier to maintain. One of the key mechanisms to handle I18N is to put any text that will be displayed for the user into a message resource file. The format for this file is simply a set of key-value pairs, where the key is used as the reference and the value is what is displayed. For example In this example,...
Using the Validator with DynaActionForms
If you're using DynaActionForms instead of ActionForms, you can still use the Validator. However, you need to make the following changes 1. When you define DynaActionForm in the struts-config.xml file, the type attribute should be org.apache.struts.validator. DynaValidatorForm instead of the standard org.apache.struts. action.DynaActionForm. 2. Make sure that the form fields referenced in the validation.xml file match the form-property names defined for the form in question.
Configuring the DynaActionForm class
Configuring a DynaActionForm is not much different from configuring a regular ActionForm. The definition still goes in a lt form-bean gt tag in the struts-config file. However, rather than specifying your extended ActionForm class for the type attribute, you use the full class name of the DynaActionForm class. In addition, you specify the form properties that will be implemented by the formbean. Listing 6-4 is an example of how to implement LoginForm from the Login example application in...
Differences between ActionForm and DynaActionForm
Although ActionForm and DynaActionForm are similar, you do need to take into account a few differences. The following differences stand out I The DynaActionForm doesn't have reset or validate methods available. They exist but they're both empty methods. Intuitively, it makes sense that reset is not present DynaActionForms are generated with each request, so there's no need to reset values. I If you want a DynaActionForm and you also need to call a reset or validate method, you must subclass...
Predefined Action classes
Struts has five predefined Action classes for developers to use. Why would you want to use these classes In the appropriate situation, these classes can save you a lot of time. These classes are explained in the next few sections. The ForwardAction class is useful when you're trying to integrate Struts into an existing application that uses Servlets to perform business logic functions. You can use this class to take advantage of the Struts controller and its functionality, without having to...
Controller configuration
You can make changes in the configuration of the ActionServlet through the use of the controller tag. You can configure quite a few qualities of the ActionServlet through this tag. Most applications can skip configuring the controller and simply use the default values. The tag for inserting a new controller is lt controller gt . The DTD syntax for the tag is shown here The lt controller gt tag defines any changes to ActionServlet. The list of possible attributes is as follows i bufferSize The...
Preparing the form with the reset method
The standard reset method does nothing by default. This is appropriate because the reset method would know nothing about the properties of your formbean. You have the responsibility to write the appropriate code to set all your form properties back to their default state. Why is resetting property values necessary Actually, you don't need to reset values if your formbean is stored in the request scope because the formbean gets reinstantiated for each new request anyway. However, if you elect to...
Global or local exception handling
Exceptions can be defined globally for the entire application or locally for a particular Action. In this respect, exceptions are similar to forwards. If you choose to define an exception globally and that exception type occurs in any Action i n your application, it's handled in the manner defined in the global definition. One caveat if the exception type is also defined locally for a particular Action, the local definition takes precedence. To define an exception globally, simply place the...
Listing Overriding the processPreprocess Method of the CustomRequestProcessor
1 protected boolean processPreprocess HttpServletRequest request, 3 boolean continueProcessing true assume success 4 Test if the request is a login request 8 ensure that the user's session has not timed out 10 session request.getSession 11 else user's session has timed out, make them login again 13 get the current request's path 14 String path processPath request, response 15 don't do any testing if user is logging on 16 if path.equals String login 19 User user User 20 ensure that user has...





