Using JSF, SpringFramework and Hibernate to build an instance of web applications

xiaoxiao2021-03-06  60

(Source: http://blog.9cbs.net/ylong/archive/2004/07/24/50810.aspx)

Original author]

Derek yang Shen [description link] http://www.javaworld.com/javaworld/jw-07-2004/jw-0719-jsf.html [Source Link] http://www.javaworld.com/javaworld/jw- 07-2004 / JSF / JW-0719-jsf.zip [translation] I [Review] This article is the first article telling JSF and Spring integration, it is a good example, more suitable for Spring I have a sense of learning. Among them, the JSF, which is described, can also come to the JSF. [Declaration] This article is the first translation of the big piece of block. Because I am scattered, my English is bad, but I don't like to watch the foreign language like I have used it. Time to translate this article. Some technical nouns and places that do not translate have been replaced by the original text, and there is a lot of mistakes, welcome to criticize and correct. [Translation] JSF is a new technique for architecture J2EE application user interface, which is particularly suitable for applications based on MVC architecture. Although many articles have been introduced to JSF, but most of them introduce JSF from the theoretical height instead of being practical. At present, there are still many problems in JSF, such as how to adapt JSF in the MVC overall architecture? How to integrate JSF with other Java frameworks? Does the business logic are placed in the JSF's Backing Beans? How to handle security mechanisms in JSF? What's more important is how to use the JSF architecture of the real world web application? This article will involve these problems above, it will demonstrate how JSF, Spring and Hibernate are integrated together, and architectures have a named JCATALOG.

Online product price system

. With this Demo, this paper covers every stage of Web application development, including demand collection, analysis, technical selection, system architecture, and implementation. This article discusses the advantages and disadvantages of various technologies involved in JCATALO, and demonstrates some key parts. The object of this article is engaged in J2EE-based web application architecture and developers. It is not a brief introduction to JSF, SpringFramework, and Hibernate. If you don't know much about these areas, please refer to relevant resources. The functional requirements of this example JCatalog is a real-world web application. I first describe the needs of JCATALOG, which will involve this part when designing technical decisions and architectures. The first phase of the design web application is to collect the functional requirements of the system. Example applications are a typical e-commerce application, users can browse the product's Catalog and view the details of the product, and the administrator can manage the product's Catalog. This application can become a mature e-commerce system by adding some other features such as Inventory management and order processing. Use casseSUse-case analysis is used to exhibit functional requirements for exemption applications, Figure 1 is the use-case diagram of the application. Use-case graphs are used to represent the ACTORS in the system and the possible Operations, which will have seven USE-CASE in the app. Users can browse the product Catalog and view the details of the product, once the user logs in to the system, she will Become an administrator, you can create new products, edit existing products or delete old products. Business rulesjcatalog must meet the following Business Rules:

Each product must have a unique ID Each product must belong to at least one category product ID Once founded to be modified.

Assumptions We do the following assumptions in the design and implementation of the system:

English is the default language and does not need prior internationalization in Catalog. Catalog will not be modified frequently.

Page Flow Figure 2 shows all JCATALOG Pages and the Transitions relationship between them: There are two sets of pubes: Open Internet and intranet for managing, where intranet can only be accessed by those who successfully log in to the system. . ProductSummary does not show users as a separate page, which is displayed in the Frame in the Catalog Page. ProductList is only visible to administrators, which contains links for creating, editing, and deleting products. Figure 3 is a schematic diagram of a Catalog page, in which a detailed schematic of each page should be included in the demand document. The next phase of the architecture Web application development is the architecture design, which includes dividing the application into multiple functional components and segmenting these components into layers, high-level architectural design should be neutralized. Multi-layer architecture multi-layer architecture is clearly divided into multiple functional units: Client, Presentation, Business-Logic, Integration, and EIS, which will ensure a clear division of duties, making the system easier maintenance and expansion. A system with three or more layers is proven to have better scalability and flexibility than the C / S model. The Client layer is a place to use and represent data models. For a web application, the Client layer is usually a browser. The browser-based thin client does not contain any representation logic, it relies on

Presentation

Floor. The Presentation layer demonstrates the Service-Logic service to the user, it should know how to handle the user's request, how to interact with the Business-Logic layer, and know how to select the next view to display to the user. The Business-Logic layer contains the application's Business Objects and Business Services. It accepts requests in the Presentation layer, based on request processing business logic. Business logic layer components will benefit from system-level services such as security management, transaction management, and resource management. Integration layer is between

