Designing Enterprise Applicationswith the J2EETM Platform, Second Edition phần 9 pptx

44 577 0
Designing Enterprise Applicationswith the J2EETM Platform, Second Edition phần 9 pptx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

WEB TIER INTERNATIONALIZATION 331 localized selectively with this scheme. The logic for determining which file to forward to is in a dispatching servlet or servlet filter, which can implement the same naming convention scheme as do resource bundles. The forwarding compo- nent can always choose the most specific file available and use a default file (with no localization suffix) as a fallback. The page-per-locale approach has the following benefits: • Greater customizability—Using resource bundles to customize a single JSP page results in pages whose structure is essentially the same for all locales. Using one JSP page per locale provides maximum customizability of the content for a locale, because customizations are not limited to the contents of a resource bundle. As a result, the page-per-locale approach is prefereable when content differs substantially between locales. • Source clarity—All of the content for a locale appears in a single file (the JSP file for the locale) instead of being separated between a JSP page file with some structural tags, and a properties file or resource bundle class containing named strings. At the same time, this approach has some drawbacks. Maintaining a consis- tent look-and-feel between locales is more difficult with separate JSP pages than with resource bundles. Separate files must be created and maintained consistently for several locales. This means more maintenance than does the resource bundle approach. The Web-tier framework and tools you select for creating your application may influence your decision in how to support internationalized content. The sample application uses a templating mechanism, providing both struc- tural consistency between locales and the flexibility of page-per-locale localiza- tion. The templating mechanism uses an XML “screen definitions file” for each locale to assemble localized JSP pages into a single page. The screen definitions file for a locale specifies a template file, and maps localized JSP pages to symbolic names such as “header,” “footer,” and so on. The template file defines the overall structure for a page, and uses custom tags to include localized JSP pages, which it references by symbolic name. Because the screen definitions file specifies the template, both page layout and “look and feel” can be unified across locales (by using a single template) or customized for particular locales (by using separate templates). DEA2e.book Page 331 Friday, March 8, 2002 12:31 AM CHAPTER 10 J2EE INTERNATIONALIZATION AND LOCALIZATION 332 Regardless of which option you choose, setting the JSP page response encod- ing correctly is crucial. The sample application standardizes all page encoding to UTF-8, and enforces this encoding with a servlet filter for all JSP pages it serves. 10.4 EIS Tier Internationalization Because data in an enterprise information system can vary by locale, localization issues can reach all the way into the EIS tier. This section discusses some issues regarding persistent data and schema in databases. 10.4.1 Persistent Localized Data A J2EE application requires internationalization support in its persistence layer as well as in component source code. Persistence layer design should always address internationalization concerns. Both container-managed persistence and bean-managed persistence require that an application’s JDBC driver and back-end data store support all character sets and all encodings used to represent persistent data. UTF-8 encoding is advised because it is widely supported by JDBC drivers and databases, and sup- ports many character sets. 10.4.1.0.1 Value Conversion, Value Representation, and Information Loss Uniform value representations in a database simplify database access and applica- tion code, but improper localization can cause subtle flaws in application logic. Value representations in a database should be as independent of locale as possible, if the conversion from the original representation can be performed without informa- tion loss. Where such a conversion cannot be performed, a data value should include a locale and unit designator. The key distinction to make is between the data value, which usually should not be modified, and the way that the value is represented, which usually should be uniform for all database records. The following examples illustrate the difference between a data value and the way the value is represented: • Fixed decimal numbers—English-speaking countries often format decimal numbers as 1,234.56, whereas people in many other countries format the same number as 1.234,56. Rather than maintain the original punctuation, a database attribute for such a value should be a coded decimal type that can later be pre- DEA2e.book Page 332 Friday, March 8, 2002 12:31 AM EIS TIER INTERNATIONALIZATION 333 sented in any format or encoding. Where there is a business reason to do so, a locale should be stored along with the data value. • Strings—The sequence of characters in a string, not the string’s encoding, de- termines the string’s value: For example, any number of different byte se- quences can represent the string abc. Saving strings in a database in a variety of encodings, even if the encoding is stored with the value, can complicate pro- cessing the strings. The recommended approach for persisting strings received in multiple encodings is to use a universal encoding such as UTF-8 as the da- tabase attribute type, and convert from the received encoding to the database encoding before storing the value. The string can later be converted to other encodings for display. Where there is a business reason to do so, store a string along with its original encoding and/or locale, so that the original string can be recovered by encoding conversion. For example, a multilingual Customer Relationship Management (CRM) application might use a stored locale to route each customer request to a service representative who speaks that customer’s language. The application could use the stored encoding to encode the response to the customer. • Currency—It is impossible to overemphasize the importance of properly han- dling currency values. Your organization’s business rules, not the user’s lo- cale, determine the values of quantities such as prices in a catalog. If your application quotes a price in Yen to a Japanese customer, for example, the ap- plication should persist the value in Yen, not a value converted to U.S. dollars. (If business rules mandate conversion to dollars at the time of the quote, then the value should be displayed in dollars toavoid misleading the customer.) The application must always record currency values denominated in the currency mandated by business rules. When currency is converted, an audit trail often also requires storing the conversion rate and the value and denomination be- fore conversion. An application’s handling of currency values should always be checked by someone who understands the business’s accounting rules. Ex- tensive testing with audits can also uncover currency conversion errors. The J2SE platform version 1.4 class java.util.Currency represents ISO 4217 cur- rency codes, and can be used for currency formatting; see the J2SE javadoc documentation for details. DEA2e.book Page 333 Friday, March 8, 2002 12:31 AM CHAPTER 10 J2EE INTERNATIONALIZATION AND LOCALIZATION 334 • Physical properties and dimensions—Some value conversions for physical properties can cause information loss, others do not. For example, the conver- sion formula from degrees Fahrenheit to degrees Celsius can introduce rounding errors that may or may not be significant for your ap- plication. Whether to store the original value with a dimension or to store a converted value with an implied dimension depends on the application’s pre- cision requirements. • Time and date—Some global distributed applications standardize on a univer- sal time coordinate (UTC) for all representations of dates and times, plus (op- tionally) an indication of time zone. Because UTC can be determined from local date and time for any geographic point, no data is lost in the conversion. As with currency, this determination depends on the organization’s business rules. There are many more situations where data value and data representation may vary by locale. Uniform value representation in a database simplifies application coding, but should never cause information loss. 10.4.2 Internationalizing Database Schema The effect of internationalization on an application’s data model is one of the more important reasons to consider internationalization in an application’s design phase. Many internationalized data sets cannot be represented reasonably as resource bundles or as static JSP pages, either because the data set is too large or the data change too fast, or both. Such data sets are usually stored in and accessed from data- bases. Data model entities often include locale-dependent attributes such as descrip- tive text, images, or resource references. In an internationalized application, an entity has a one-to-many relationship with these items. For example, each item in a non-internationalized catalog has a single descriptive text string, whereas an internationalized catalog item requires a descriptive text string for each supported locale. °C 5 °F 32–() 9 = DEA2e.book Page 334 Friday, March 8, 2002 12:31 AM EIS TIER INTERNATIONALIZATION 335 Consider the example of internationalizing the description of a catalog item. Three alternative ways to model an internationalized attribute appear in Figure 10.4. Figure 10.4 Internationalized Attribute Modeling Alternatives One way to internationalize an attribute is to add a new attribute to the entity for every supported locale. The leftmost example in Figure 10.4 shows an item table with a description column for each locale. But that approach would require both code changes and the addition of a column to every internationalized table each time a new locale is added. Another approach is to place the attribute in a separate entity for each locale. The middle example in Figure 10.4 shows an item table that has no descriptive text but joins to a separate catalog description table for each locale. But this approach still requires schema and code modifications to add a locale to the appli- cation. The third option (recommended) is to include locale in the data model, making it part of the identity of the entity representing the localized resource. The rightmost example in Figure 10.4 shows an Item table that joins with an ItemDetails table. The primary key of the ItemDetails table includes both the ID of the item being described and the locale for the description and other resources. The application code for this approach contains no hard-coded locale information, so adding a new locale is as simple as adding localized data to the table. The sample application models internationalize data in exactly this way. Figure 10.5 shows a part of the sample application’s data model. It contains a hier- archical categorization of items by product, and products by category. The cate- DEA2e.book Page 335 Friday, March 8, 2002 12:31 AM CHAPTER 10 J2EE INTERNATIONALIZATION AND LOCALIZATION 336 gory, product, and item tables each have an associated detail table that contains locale-specific data. Application code retrieves localized resources from this table, looking up descriptive text, images, names, and so on, by both locale and ID. Figure 10.5 Internationalized Catalog Schema Note that, in these tables, details tables contain all localized data. The primary key (that is, the identity) of all details tables is the locale and an ID. A properly- designed schema will support future language additions with no changes to either code or database schema. Adding a new locale in this design is as simple as adding new localized data to the details tables. An internationalized database schema requires more up-front design work, but provides a great deal of flexibility for supporting localized content later on. 10.5 Internationalized Application Design Previous sections discussed internationalization issues by tier. This section covers some design techniques that are useful across tiers in internationalized, distributed applications. DEA2e.book Page 336 Friday, March 8, 2002 12:31 AM INTERNATIONALIZING APPLICATIONS WITH XML 337 10.6 Internationalizing Applications with XML There are a variety of ways to internationalize J2EE applications: • Use resource bundles in code—for programmatic control of internationaliza- tion; see Section 10.2.1 on page 316. • Use custom tags—for JSP pages that vary by locale only in data values; see Section 10.3.3.4 on page 328. • Use a separate JSP page for each locale—for pages that have a different structure for each locale; see Section 10.3.3.5 on page 330. • Transform XML with XSLT—to internationalize XML content. An application may use any or all of these techniques. This section covers the final option, using XML and XSLT to localize and communicate locale within and between applications. 10.6.1 Generating Localized Dynamic Content with XSLT One flexible way to create internationalized content is to use locale-specific XSLT stylesheets to style model data that are represented as XML. For example, an enter- prise bean might use JMS to asynchronously send localized XHTML to a user by email. XSL stylesheets are very effective for creating customized, dynamic struc- tured content in any application tier. The application component (JSP page, serv- let, or enterprise bean) can create XML that represents localized model data that are the results of a service request. An XSL styling component can then produce localized content, inserting and styling model data from the XML document. The name of the stylesheet that performs the localization is based on the requested locale, which is encoded in the XML itself. Localizations for new locales can be created by simply generating model data for the new locale, and then styling that data with a new XSL stylesheet. This approach cleanly separates business logic (the XML data) from presentation (the template text in the stylesheets). An example of this approach, including a description of a way to communi- cate locale among decoupled application components, appears in Section 10.6.3 on page 338). DEA2e.book Page 337 Friday, March 8, 2002 12:31 AM CHAPTER 10 J2EE INTERNATIONALIZATION AND LOCALIZATION 338 10.6.2 Communicating Locale within an Application The Java programming language represents values of type String, StringBuffer, and Character as Unicode. As a result, enterprise bean methods that use these types consistently preserve international character values, including method invocations through EJB local and remote interfaces. Enterprise bean business method signatures may include locale information when business logic depends on locale or where the data returned by a bean method is localized. Examples of enterprise beans whose behavior may be locale-dependent include components for tax calculation or shipping, or components that deal directly with external systems such as Web services or clients. A catalog enterprise bean might include method signatures with locale to indicate the language for viewing the catalog’s entries. Placing locale in session state can greatly simplify code localization. Instead of including a Locale argument in every business method signature, consider placing the current Locale in session state, either as an HttpSession attribute (for Web-only applications) or by using a stateful session bean (for applications using enterprise beans). A Locale stored in session state can be determined once, early in the session, and then used by all components for the remainder of the session. 10.6.3 Communicating Locale among Applications Most large organizations have not one, but several mission-critical business applica- tions. Seldom are these applications integrated “out of the box.” The art of integrat- ing disparate enterprise applications to work together as a whole is called Enterprise Application Integration (EAI). A currently-popular EAI strategy uses messaging to link together coarse- grained, loosely-coupled applications. For example, Web services use Internet protocols and data formats (often HTTP and XML) to send and receive messages that are formatted as XML documents. When one internationalized enterprise application requests a service from another application, the requesting application must somehow indicate the locale of the request, so that the data encoded in the request can be properly interpreted. J2EE applications often communicate among themselves and with other IT systems using XML message passing. In particular, EJB components may com- municate with external applications using JMS to send and receive payloads of XML messages. Web-tier components may provide XML Web services via HTTP to end users or to other information systems. Each of these scenarios requires a way to indicate locale. DEA2e.book Page 338 Friday, March 8, 2002 12:31 AM INTERNATIONALIZING APPLICATIONS WITH XML 339 Applications that send XML messages should encode the locale of the request, the requested locale of the response, or both, as strings in an element of the XML message. The naming conventions used for resource bundles provide a useful and widely-understood way to represent a locale as a string. Code Example 10.1 shows a sample XML message representing an invoice localized for the United States English locale. As in this case, the locale of the request and the response are usually the same, so only a single locale element is necessary. <?xml version="1.0" encoding="UTF-8"?> <invoice> <orderid>1234</orderid> <locale>en_US</locale> </invoice> Code Example 10.1 Sample XML Message with United States English Locale The same message with a Japanese locale appears in Code Example 10.2 below. <?xml version="1.0" encoding="UTF-8"?> <invoice> <orderid>1234</orderid> <locale>ja_JP</locale> </invoice> Code Example 10.2 An XML Message with Japanese Locale Note that the string used to represent the locale follows the naming conven- tion for resource bundle class name suffixes. Choose a universal encoding such as DEA2e.book Page 339 Friday, March 8, 2002 12:31 AM CHAPTER 10 J2EE INTERNATIONALIZATION AND LOCALIZATION 340 UTF-8 for all such XML messages, and be sure to include the document encoding in the XML declaration, as the code examples show. Figure 10.6 Communicating Localized Content A message receiver may use the locale encoded in the request to localize the content of an XML message it receives. The sample application contains a multi- lingual mailer application that transforms XML messages into localized emails to customers. A sample scenario appears in Figure 10.6 above. In this diagram, an EJB component in Application 1 sends an XML message via JMS to a multilin- gual mailer application. The mailer application receives JMS messages (using a message-driven bean), localizes the message contents, and sends the localized contents as emails to users. The message-driven bean in the mailer application receives and merges the XML payload ( invoice.xml) of each JMS message with a stylesheet containing template text. The bean selects an XSL stylesheet based on the incoming message type ( inv in this case) and the requested locale. The stylesheet contains XSL tem- plate rules that create email body text by inserting values from the XML docu- ment into localized template text. The result of the XSL transformation is an email message localized to the locale requested by the incoming message. This flexible solution provides a simple way to extend the mailer application for new locales. To add a new locale, a developer need only generate localized DEA2e.book Page 340 Friday, March 8, 2002 12:31 AM [...]... data in the exception are not localized: The localization is handled by the JSP page formatting the message In the example shown, UserExistsException reports that the given user name already exists in the system, and the exception object contains the user name that caused the error The exception does not contain localized messages, because the localization is handled by the JSP page for the locale The. .. values from the model (as XML), create an XSL stylesheet for the new locale, and follow the stylesheet naming convention The mailer application will correctly style incoming messages for the new locale Notice that this design maintains MVC separation: The data sent in the XML message is model data, the XSL stylesheet generates the view (the “view” is the email being sent to the customer), and the bean... as applicable The chapter begins with a description of some of the J2EE architectural approaches and the J2EE design patterns It also examines the design issues common to all J2EE applications These architectural concepts form the basis for the design of the sample application After covering these concepts, the chapter presents an overview of the sample application Then, it examines the key design... across the tiers Certain tiers are always present in a Webenabled application such as the sample application, including: • The client tier provided by the browser • The Web tier provided by the server • The EJB tier provided by the server • The enterprise information system or database tier holding persistent application data It is important to choose whether a Web tier component accesses the enterprise. .. 2002 12:31 AM DESIGNING THE SAMPLE APPLICATION Conceptually, the business divides into these functional units: • The Web site presents an online pet store interface to the customer The customer shops and places orders through this interface When a customer completes an order, the interface sends the order to the order fulfillment center Because the Web site functional unit drives further business processing... contains the exception object The error page may use this request parameter to format an error message The error page must include an isErrorPage directive, like this: The isErrorPage directive causes the implicit scripting variable exception to be initialized to the exception object thrown by the original JSP page The page may then format the message using the. .. and other suppliers may interact with the fulfillment center This portion of the business is referred to as the back end, because its processing is triggered by placing an order, an action that occurs in the Web site portion Although the supplier component is part of the sample application, it could just as easily be a service external to the application 11.3 Designing the Sample Application Designing. .. purchases the shopping cart contents Prior to a purchase, the sample application displays the order: the selected items, quantity and price for each item, and the total cost The customer can revise or update the order To complete the purchase, the customer provides a shipping address and a credit card number Figure 11.3 shows a high-level use case diagram for the sample application It shows the potential... Application clients can localize data on the server or the client, but in either case, localization should occur in presentation code An internationalized MVC controller can easily localize error messages The controller can catch all exceptions thrown from the Web tier and route them to the appropriate error page based on the name of the exception class The controller looks up the error page URL in an XML-based... and objects that address the different functional requirements The partitioning process includes deciding how to apportion the application across the different tiers of the J2EE platform, which portions of the application need to be distributed, and which should be implemented for local interaction The discussion begins with the functional specification for the user interface to the pet store Web site . an ItemDetails table. The primary key of the ItemDetails table includes both the ID of the item being described and the locale for the description and other resources. The application code for. maintains MVC separation: The data sent in the XML message is model data, the XSL stylesheet generates the view (the “view” is the email being sent to the customer), and the bean acts as a controller. internationalized enterprise application requests a service from another application, the requesting application must somehow indicate the locale of the request, so that the data encoded in the request

