JavaServer Page

October 23, 2006

610 CHAPTER 15 USING STRUTS, XDOCLET, AND

Filed under: JavaServer Page — webmaster @ 4:13 am

610 CHAPTER 15 USING STRUTS, XDOCLET, AND OTHER TOOLS Figure 15-12. The Tiles template shown previously renders this web page. Tiles templates, also known as layouts, can be referenced using two different techniques. The first is by using a JSP page. For example, you could put all the JSP pages in a pages directory. This technique comes in handy when using JSP pages to compose Tiles pages. You can simply put all your different page sections (or tiles) in the pages directory, and then reference them from the root directory. For instance, this is what a page might look like in the root directory: < %@ include file="/common/taglibs.jsp"%> The second option is to use an XML file and create definitions for each page. This is nice because definitions can extend each other as well as provide a central repository of your page composition information. Furthermore, definitions can still be references from a JSP page (when using a /do/* mapping) or as ActionForward paths in struts-config.xml. Let s look at how the previous JSP code might look in a tiles-config.xml file:

Note: If you are looking for good and high quality web space to host and run your jsp application check Lunarwebhost jsp web hosting services

610 CHAPTER 15 USING STRUTS, XDOCLET, AND

Filed under: JavaServer Page — webmaster @ 4:13 am

CHAPTER 15 USING STRUTS, XDOCLET, AND OTHER TOOLS 611
One of the principal advantages of using definitions is that you can inherit properties from each other. In this way, you can create a baseLayout definition that all definitions inherit from, and child definitions won t need to define certain properties, such as the header and footer. The previous definition can be refactored to something like this:

In the previous .login definition, you ll notice that we ve prefixed the tile name with a period (.). This dot notation is the recommended practice for naming tiles. Since Tiles s definitions can be references in a forward s path attribute, this prefix makes them easier to recognize. A definition can be referenced in a JSP page if you don t want to forward to it from an action. In struts-resume, we do this in the login.jsp page. We re protecting all *.do mappings with a , so we re unable to access any action without authenticating. The content of the login.jsp page is short and simple: < %@ include file="/common/taglibs.jsp"%> In the examples provided, you ll notice that messages come from ApplicationResources.properties for title and heading settings, but another option is available. This may be why Tiles seems so intimidating to some there are so many options! However, we do want to show you some other options that might be more suitable for you. Rather than using the ApplicationResources.properties file to represent the title or heading, you can code the strings directly in your definition or JSP:
Rather than using and , you can use . You might think you ve lost the internationalization (I18n) support in this process, but Tiles allows for an alternative way of achieving I18n: creating separate XML definition files for each locale. Using this strategy, you would have a tiles_config_en.xml for English, tiles_config_ru.xml for Russian, and so on. Using the

Note: If you are looking for good and high quality web space to host and run your jsp application check Lunarwebhost jsp web hosting services

October 22, 2006

CHAPTER 15 USING STRUTS, XDOCLET, AND OTHER

Filed under: JavaServer Page — webmaster @ 10:18 am

608 CHAPTER 15 USING STRUTS, XDOCLET, AND OTHER TOOLS While this approach is much easier than the first approach, you re still duplicating code between all your pages to include these external elements. It might only be three or four lines of code, but nevertheless, if you forget to include the header, chances are you won t find out until you (or your users) run your page through a browser. If you re using Struts, we d recommend Tiles because it offers many built-in interoperability features with Struts. Just like the Validator, it can be used on its own by simply making a servlet entry in your application s web.xml. However, we won t explore this configuration because this chapter focuses on Struts-based solutions. We will illustrate the templating system used in the example r sum application and how we ve implemented Tiles in this particular application. The architecture and techniques we ll be using have been tried and proven in production applications. Tiles can be used in many different ways for building portal sites and menuing systems as well as customization. Detailed online documentation for Tiles can be found at http://www.lifl.fr/~dumoulin/ tiles/. Using Tiles in the Example Application First of all, let s see how to integrate Tiles into the Struts application. With Struts, it s much like the Validator and only needs to be registered as a plug-in in your struts-config.xmlfile:
If you re using XDoclet, this will need to go in a struts-plugins.xmlfile in your merge directory. There are basically two ways to use Tile: The first is through a JSP page that includes other pages as a template. The second is to use an XML file to define the different components in a given page, also known as a definition. We highly recommend the XML-configuration route because it enables you to change page definitions in one location, rather than on a page-by-page basis. It also supports inheritance so you can define a base definition with the same header and footer, and then you don t need to specify these in the child definitions. The first property, definitions-config, points to the file you use to define your definitions. It also supports a comma-delimited list of file paths, which might be handy if you have many pages or definitions in your application. The second property, moduleAware, allows Tiles to recognize modules (formerly known as subapplications). We ll describe these further in an upcoming section. The basis of Tiles is that it allows you to define a template for your entire application, or several templates depending on your needs. This template will generally look like a regular HTML file, with all the basic elements, such as , , , and any layout elements, such as

or
. If you re still using tables for laying out your web applications, we implore you to try a tableless layout with
and CSS because it will make your pages much lighter and smaller for your clients. XHTML and CSS, and a modern browser of course, make this much easier. Listing 15-1 presents a very simple template for Tiles.

Note: If you are looking for good and high quality web space to host and run your jsp application check Lunarwebhost jsp web hosting services

CHAPTER 15 USING STRUTS, XDOCLET, AND OTHER

Filed under: JavaServer Page — webmaster @ 10:18 am

CHAPTER 15 USING STRUTS, XDOCLET, AND OTHER TOOLS 609 Listing 15-1. template.jsp < !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> < %@ taglib uri="http://jakarta.apache.org/struts/tags/struts-tiles" prefix="tiles" %> < %@ taglib uri="http://jakarta.apache.org/struts/tags/struts-bean" prefix="bean" %> < %-- Push tiles attributes in page context --%>

< %@ include file="/common/messages.jsp" %>

In the previous template, you can see that there are attributes that you import and attributes you insert. Basically, the is used for the tags. When you configure the application to use this template, you can actually tell it which key from your ApplicationResources.properties file to use for the title.key and for the heading.key. The tag is used to insert or include a JSP page, but this could also be a URL to any component within your application. If you re inserting JSP pages into your Tiles template, you ll need to configure your JSP pages so they can be executed independently of other pages. By this, we mean to say that they could be referenced with a dynamic include () rather than a static include (< %@include/>). Therefore, you must reference the appropriate tag libraries at the top of each page. To make development easier and faster, we usually create a JSP file with all our tag library declarations, and then use a static include to include them on every page. You can see an example of this in the struts-resume application. The template in Listing 15-1 will render a layout similar to the one shown in Figure 15-12.

Note: If you are looking for good and high quality web space to host and run your jsp application check Lunarwebhost jsp web hosting services

CHAPTER 15 USING STRUTS, XDOCLET, AND OTHER

Filed under: JavaServer Page — webmaster @ 10:18 am

CHAPTER 15 USING STRUTS, XDOCLET, AND OTHER TOOLS 607 In the struts-resume application, the BaseAction extends LookupDispatchAction. We ve also added our own little enhancement to the getKeyMethodMap()method, so that the key or value pairs are loaded from another property s file. This allows mapping new methods to buttons without recompilation. This might seem like overkill, but it only took a couple minutes to implement. One problem we ve seen with this class is that if you use JavaScript to disable your Submit buttons after they ve been clicked, the action parameter won t be sent. Note More information on each of these built-in actions can be found in the Struts Javadocs at http://struts.apache.org/javadoc.html. Using the Tiles Framework to Assemble the View Tiles is a Composite View framework for assembling presentation pages from component parts. Each part, or tile, can be reused as often as needed throughout your application. You can use Tiles in any JSP or servlet application, but it was originally designed for Struts and is therefore easiest to use within Struts. Since Struts 1.1, the Tiles framework has been integrated into the core Struts library (struts.jar). Tiles is often seen as a heavyweight, configuration- intensive plug-in, when in fact it offers the same simple functionality as the (now deprecated) struts-template tag library. Tiles was developed by Cedric Dumoulin, and in our opinion is one of the best things that ever happened for JSP developers. Standards like CSS and XHTML are also awesome (and have provided more structure to develop web applications that work across browsers), but Tiles has made it so much easier. Tiles will reduce your development time in building web applications and will also make it relatively easy to change the entire application s look. It offers the best layout framework we know of, although there are others that have fervent supporters such as SiteMesh (http://www.opensymphony.com/sitemesh) from OpenSymphony. We ve developed several JSP applications over the past few years, and we ve laid them out using many different techniques. The first technique was similar to how you would develop a static website, where each JSP page contained all the layout elements of a typical HTML page. This included the declaration, the element, , and any

or
elements within the body as well as the actual content. While this is generally easier for HTML developers to grasp, it s definitely the hard way. If you ever need to carry out a site redesign, chances are you ll need to meddle with every JSP file to do so. Of course, HTML editors (such as Dreamweaver, BBEdit, and HomeSite) will make this easier with their global search-andreplace features, but you can easily mess up your HTML at the same time. An easier way is to include elements that are common to all pages. Such elements include the element, which contains your CSS and JavaScript references, or a menu that is common to all pages.

Note: If you are looking for good and high quality web space to host and run your jsp application check Lunarwebhost jsp web hosting services

386 CHAPTER 9 DATA ACCESS OPTIONS FOR

Filed under: JavaServer Page — webmaster @ 3:16 am

388 CHAPTER 9 DATA ACCESS OPTIONS FOR WEB APPLICATIONS private Object retrieveObject(Class clazz, String id) throws DAOException { Object obj = null; Session ses = null; try { ses = sessionFactory.openSession(); obj = ses.load( clazz, id ); } catch (Exception e) { throw new DAOException(e); } finally { try { ses.close(); } catch (Exception ex) { ex.printStackTrace(); }; } return obj; } The getAllNewsfeeds() method, shown in the following excerpt, illustrates the code necessary to fetch a collection of objects from the database by using a query. This is also a simple operation. You open a session and run a query to get all news feeds by using the ses.find() method. The query is expressed by using Hibernate s own OQL, which is similar to but not quite the same as SQL. Listing 9-6. HibeAggregatorDAO.java (getAllNewsfeeds() Method) public List getAllNewsfeeds() throws DAOException { List feeds = null; Session ses = null; try { ses = sessionFactory.openSession(); feeds = ses.find(”from newsfeed in class ” + “com.apress.projsp.Newsfeed”); } catch (Exception e) { throw new DAOException(e); } finally { try { ses.close(); } catch (Exception ex) { ex.printStackTrace(); }; } return feeds; } The removeNewsfeed() and removeObject() methods show the code necessary to remove an object from the database. The steps here are very similar to the steps involved in the storeNewsfeed() method, except that we call ses.delete() to delete the object. Note that, because you specified the cascade=”true” attribute in the mapping for the associated Item

Note: If you are looking for good and high quality web space to host and run your jsp application check Lunarwebhost jsp web hosting services

386 CHAPTER 9 DATA ACCESS OPTIONS FOR

Filed under: JavaServer Page — webmaster @ 3:15 am

386 CHAPTER 9 DATA ACCESS OPTIONS FOR WEB APPLICATIONS The create-tables target in the previous example code comes from an Ant build script. This Ant build script compiles the example Java classes, builds the example WAR file, and creates the example s database tables by using the create-tablestarget. You can find the build script with the code download for this book (http://www.apress.com/book/download.html). Step 4: Implementing the AggregatorDAO The next step in RSS newsreader development is to write the Hibernate implementation of the AggregatorDAO interface. This implementation is in the package com.apress.projsp.persist. hibe and is named HibeAggregatorDAO. This task requires some knowledge of the Hibernate API, but the excellent Hibernate Reference Document (available at http://www.hibernate.org/hib_docs/v3/reference/en/html/) and Javadocs really shortens the learning curve. Obviously, we don t want to discuss every line of code in the implementation. Looking at the code for the constructor and the logic for persisting one object should give you a good understanding of the implementation. Listing 9-6 is the source code for the HibeAggregatorDAO class. We have split this code listing into parts, so that we can more easily discuss the various methods of the class. The constructor creates a Hibernate Datastore, loads the mappings for the classes that will be persisted, and creates a SessionFactory for use during the rest of the lifetime of the DAO object. The SessionFactory represents a database connection pool and is responsible for creating Session objects. The Session interface is the main Hibernate interface used by a Java program; a Session object holds a database connection. Listing 9-6. HibeAggregatorDAO.java (Package, Imports, and Constructor) package com.apress.projsp.persist.hibe; import com.apress.projsp.*; import com.apress.projsp.persist.*; import net.sf.hibernate.*; import net.sf.hibernate.cfg.*; import java.util.List; /** Hibernate implementation of Ag DAO. */ public class HibeAggregatorDAO implements AggregatorDAO { private static SessionFactory sessionFactory; public HibeAggregatorDAO() throws DAOException { try { Configuration config = new Configuration(); config.addClass(Newsfeed.class); config.addClass(Subscription.class); config.addClass(User.class); config.addClass(Item.class); sessionFactory = config.buildSessionFactory(); } catch (MappingException e) { throw new DAOException(e); }

Note: If you are looking for good and high quality web space to host and run your jsp application check Lunarwebhost jsp web hosting services

386 CHAPTER 9 DATA ACCESS OPTIONS FOR

Filed under: JavaServer Page — webmaster @ 3:15 am

CHAPTER 9 DATA ACCESS OPTIONS FOR WEB APPLICATIONS 387 catch (HibernateException e) { throw new DAOException(e); } } The storeNewsfeed() and storeObject() methods, as shown next, illustrate the code necessary to add a new object into the data store. The first step in the method is to open a session, which begins a database transaction. Next, you ll save the object database. To finalize the operation, you commit the transaction. If an exception occurs, roll back the transaction and throw a DAOException so that the business layer can handle the error condition. The finally block ensures that, no matter what happens, the session is closed and therefore the database connection that was used by the connection is released back to the database connection pool. Listing 9-6. HibeAggregatorDAO.java (storeNewsfeed() and storeObject() Methods) public void storeNewsfeed(Newsfeed feed) throws DAOException { storeObject(feed); } private void storeObject(Object obj) throws DAOException { Session ses = null; try { ses = sessionFactory.openSession(); ses.saveOrUpdate(obj); ses.flush(); ses.connection().commit(); } catch (Exception e) { try { ses.connection().rollback(); } catch (Exception ex) { e.printStackTrace(); }; throw new DAOException(e); } finally { try { ses.close(); } catch (Exception ex) { ex.printStackTrace(); }; } } The retrieveNewsfeed() method and retrieveObject() methods in the following continuation of Listing 9-6 show the code necessary to retrieve an object from the database by using the object s primary key. The steps are simple. You open a session, load the object, close the session, and return the object. Listing 9-6. HibeAggregatorDAO.java (retrieveNewsfeed() and retrieveObject() Methods) public Newsfeed retrieveNewsfeed(String id) throws DAOException { return (Newsfeed)retrieveObject(Newsfeed.class, id); }

Note: If you are looking for good and high quality web space to host and run your jsp application check Lunarwebhost jsp web hosting services

October 21, 2006

CHAPTER 9 DATA ACCESS OPTIONS FOR WEB

Filed under: JavaServer Page — webmaster @ 4:27 pm

CHAPTER 9 DATA ACCESS OPTIONS FOR WEB APPLICATIONS 385 It s possible to map more than one class within a single element, but it s a recommended practice to map only one class per mapping file. At runtime, the Newsfeed.hbm.xml file should be placed in the same package as the Newsfeed.class so that Hibernate can find it. The Hibernate mapping file may look complicated, but it s complicated for a reason. The mapping is designed to accommodate all the different data and relationship types that you might use in a Java application and in a relational database schema. If you have problems coming up with the right mappings, consult your friendly database administrator. Ask for help on the Hibernate mailing list. Step 3: Creating the Database Tables Creating the object-relational mappings for the RSS newsreader classes is relatively difficult, but once you have those mappings Hibernate starts to earn its keep. Hibernate includes a command-line tool that reads mapping files and can then either generate a database creation script or connect to your database and create the tables for you. This tool is called SchemaExport and it can handle 16 database dialects including Oracle, Sybase, Microsoft SQL Server, MySQL, and PostgreSQL. SchemaExport is just a command-line Java program, so it may be easily run from an Ant build script. For example, the following Ant build script excerpt is used to run SchemaExport and create the tables for the RSS newsreader example:
The element runs the class cirrus.hibernate.tools.SchemaExport within the build directory so that it can find the mapping files. The output argument tells the Schema- Export to generate a database creation script named rss.ddl. The properties argument tells SchemaExport where to find the Hibernate properties file, which contains the database connection parameters needed to connect to the target database. The rest of the arguments indicate which mappings are to be processed.

Note: If you are looking for good and high quality web space to host and run your jsp application check Lunarwebhost jsp web hosting services

CHAPTER 9 DATA ACCESS OPTIONS FOR WEB

Filed under: JavaServer Page — webmaster @ 4:27 pm

CHAPTER 9 DATA ACCESS OPTIONS FOR WEB APPLICATIONS 383 return mTime; } public void setTime(Date time) { mTime = time; } } Similar JavaBeans exist for User, Subscription, and Newsfeed. Step 2: Creating an Object-Relational Mapping The next step in the development of the RSS newsreader is the development of the data layer to store and retrieve the business objects developed in step 1. This step is a little more difficult because you must learn the ins and outs of your persistence choice in our case the Hibernate O/R persistence framework. Luckily, the Hibernate documentation is very good and Hibernate is fairly easy to use. Before you can use Hibernate to store Java objects in a relational database, you have to create an object-relational mapping for each object to be stored. A mapping specification is an XML file that describes how to map one or more Java classes to tables in a database. For example, the mapping for the com.apress.projsp.Newsfeed class, from the file Newsfeed.hbm.xml, is shown in Listing 9-5. Listing 9-5. Newsfeed.hbm.xml < ?xml version="1.0"?> < !DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 2.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

Note: If you are looking for good and high quality web space to host and run your jsp application check Lunarwebhost jsp web hosting services

« Previous PageNext Page »

Powered by Java Web Hosting