Business-logic

The bridge between the layer and the EIS layer, which encapsulates logic interact with the EIS layer. Sometimes, the Integration layer and the Business-Logic layer are synamed as an intermediate layer. The application's data is saved in the EIS layer, which includes relational databases, object-oriented databases, and legacy systems. JCATALOG frame design Figure 4 shows the frame design of JCATALOG and how to apply in multi-layer architecture systems. The application uses a multi-layer non-distributed architecture. Figure 4 shows the layering of the system and the technique selected in each layer. It is also a deployment diagram of this example, its Presentation, Business-Logic and Integration layers Exist in the same web container. Defining a good interface will isolate each layer of responsibilities, this architecture makes it easier and better. For Presentation layers, experience shows that the best way is to choose the existing and proven web application framework, rather than yourself to design and develop new frameworks. We have multiple optional frameworks such as Struts, Webwork, and JSF, in JCATALOG, we choose JSF. EJB and POJO can be used to create a business logic layer. If the application is distributed, EJB with the Remote interface is a good choice; because JCATALOG is a typical web application, it is selected to use Pojo, and Take advantage of the help of Spring Framework will be a better choice for the business logic layer. The Integration layer uses the continuous data of the relationship database, there are many ways to implement: JDBC: This is the most flexible approach, however, the low JDBC is difficult to use, and the quality of JDBC code is difficult to operate. Entity Beans: CMP's Entity Bean is an expensive method for separating data access code and handling ORM. It is a way to apply servers, that is, Entity Beans is not constrained with a database type but an EJB container. O / R mapping framework: An ORM framework implements data-centric approach to implement data continuous, and a object-centric application is easy to develop and has a high degree of portability. There are several frames in this field available - JDO, Hibernate, Toplink, and Cocobase. Hibernate will be selected in our example.

Now, we will discuss design issues in each layer, because JSF is a relatively new technology, it will focus on its use:

Presentation

The functionality of the layer and JSF represents the layer of the user's input, display data, control page navigation, and transmits the user's input to the business logic layer, indicating that the layer needs to verify the user's input and the SESSION state of the maintenance application. In the following sections, I will discuss the considerations and patterns of layer design and describe the reasons for selecting JSF as a JCATALOG representation. MVCMVC is a schema design mode recommended by Java-Blueprints, and MVC separates several aspects, thereby reducing the repetition of code, which is controlled centered and makes it more scalable. MVC can help users with different skills more focus on their skills and cooperate with each other by defining a good interface. The MVC is the architecture design pattern of the layer. JSFJSF is the server-side user component framework for web applications. It contains the following API: Indicates the UI component, manages them, processing events, server-side authentication, data conversion, definition page navigation, supports internationalization, and provides extension capabilities for these features . It also includes two JSP TAG libraries to represent UI components in the JSP page, and the component Wire is a server-side object. JSF and MVCJSF are ideal for MVC-based representation layer architecture, which provides a clear separation between behavior and representation, which makes you adopt familiar UI components and web layer concepts without being limited to certain special scripts. Or marker language. JSF BACKING Beans is a MODEL layer of JSF. In addition, it also contains Actions, Action is an extension of the Controller layer, used to delegate the user's request to the business logic layer. Note here, from the overall application framework, the business logic layer is also known as the Model layer. The JSP page containing the JSF tag is the representation of the layer, the Faces Servlet provides the Controller's functionality. Why choose JSF? JSF is more than just another web framework, the following features are the JSF different from other web frameworks:

Object-oriented Web Application Development of class SWING: The server-side UI component model, with Event Listeners and Handlers, facilitates object-oriented web application development. BACKING-BEAN management: The BACKING BEAN is a JavaBean component associated with the UI component used in the page, and the backing-bean management seizes the definition of the UI component object with the application-related processing and the objects of the data. JSF saves and manages these backing-bean instances within a suitable range. Scalable UI Model: The UI model of JSF is configurable, reusable to build a user interface for JSF applications. You can develop more complex components, such as menu strips, tree components, and so on by extending standard UI components. Flexible Rendering Model: Renderer Separates the functionality and display of the UI component, multiple rendrers can create and define different displays for the same client or different clients. Scalable Conversion and Verification Model: Based on standard Converter and Validator, you can develop your own CONVERTER and Validator that provides better model protection.