Ngày đăng: 12/08/2014, 16:21

Từ khóa liên quan

Mục lục

  • Designing Enterprise Applications with J2EE 2nd

    • J2EE Internationalization and Localization

      • 10.4 EIS Tier Internationalization

        • 10.4.1 Persistent Localized Data

          • 10.4.1.0.1 Value Conversion, Value Representation, and Information Loss

          • 10.4.2 Internationalizing Database Schema

          • 10.5 Internationalized Application Design

          • 10.6 Internationalizing Applications with XML

            • 10.6.1 Generating Localized Dynamic Content with XSLT

            • 10.6.2 Communicating Locale within an Application

            • 10.6.3 Communicating Locale among Applications

            • 10.7 Localizing Error and Logging Messages

              • 10.7.1 Client Messages and Application Exceptions

                • 10.7.1.0.1 JSP Pages Error Mechanism

                • 10.7.1.0.2 Servlet Error Mechanism

                • 10.7.1.0.3 Localizing Error Messages

                • 10.7.2 System Exceptions and Message Logging

                • 10.8 Summary

                • 10.9 References and Resources

                • Architecture of the Sample Application

                  • 11.1 J2EE Architecture Approaches

                    • 11.1.1 Model-View-Controller Architecture

                    • 11.1.2 J2EE Design Patterns

                    • 11.2 Sample Application Overview

                    • 11.3 Designing the Sample Application

                      • 11.3.1 Choosing Application Tiers

                      • 11.3.2 Choosing Local or Distributed Architecture

                        • 11.3.2.1 Comparison of Local and Distributed Architectures

                        • 11.3.2.2 J2EE Platform Distributed and Local Options

                        • 11.4 Architecture of the Sample Application

                          • 11.4.1 Application Web Site Architecture

                            • 11.4.1.1 View Layer of the Application Architecture

                            • 11.4.1.2 Model Layer of the Application Architecture

Tài liệu cùng người dùng

Tài liệu liên quan