JavaServer Page

October 21, 2006

CHAPTER 9 DATA ACCESS OPTIONS FOR WEB

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

384 CHAPTER 9 DATA ACCESS OPTIONS FOR WEB APPLICATIONS Let s analyze the contents of the Hibernate mapping. After the standard XML declaration and the DOCTYPE tags, you find the root element of a Hibernate mapping file, the element. Within the root element, you ll find one or more tags. The tag maps one class to a database table, so the tag has two attributes. The nameattribute specifies the name of the Java class, and the table attribute specifies the name of the table that the Java class is to be mapped to: The first element within the class mapping is the element. This element specifies which JavaBean property and which database table column are to be used as a primary key for the class. Within the tag is the tag, which specifies which method should be used to generate primary keys for new objects: Hibernate supports 10 primary-key generation methods. The class=”uuid.hex” method results in a 32-character key that is generated by using the IP address of the machine upon which Hibernate is running. It s also possible to tell Hibernate to allow the database to generate the key by using class=”sequence” or to allow the application to assign the key by using class=”assigned”. The
tag maps a simple java.lang.String property named url to a database column called url. The property isn t allowed to be null and is required to be unique.
The next two elements are interesting. The tag indicates that you re mapping a java.util.Set collection to the database. Each Newsfeed is associated with a collection of Item objects and a collection of Subscription objects. This is a classic one-to-many relationship. The com.apress.projsp.Newsfeed objects are stored in the newsfeed table, the com.apress.projsp.Item objects are stored in the item table, and the two tables are related by a newsfeed_id column in the item table: If you re having a hard time visualizing these relationships, refer to Figure 9-7 in the Two-Layer Architecture section, which shows the relationships between User, Subscription, Newsfeed, and Item objects.

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

380 CHAPTER 9 DATA ACCESS OPTIONS FOR

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