Despite this, JSF is currently not yet mature, with the COMPONENTS, CONVERS and Validators released by JSF, and the Per-Component verification model cannot process Many-to-Many authentication between Components and Validators. In addition, the JSF tag cannot be integrated with JSTL. In the following chapter, I will discuss several key parts and design decisions in the JCATALOG implementation. I first explain the definition and use of Managed Bean and the BACKING BEAN in JSF, and I will explain how to handle security, pagination, caching, file upload, verification, and error messages customization. Two new beans: Managed Beans and Backing Beans are introduced in Managed Bean, View Object and Domain Object ModelJSF. JSF provides a powerful managed-bean tool, a JavaBean object managed by JSF, called Managed-Bean, and a Managed bean represents how a bean is created and managed, which does not include any functional description of the bean. The Backing Bean defines the properties and processing logic associated with the UI components used in the page. Each backing-bean property is scheduled to a component instance or a Value of an instance. A backing-bean also defines a group of methods for executing component functions, such as verifying data of components, processing components triggered, implementing navigation related to component. A typical JSF application combines each page and a backing-bean, however, in a real application, the relationship of this One-ON-One is not an ideal solution, it may cause the code Repeat and other issues. In real-in-use applications, multiple pages can share a backing-bean, for example in JCATALOG, CreateProduct and EditProduct share the same productBean definition. The Model object is specific to a VIEW object in the layer, which contains data that must be displayed on the View layer and verifying user input, processing events, and processing logic interact with business logic layers. In JSF-based applications, the Backing Bean is a View object, and the BACKING BEAN and VIEW objects are interchangeable nouns. Compare ActionForm and Action in Struts, using the BACKING-BEAN in JSF will be better able to follow object-oriented methods, and a backing-bean contains not only view data, but also related to these data, but in Struts. In, Action and ActionForm include data and logic, respectively. We should have I have heard of Domain Object Model, then what is the difference between Domain Object Model and View objects? In a simple web application, a Domain Object Model can cross all layers, and in complex applications, you need to use a separate View object model. Domain Object Model should belong to the business logic layer, which contains business data and business logic related to a particular business object; a View object contains the data and logic of Presentation-Specific. The disadvantage of separating the View object from the Domain Object Model is that data mapping will occur between the two object models. In JCATALOG, ProductBeanBuilder and UserBeanBuilder utilize Reflection-Based Commons BeanUtils to implement data mapping.

Safety Currently, JSF does not have built-in security features, and for example applications are very basic: users are logged in to Administration intranet only requires only username and password authentication without considering authorization. For JSF certification, there are several ways to use a backing bean: This method is very simple, but it combines the backing bean with special inheritance relationships using JSF's ViewHandler Decorator: This method is safe. The logic is closely related to a specific Web layer technology to use servlet filter: A JSF application is nothing from other web applications. Filter is still the best place to handle authentication checks. In this approach, certification logic and web application Separated

In our sample program, the SecurityFilter class is used to process the user's authentication. At present, protected resources only contain three pages, for simple considerations, the positions are hardcoded into the Filter class. Page the Catalog page in this application requires paging, indicating that the layer can be used to process paging, ie it takes out all the data and saves this layer; paging can also be implemented in the Business-Logic layer, an Integration layer, and even an EIS layer. Since there is no more than 500 products in JCATALOG, all product information can be stored in a USER Session, we put paging logic in the ProductListBean, and the pagination-related parameters will be configured through the JSF Managed-Bean tool. CachingCaching is one of the most important technologies for improving web application performance, and caching can be implemented in many layers in application build. The JSF Managed-Bean tool makes it easy to implement caching in the representation layer. By changing the range of a Managed BEAN, the data contained in this Managed BEAN can be cached in a different range. The two-stage CACHING is used in the sample application. The first level Caching exists in the business logic layer. The CachedCatalogServiceImpl class maintains a read and write cache of all products and directories. Spring is managed as a Singleton Service Bean, so the first-class cache It is an application range read and write cache. In order to simplify the speed of paging logic, the product is also cached to the representation layer in the session range, each user maintains his own ProductListBean, the shortcoming of this method is the memory consumption and data failure problem, in one user In the session, if the administrator changes Catalog, the user will come to the data, however, these shortcomings will be able to endure because the data we assume that the application is not changed. File Upload is not supported in the current JSF Sun Reference implementation of the current UPLOAD. Although Struts has very good File Upload capabilities, you need to use this feature to need a Struts-Faces integration library. In JCATALOG, an image is associated with a product, after a user created a new product, she must upload the corresponding picture, the picture will be saved in the file system of the application server, the product ID is the image name. The File-Upload API of the SEVLET and JAKARTA COMMON is used in the sample application to implement a simple file upload function, which contains two parameters: image path and image upload result page. They will be configured via ApplicationBean. For details, please refer to the FileUploadServlet class. The standard Validator released in ValidationJSF is very basic and cannot meet the needs of reality, but it is easy to develop its JSF Validator. In the example, I developed SelectEMSRANGE Validator, which is used to verify the number of selected in the UISElectrMany component: Details Please refer to the example. Custom Error Information In JSF, you can create resource bundle and custom error information for Converters and Validators, and a resource bundle can create in Faces-Config.xml:

Catalog.view.bundle.Messages

And the key-value of the error message is added to the message.properties file: javax.faces.component.uiinput.conversion = input data is not in the correct type. Javax.facs.component.uiinput.required = Required Value IS Missing Business logic layer and Spring Framework business objects and service services exist in the business logic layer, and a business object not only contains data, but also contains three business objects in the sample application: Product, Category and User. Business services interact with business objects and provide more advanced business logic, you need to first define a formal service interface, which is a service interface that is directly interacting with end users. In JCATALOG, the business logic layer is implemented by POJO with Spring Framework, where there are two business services: CatalogService contains Catalog Management-related business logic, and UserVice contains user management logic. Spring is an IOC concept-based framework, the Spring features used in the sample application include: Bean Management With Application Contexts: Spring can effectively organize our intermediate objects, which can eliminate Singleton's Proliferation and easy to achieve good object-oriented objects Programming method, "programmed to interface". Declarative Transaction Management: Spring uses AOP to implement transaction management without the need to use this method, transaction management can be used in any POJO. Spring's transaction management is not limited to JTA, but can use different transaction policies. In sample applications, we will use the Declarative Transaction Management With Hibernate Transaction. Data-Access Exception Hierarchy: Spring provides a very good exception instead of SQLException, in order to use Spring exception, you must define the following exception conversion in the Spring profile:

In an example application, if a new product with a duplicate ID is inserted, DataintegrityViolationException will be thrown, which will be Catch and RethRown a duplicateProductIdexception. Thus, this exception can be processed with other abnormal distinguishes.

Hibernate Integration: Spring is very good, Spring provides efficient and secure processing for Hibernate Session, which can configure Hibernate's sessionFactories and JDBC data sources via Application Context, and make it easy to test.

Integration layers and HibernateHibernate are an open source ORM framework that supports all mainstream SQL database systems, Hibernate's query language has a very good bridge with a relationship. Hibernate provides powerful features to implement: data read and update, transaction management, data connection pool, query, and entity relationship management, etc. Data Access OjBect (DAO) JCATALOG has a DAO mode, which is abstract and encapsulated all of the data sources, including two DAO interfaces: CatalogDao and Userdao, which implements HibernateCatalogDaoImpl and HibernateUserDaoIMPL contains Hibernate specific Logic to achieve data management and persistence. Implement us now to see how these things discussed together with these things to achieve JCATALOG, you can download the source code from this address: Source Code Database Design We create a database containing 4 tables for this example application, as shown in Figure 5 Screen: Class Design Figure 6 shows the idea of ​​jcatalog class diagram "programmed to interface" runs through the entire design, in the representation, a total of four backing beans: ProductBean, ProductListBean, UserBean, and MessageBean; business logic layers contain two Business Services (CatalogService and Uservice) and three business objects (Product, Category and User); Integration layers have two DAO interfaces and their corresponding Hibernate implementations, Spring's Application Context is used to manage most of the business logic layers and The object of the Integration layer; ServiceLocator integrates the JSF and business logic layers. Wire everything UP Due to the space limit, we will only exemplary, the use case createproduct shows how to assemble and build applications. Before detail, we use the sequence map (Figure 7) to clear all layers end-tp-end. Integration. Indicates the layer: The representation layer implementation includes creating a JSP page, defining page navigation, creation, and configuring backing beans, and integrating JSF with business logic layers. JSP Page: CREATEPRODUCT.JSP is used to create a new product page, which contains the UI component and packages the component to verify the number of types selected by the user, and at least one of the products is selected.