CHAPTER 9 DATA ACCESS OPTIONS FOR WEB APPLICATIONS 381 The presentation layer is implemented with JSP pages, JSTL tags, and Java classes in the package com.apress.projsp.web, which are responsible for parsing request parameters and calling the business layer. The presentation layer depends only on the business layer. The sole interface to the business layer is the Aggregator business interface. The data layer exists under the com.apress.projsp.persist package and is made up of the AggregatorDAO interface, the DAOException class, and the DAO implementation class HibeAggregatorDAO. The DAO implementation uses the Hibernate O/R persistence framework. Step 1: Implementing the Object Model You ve already learned the first steps in the RSS newsreader development process. These steps were the design of the object model, the design of the business interface, and the design of the DAO interface that will encapsulate data access. The next step in the process is to implement the object model. This is easy because there are only four business objects, and these business objects are simple JavaBeans with each having only a small number of properties. Listing 9-4 is an example of one of the business objects, the Item class. Listing 9-4. Item.java package com.apress.projsp; import java.util.Date; import java.util.Set; /** * Represents a single news item retrieved from a newsfeed. */ public class Item { private String mId; private String mLink; private String mDescription; private String mContent; private String mTitle; private Date mTime; private Newsfeed mNewsfeed; private Item mItem; /** * Construct Item using all field values. * @param title Title of this news item. * @param time Time of publication. * @param link Link article on originating website. * @param desc Description of article (or full text of article). * @param content (Optional) full text of article. */ public Item( String title, Date time, String link, String description, String content ) {

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

380 CHAPTER 9 DATA ACCESS OPTIONS FOR

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

382 CHAPTER 9 DATA ACCESS OPTIONS FOR WEB APPLICATIONS mTitle = title; mTime = time; mLink = link; mDescription = description; mContent = content; } /** Default constructor */ public Item() { } public String getId() { return mId; } public void setId(String id) { mId = id; } public Newsfeed getNewsfeed() { return mNewsfeed; } public void setNewsfeed(Newsfeed newsfeed) { mNewsfeed = newsfeed; } public String getTitle() { return mTitle; } public void setTitle(String title) { mTitle = title; } public String getContent() { return mContent; } public void setContent(String content) { mContent = content; } public String getDescription() { return mDescription; } public void setDescription(String description) { mDescription = description; } public String getLink() { return mLink; } public void setLink(String link) { mLink = link; } public Date getTime() {

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

380 CHAPTER 9 DATA ACCESS OPTIONS FOR

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

380 CHAPTER 9 DATA ACCESS OPTIONS FOR WEB APPLICATIONS Newsfeed, and Item objects in an XML file. In the next section, you ll learn the steps involved in implementing the AggregatorDAO interface when using the Hibernate O/R persistence framework. Implementing the RSS Newsreader Example The RSS newsreader example that we have been discussing in this chapter is developed by using a three-layer architecture as described in the previous section. The application includes a presentation layer, a business layer, and a data layer. In this section, we ll first discuss the package organization of the RSS newsreader and then we ll cover each of the steps that were taken in the development of the application. Package Organization Before talking about the steps involved in building this application, let s talk a little more about how the pieces fit together. Figure 9-9 shows the three layers of the application, the Java packages that exist within each layer, and the dependencies that exist between these packages indicated by arrows. Figure 9-9. The RSS application has three layers (or tiers). Each component in the application is part of a single layer. The components work together to provide the functionality of the application. The business layer is made up of the business objects and the AggregatorImpl class, which implements the Aggregator business interface that was discussed earlier in the section on two-layer architectures. The business layer depends only on the data layer, and the sole interface to the data layer is the AggregatorDAO interface.

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 20, 2006

CHAPTER 9 DATA ACCESS OPTIONS FOR WEB

Filed under: JavaServer Page — webmaster @ 9:30 pm

378 CHAPTER 9 DATA ACCESS OPTIONS FOR WEB APPLICATIONS Why would anybody want to introduce yet another layer into an application? After all, each additional layer adds another layer of complexity, and all these layers cannot be good for performance. You have to think carefully before you decide to add another layer to your application, but there are at least two reasons that you might want to do so. These reasons to consider separate business and data layers come right off the list of trade-offs that we discussed when we introduced the topic of architecture: Reusability: Someday you may want to turn your business layer into a stand-alone desktop application that doesn t require a database. If your data access logic is mixed in with your business logic, this task is going to be difficult and error-prone. Resilience to change: Changes in the persistence logic will be less likely to affect the business logic, and changes in the business logic will be less likely to affect the persistence logic. For example: Someday you might find that the O/R persistence framework you chose has a fatal flaw or is no longer going to be supported. You might need to replace your chosen O/R framework with something else, and separation of business logic and data access logic will make this task easier. Reusability and resilience to change are forms of flexibility, and most developers consider flexibility to be a good thing. However, it s important to realize that flexibility comes at the price of added complexity, and complexity makes software more difficult to develop and to maintain. You don t want to do a lot of extra work now for some event that may possibly occur at some point in the future, especially if that extra work is going to make your application more difficult to maintain. The following are a couple of other reasons not to use separate business and data layers: Developing an abstract interface to data access isn t an easy task. It requires some knowledge of each of the various data access technologies that you may wish to use behind that interface. Hiding your data access technology behind an abstract interface may make it difficult to use some of that technology s advanced features. The Data Access Object Pattern If you decide that you do want to implement a three-layer architecture and you do want to separate out your data access logic into a data layer, then you should consider using the Data Access Object (DAO) pattern. As you may already know, a pattern is a general design for a recurring problem. The DAO pattern is a general design for encapsulating data access. The DAO pattern is a popular pattern and is documented as part of the Sun J2EE Patterns Catalog (http://java.sun.com/blueprints/corej2eepatterns/). Here is how the DAO pattern works. Instead of calling the JDBC or some other persistence API directly from all of your Java classes that need to access data, you encapsulate all of your data access code in one or more data access objects, or DAOs. Typically a DAO will include methods for creating, retrieving, updating, and deleting objects from the database as well as methods for querying the database to retrieve collections of objects. Depending on how you implement the DAO pattern, you could have a DAO for each class of object in your application or you could have a single DAO that is responsible for creating, retrieving, updating, and deleting all of your objects.

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 @ 9:30 pm

CHAPTER 9 DATA ACCESS OPTIONS FOR WEB APPLICATIONS 379 In your RSS newsreader application example, there is a single DAO called AggregatorDAO, which is shown in Listing 9-3. The AggregatorDAO contains methods for creating, retrieving, updating, and deleting all the different types of objects that are part of the application. These objects are User, Subscription, Newsfeed, and Item. Listing 9-3. AggregatorDAO.java package com.apress.projsp.persist; import com.apress.projsp.Item; import com.apress.projsp.Newsfeed; import com.apress.projsp.Subscription; import com.apress.projsp.User; import java.util.List; /** Aggregator Data Access Object (DAO) interface. */ public interface AggregatorDAO { /** Gets user by name, create new user if necessary. */ public User getUser(String userName) throws DAOException; /** Add new subscription and associate with a newsfeed */ public Subscription addSubscription( User user, String name, String url) throws DAOException; /** Retrieve subscription by ID */ public Subscription retrieveSubscription(String id) throws DAOException; /** Remove subscription but not associated Newsfeed. */ public void removeSubscription(Subscription sub) throws DAOException; /** Get all newsfeeds. */ public List getAllNewsfeeds() throws DAOException; /** Remove newsfeed and associated subscriptions. */ public void removeNewsfeed(Newsfeed feed) throws DAOException; /** Store newsfeed. */ public void storeNewsfeed(Newsfeed feed) throws DAOException; /** Add item to newsfeed. */ public void addItem(Newsfeed feed, Item item) throws DAOException; /** Add a newsfeed (for testing only). */ public Newsfeed addNewsfeed(String url) throws DAOException; /** Get all items (for testing only). */ public List getAllItems() throws DAOException; } AggregatorDAO is an interface that you could implement by using just about any data access technology. For example, you could write a JdbcAggregatorDAO class that implements data access with JDBC or you could write an XmlAggregatorDAO that stores User, Subscription,

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 @ 9:30 pm

CHAPTER 9 DATA ACCESS OPTIONS FOR WEB APPLICATIONS 377 /** Run the aggregator and fetch items from all Newsfeeds. */ public void aggregate() throws Exception; } The Aggregator interface distills the interface between the presentation layer and the business layer down to only four methods. The interface is so simple because the getUser()method does a lot of work. It returns a User object that has a collection of Subscriptionobjects. Each Subscription has a Newsfeedobject, and each Newsfeed has a collection of Item objects, the most recent news stories retrieved from the Newsfeed s website. The addSubscription() and removeSubscription() methods allow you to manage subscription in the presentation layer. Finally, the aggregate() method allows you to launch the aggregate operation, which visits each of the news feeds represented by subscriptions in the database, parses the RSS from the news feed into Item objects, and stores those objects in the database. With the simple Aggregator interface previously discussed, you can totally separate the presentation layer of the RSS newsreader from the business layer. The presentation layer doesn t need to know anything about what is going on behind that interface. It doesn t need to know what type of RSS parser is being used to parse the incoming news feeds. It doesn t need to know what type of data access technology is being used to persist business objects. A two-layer architecture is usually sufficient, but in some cases you may wish to take the architecture one step further and use a three-layer architecture. Three-Layer Architecture The two-layer architecture works well. It allows you to separate presentation logic from business logic, and that is good. However, you didn t separate the business logic from the data access logic. Business logic and data access logic seem to go together. Business rules are often built right into database schemas in the form of database constraints, and business logic is often coded into databases in stored procedures and triggers. But if two is good, three must be better. Figure 9-8 shows an illustration of a three-layer architecture. In the three-layer architecture, business logic is further separated from data access logic. Web Browser Database Servlet API Presentation Tier Business Tier Business Objects Data Access Data Tier Figure 9-8. In a three-tier architecture, presentation, business, and data are separated into different components, making it easier to change components in a tier without affecting the other tiers.

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

374 CHAPTER 9 DATA ACCESS OPTIONS FOR

Filed under: JavaServer Page — webmaster @ 2:08 pm

users, subscriptions, news feeds, and news items. Figure 9-7 is a UML diagram that shows these objects, their attributes, and their relationships. Figure 9-7. A User has one or more Subscriptions. A Subscription consists of Newsfeeds, which consists of Items. The diagram, which uses UML notation, shows that the users have a one-to-many relationship with subscriptions, subscriptions have a many-to-many relationship with news feeds, and news feeds have a one-to-many relationship with items. In this example, you ll have a one-to-one correspondence between classes and database tables. So you ll have User, Subscription, Newsfeed, and Item objects as well as corresponding user, subscription, newsfeed, and item tables. Now that you ve designed the objects needed for your application, you ll need to design the business-layer interface. This interface will be used by the presentation layer to invoke newsreader operations and to access the newsreader objects that were discussed earlier. To implement the presentation layer, you need to be able to add subscriptions, remove subscriptions, access users, and run the news feed aggregation operation. Listing 9-2 shows an interface that fulfills all of these requirements. Listing 9-2. Aggregator.java package com.apress.projsp; /** * Business interface for Newsfeed aggregation. */ public interface Aggregator { /** Gets user by name, create new user if necessary. */ public User getUser(String userName) throws Exception; /** Add new subscription and associate with a newsfeed. */ public Subscription addSubscription( User user, String name, String url) throws Exception; /** Remove subscription by id. */ User +name Item +title +time +description +link Newsfeed +url 1 1 * *+name Subscription * * CHAPTER 9 DATA ACCESS OPTIONS FOR WEB APPLICATIONS 376

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

374 CHAPTER 9 DATA ACCESS OPTIONS FOR

Filed under: JavaServer Page — webmaster @ 2:08 pm

374 CHAPTER 9 DATA ACCESS OPTIONS FOR WEB APPLICATIONS In this chapter, you ll develop a simple JSP-based RSS newsreader. If you would like to see a more full-featured web-based RSS newsreader, take a look at O Reilly s Meerkat, (http://www.oreillynet.com/meerkat/), which can aggregate and filter news stories from numerous professional sources. An alternative is Atlassian s JavaBlogs.com, which aggregates numerous Java-oriented weblogs (http://www.javablogs.com). Note Because of the large amount of code in this example, only a few code listings from the example are included in this chapter. The complete source code for the example is available as part of the code download for the book, at the Source Code area of the Apress website (http//:www.apress.com/book/download.html). Now that you know a little bit about RSS and RSS newsreaders, you re equipped to understand the examples that follow. Now, let s move on to the architectures. One-Layer Architecture In the simplest JSP data access architecture, an application accesses data directly from the presentation layer. You might be tempted to use this type of architecture because it seems like the easy route. After all, you don t have to design and implement a business layer or a data layer. Figure 9-5 illustrates the single-layer architecture. As you can see, the presentation layer not only depends on the Servlet API, but also has a direct dependence on the data access technology, which might be JDBC, JDO, or some other persistence framework. Web Browser Database Presentation Tier Servlet API Data Access Figure 9-5. In a single-layer architecture, the presentation logic, business logic, and data access logic all reside within the same application code. With single-layer architecture, you re sacrificing maintainability, reusability, and resilience to change in order to make development a little easier. This might be acceptable for a smaller application, but for a larger application this type of architecture will make your code have the following characteristics: Difficult to maintain: Presentation, business, and persistence logic are all mixed together and cannot be considered or changed separately.

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

374 CHAPTER 9 DATA ACCESS OPTIONS FOR

Filed under: JavaServer Page — webmaster @ 2:08 pm

CHAPTER 9 DATA ACCESS OPTIONS FOR WEB APPLICATIONS 375 Difficult to reuse: The business logic cannot easily be separated from the presentation logic. If you need to create a new application or a web service that uses your business logic, you re out of luck because your business logic is mixed in with your JSP and servlet-based presentation code. Not resilient to change: If you need to switch to a new data access technology, you ll have to make sweeping changes in your code. You cannot change the persistence logic without putting the business logic and presentation logic at risk. Two-Layer Architecture Splitting your application into a presentation layer and a business layer can solve the one-layer problems previously mentioned. This is a more difficult task because it requires designing business objects to model the business concepts and entities in your application. It also requires creating an interface or a set of interfaces through which your presentation layer can invoke business operations and access business objects. Figure 9-6 illustrates the two-layer architecture. As you can see, the presentation layer depends on the Servlet API but it calls upon the business layer to perform business operations and data access. The business layer depends on data access technology, which again can be JDBC, JDO, or some other persistence framework. Looking at Figure 9-6, you can see that the business layer is now an independent and reusable software entity. You could take that business layer and place it in a desktop application or you could take it and build a SOAP-accessible web service around it. Database Data Access Web Browser Servlet API Presentation Tier Business Tier Business Objects Figure 9-6. In a two-layer architecture, the presentation logic is separated from the business logic and data access logic. You re probably wondering what is going on inside the business layer box in Figure 9-6. The best way to understand the concepts of business interfaces and business objects is by example. So, let s take a look at the business objects and business interface of the RSS news- reader that was mentioned earlier. An RSS newsreader allows a user to subscribe to a number of news feeds and then to read the news items retrieved from those news feeds. By looking at the nouns in that sentence, you can see what objects are going to be involved in this application. You ll need objects to model

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