Page Navigation: Navigation in Applications Defined in Application Faces-Navigation.xml, the navigation criterion of CreateProduct is as follows:

*

CreateProduct

/createproduct.jsp

/createproduct.jsp

Success

/uploadImage.jsp

Retry

/createproduct.jsp

Cancel

/productlist.jsp

BACKING BEAN: ProductBean not only contains the properties of the UI component that maps the data to the page, but also includes three action: cretection, editAction, and deletection, the following is the code of the CreateAction method:

Public string creageAction () {

Try {

Product Product = ProductBeanBuilder.createProduct (this);

// save the product.

This.ServiceLocator.getCatalogService (). SaveProduct (product); // Store The Current Product ID Inside The Session Bean.

// for the use of image uploader.

FaceSUTILS.GetSessionBean (). SetCurrentProductId (this.id);

// Remove the productlist inside the cache.

This.logger.debug ("Remove ProductListBean from Cache");

FaceSUTILS.RESETMANAGEDBEAN (beannames.product_list_bean);

} catch (duplicateproductidException de) {

String msg = "Product ID Already EXISTS";

This.logger.info (msg);

FaceSUTILS.ADDERRORMESSAGE (MSG);

Return NavigationResults.Retry;

} catch (exception e) {

String msg = "Could Not Save Product";

This.logger.error (MSG, E);

FaceSUTILS.AdderrorMessage (MSG ": Internal Error");

Return navigationResults.failure;

}

String msg = "Product with ID of" this.id "WAS CREATED SUCCESSFULLY."

This.logger.debug (msg);

FaceSUTILS.Addinfomessage (MSG);

Return navigationResults.success;

}

Managed-bean statement: ProductBean must be configured in JSF configuration files, Faces-Managed-bean.xml:

BACKING Bean That Contains Product Information.

ProductBean

Catalog.view.bean.productbean

REQUEST

id

# {param.ProductId}

ServiceLocator

# {serviceLocatorBean}

Represents the integration between layers and business logic layers: ServiceLocator abstracted logic of finding services, in example applications, ServiceLocator is defined as an interface, which is implemented as a JSF's Managed Bean, ServiceLocatorBean, which will be in Spring Application Looking for services in Context:

ServletContext Context = FaceSUTILS.GetServletContext ();

THIS.AppContext = WebApplicationContextUtils.getRequiredWebApplicationContext (CONTEXT);

THIS.CATALOGSERVICE = (catalogservice) this.lookupservice (catalog_service_bean_name);

This.userService = (userService) this.lookupservice (user_service_bean_name); business logic layer

Business object: Since Hibernate provides persistence, both Product and Category business objects need to provide Getter and Setter for all of them.

Business Services: All Catalog Management Related services are defined in the CatalogService interface:

Public interface catalogservice {

Public Product SaveProduct (Product Product) Throws CatalogException;

Public Void UpdateProduct (Product Product) Throws CatalogException;

Public void deleteProduct (Product Product).

Public Product Leptuct (String Productid) Throws CatalogException;

Public Category Getcategory (String CategoryId) THROWS CATALOGEXCEPTION;

Public List GetAllProducts () THROWS CATALOGEXCEPTION;

Public List GetAllcategories () THROWS CATALOGEXCEPTION;

}

Spring Configuration: Here is the Spring configuration of CatalogService:

Propagation_Required, Readonly

Propagation_required

Propagation_required

Propagation_required

Spring and Hibernate Conception: The following is the configuration of HibernateSessionFactory:

<-! Hibernate SessionFactory Definition -> catalog / model / businessobject /Product.hbm.xml catalog / model / businessObject / category.hbm.xml catalog / model / businessobject / user.hbm.xml net.sf.hibernate.diaalect.mysqldiaalect True < / prop> true net.sf.hibernate.cache.HashtableCacheProvider < / property> CatalogDao uses HibernateTemplate to integrate between Hibernate and Spring. Here's the configuration for HibernateTe Mplate:

The Integration Layer Hibernate maps the business object and the relational database through the XML configuration file. In JCATALOG, Product.hbm.xml represents the mapping of the Product object, category.hbm.xml is used to represent Category mappings, product.hbm.xml is as follows :

CatalogDao IS Wired with hibernateTemplate by Spring: Hibernate Implementation ->

转载请注明原文地址:https://www.9cbs.com/read-112802.html

New Post(0)