Using Open Source Product Assembly Your web application architecture (Struts + Spring + Hibernate)

zhaozj2021-02-16  83

In fact, even if you use Java, it is not a very cumbersome web application, nor is a relaxed thing. There is a lot of things to consider at the beginning of the architecture. From the height, there are many problems in front of the developer: How do you think about how to build a user interface? Where to deal with business logic? How to persist. In this three-layer architecture, each layer has them to carefully consider. What technology should be used in each layer? What kind of design can loose coupling and flexible change? How to replace a layer without affecting the overall architecture? How do applications do all levels of business processing (such as transaction processing)? Building a web application needs to understand many questions. Fortunately, many developers have already encountered such problems and have established a framework for processing such issues. A good frame has the following points: Reduce the burden of developers' handling complex problems ("Do not repeat the invention"); there is a good extension within; and there is a powerful user group that supports it. Good architecture generally targeted a certain type of problem and can do it well (Do One Thing Well). However, several layers in your program may need to use a specific framework, the completed UI (user interface) does not mean you can also couple your business logic and persistent logic to your UI section. For example, you should write JDBC code as your business logic in a Controller (Controller), which is not the controller. A UI controller should delegate other lightweight components that are given to the UI range. A good frame should be able to guide the code how to distribute. More importantly, the framework can liberate developers from the encoding, so they can concentrate on the logic of the application (which is important to customers). This article will discuss how to combine several famous frameworks to make your application relax. How to build your architecture and how to keep your application layers consistent. ? How to integrate the frame to allow each layer to work with each other with a loose coupling without tube low-level technical details? This is really a challenge for us. Here, discussing a strategy of integrated framework (using three popular open source frames): Standby We use struts; business strata us with Spring; while persistence is used. You can also replace other Framework as long as you get the same effect. See Figure 1 (Framework Schematic) Application Most web applications can be divided into 4 layers in terms of responsibilities. These four layers are: Presentation, Persistence, Business (Business) and Domain Model. Each layer should have a clear responsibility on the handler, and should not be mixed with other layers, and each layer is separated from other layers, but to put a communication interface between them. We started from the introduction of each layer, discuss what these layers should provide, and should not provide anything. The presentation layer is generally, and the end of a typical web application should be a layer. Many Java senters also understand Struts. I am packed to org.apache.struts.action as a business logic. Therefore, we agree with a framework such as Struts. The following is the Struts responsible: * Manage the user's request to make a corresponding response. * Provide a Controller to delegate the business logic and other upper-level processing. * Handling exception, throwing Struts Action * For display, providing a model * UI verification. The following provisions should not appear in the coding of the Struts display layer. They are independent of the display layer.

* Communication with databases, such as JDBC calls. * Business logic and verification associated with your application. * Things management. In the representation layer introduces these code, it will bring high coupling and trouble maintenance. Another end of the typical web application of the Persistence Layer is a persistent layer. It is usually the easiest way that the program is most likely to be out of control. Developers always underestimate the challenge of building their own persistent framework. The continuity layer inside the system not only requires a large amount of debugging time, but also the lack of functionality makes it difficult to control, which is a common problem of persistent layers. Also, there are several ORM open source frameworks to solve such problems. Especially hibernate. Hibernate provides Java with OR persistence mechanisms and query services, which also gives a Java developer who is familiar with SQL and JDBC API, and it is very convenient to learn. Hibernate's persistent object is based on Pojo and Java Collectes. In addition, using Hibernate does not hinder your Ide you are using. Please see the entry below, you need to understand in the persistent layer code. * Query the relevant information of the object's information. Hibernate completes the query through an OO query language (HQL) or the regular expression of the API. HQL is very similar to SQL - just replacing the table and columns in SQL with objects and its fields. You need to learn some new HQL languages; no matter what, they are easy to understand and the documentation is also very good. HQL is a natural language of an object query, which can learn it at a small cost. * How to store, update, delete database records. * Advanced ORM frames like Hibernate support most mainstream databases, and they support Parent / Child relationship, things handling, inheritance, and polymorphism. The Business Layer is a typical web application is a business layer or a service layer. From the perspective of the coding, this layer is the most easily ignored. And we often see the code for these business processing around the UI layer or persistent layer, which is actually incorrect because it leads to a close couch of the program code, so that these code is difficult to maintain over time. Fortunately, there are several Frameworks to exist for this issue. The most popular framework is Spring and PicoContainer. These are also known as MicroContainers, they can make you look good. These two frames have a simple concept of 'Dependency INJECTION (also we know' control reversal 'inversion of control = ioc). This article will focus on Spring's injection (translation: Through a setter method of a given parameter, it is different from factory, and Spring also provides setter incjection (type2), constructor inject (Type3) to we select. Spring puts the Objects, such as Transaction Management Handler, such as Transaction Management Handler, Object Factoris, Service Objects, and Service Objects, Service Objects, and Service Objects. Behind we will give an example to reveal how Spring uses these concepts. The business layer is responsible for the following: * Processing the application's business logic and business check * Manage things * Allow interfaces that interact with other layers * to manage the dependence of the business layer level. * Add a flexible mechanism between the display layer and the persistence layer, so they do not directly link together. * BUSINESS SERVICES is obtained by revealing context from the display layer to the business layer.

* The execution of the management program (from the business layer to the persistence layer). The Domain Model Layer Since we are committed to an application that is not a very complex web, we need an object collection that allows it to move between different layers. The domain module layer consists of a business object in the actual requirement, such as ORDERLINEITEM, PRODUCT, and more. Developers don't have to manage those DTOs in this layer, only pay attention to Domain Object. For example, Hibernate allows you to put information in the database into the domain objects so you can display these data to the UI layer without disconnection. And those objects can also be returned to the continuous layer to update in the database. Moreover, you don't have to convert the object into DTOS (this may be lost in the transmission process between different layers), this model makes Java developers to use OO without the need to encode. A simple example is since we have already understood these components from globally. Let us start practice now. We still use struts, Spring and Hibernate. These three frameworks have been described enough, and they will not be repeated here. This article example guides you how to use these three frameworks to integrate development and reveal how a request runs through each layer. (Add an ORDER to the database from the user, display; and then update, delete). From here you can download to the program program original code (Download) Since each layer is mutually effect, we will first create Domain Objects. First, we must determine those of these objects to be persistent and which are provided to Business Logic, those are the design of the display interface. Next, we will configure our persistence layer and define Hibernate or mappings. Then define business objects. With these components, we will connect them with Spring. Finally, we offer Spring a persistent layer, from this persistence we can know how it communicates with the Business Service Layer, and how it handles other layers thrown. . Domain Object Layer This layer is encoded, and our coding begins with this layer. In the example, ORDER and OrderItem are one one-to-many relationship. Below is the two objects of Domain Object Layer: · com.meagle.bo.order.java: Contains an ORDER's profile information · com.meagle.bo.orderLineItem.java: How to consider the details of the order, how to consider you Package is named, this reaction is delayed. For example, Domain Objects may be packaged in com.meagle.bo in the program. A more detailed one will be packaged below the sub-directory of com. Meagle.bo. Business logic should be packaged from com.meagle.Serice, while the DAO object should be in com.meagle.service.dao.hibernate. The PRESentation Classes of Forms and Actions should be placed separately in com.meagle.action and com.meagle.forms. Accurate giving your package makes your Classes very segmented and easy to maintain, and when you add new classes, you can keep up and down on the program structure.

The persistence layer configured to establish a persistence layer of Hibernate requires several steps. The first step allows us to persist BO. Since Hibernate is working through Pojo, the ORDER and ORDERLINEITEM objects need to add Getter, setter methods to all Files. Hibernate mapping (OR) objects via an XML file, the following two XML files map ORDER and ORDERITEM objects, respectively. (Here is a XDoclet tool to automatically generate your XML image) - Order.hbm.xml - ORDERLINEITEM.HBM.XML You can find these XML files in a webcontent / web-inf / class / com / meagle / bo directory . Hibernate's [URLHTTP: //www.hibs/api/net/sf/Hibernate/sessionFactory.html] sessionFactory [/ url] is used to tell the program to communicate with which database, which connection pool or use DataSource, which persistent objects should be loaded. The Session interface is used to complete these operations for Selecting, Saving, Delete, and Updating. Behind us will explain how SessionFactory and Session are set. Business Layer Configuration, Since we already have Domain Objects, we have to ask Business Service Objects, use them to execute the program's logic, call the persistence layer, get the UI layer Requests, process Transactions, and control Exceptions. In order to connect these and easy to manage, we will use aspective SpringFramework. Spring provides control inversion (Inversion of Control 0 == IOC) and SETTER Dependency Injection (optional), connects objects with an XML file. IOC is a simple concept (it allows an object to be created in the upper layer), using IOC to release your object from the creation, reducing coupling. Here is an example of an object that does not use IOC, which has a high coupling. Figure 2. No IOC. A creates B and C, which is an example using IOC, which allows objects to be created and entered on the high layer, so this can be directly executed. Figure 3. Objects use IOC. A contains the setter method of accepting B, C, which also achieves the purpose of creating B, C by A. Establish our business service object (Building Our Business Service Objects Business Object) The setter method accepts the interface so that we can define object implementations very loose, and then inject. In our case, we will use a Business Service Object to receive a DAO, use it to control the persistence of Domain Objects. Since Hibernate is used in this example, we can easily use other persistent frameworks to notify Spring Spring has new DAOs. In the interface-oriented programming, you will understand how the "Injection Dependence" mode is loosely coupled to your business logic and persistent mechanism :).

The following is an interface business service object, DAO snippet: Code: public interface IOrderService {public abstract Order saveNewOrder (Order order) throws OrderException, OrderMinimumAmountException; public abstract List findOrderByUser (String user) throws OrderException; public abstract Order findOrderById (int id) THROWS Orderyxception; Public Abstract Void Setorderdao (iorderdao OrderDao);

Note that there is a setOrDao () in this code, it is a DAO Object setting method (syringe). But there is no way to getORDAO, this is not necessary, because you will not access this ORDERDAO outside. This Dao ObjectE will be called, and communicate with our Persistence Layer. We will use Spring to match Dao Object and Business Service Object. Because we are interface-oriented, it is not necessary to couple the category coupled together. Next, we start our DAO implementation class for encoding. Since Spring has supported Hibernate, this example directly inherits the Hibernatedaosupport class, this class is useful, we can refer to HibernateTemplate (it is mainly a use of HibernatedAosupport, the translation: You can view the Srping API). Here is this DAO interface code:

Code: public interface iorderdao {public intend oredioterbyid (final int id); public string placedBy; public Abstract Order SaveOrder (Final Order Order);

We still have to assemble a lot of associated objects to our persistent layer, which contains HibernateSessionFactory and TransactionManager. Spring provides a HibernateTransactionManager, which is bundled with a hibernate session using it to support Transactions (see threadlocal). Here is the configuration of HibernateSessionFactory and HibernateTransactionManager:

Code: COM / meage / bo / order.hbm.xml COM / meage / bo / orderlineItem.hbm.xml NET . Sf.hibernate.dialect.mysqldiaalect false Spring

It can be seen that each object can be referenced in the Spring configuration information. Here, MySessionFactory references HibernateSessionFactory, and MyTransactionManager references HibernateTransactionManage. Note that the MyTransactionManger Bean in the code has a sessionFactory property. HibernateTransactionManager has a SessionFactory Setter and getter method, which is used to implement "dependency injection" when Spring starts. Quote MySessionFactory in the SessionFactory property. These two objects were assembled after the Spring container was initialized. Such a match allows you to liberate from the Singleton Objects and Factories, which reduces the maintenance cost of the code. The two properties of MySessionFactory. are used to inject mappingResources and HibernateProperties. Usually, if you use Hibernate outside Spring, such settings should be placed in hibernate.cfg.xml. In any case, Spring provides a convenient way ----- In the Spring internal configuration, it has entered the configuration of Hibernate. If you want more information, you can check the Spring API. Since we have already assembled service beans, you need to assemble Business Service Object and Dao and distribute these objects to a transaction manager. Configuration information in Spring:

Code: <-! ORDER SERVICE -> < / property> PROPAGATION_REQUIRED, readOnly, -OrderException propagation_required, -orderexception

UI layer configuration (UI layer configuration) This example uses Struts framework. Here we have to explain when giving the program hierarchical, which is part of the Struts. Let's start with the configuration information of Action in a struts-config.xml file. Code: struts-config.xml file. save new order

SAVENEWORDER This action is used to persistence of forms submitted over the UI layer. This is a typical action in Struts; pay attention to observing the Exception configuration in this action, which is also configured in the spring profile (ApplicationContext-Hibernate.xml) (in the Business Service Object TransactionAttributes properties). When an exception is thrown at the business layer, we can control them and display it appropriately to the UI layer. The first exception, ordexception, is triggered when the lasting layer saves the ORDER object failed. This will cause things to roll back and pass abnormally to the Struts by BO. The second exception, ORDERMINIMUMAMOUNTEXCEPTION is also the same as the first one. The final step of matching is to combine your display layer and business layer. This has been implemented by the Service Locator (the previous discussion), where the service layer is provided to our business logic and persistence layer as an interface. SAVENEWORDER Action Calls the execution business method in Struts. The method code is as follows:

Code: public ActionForward execute (ActionMapping mapping, ActionForm form, javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws java.lang.Exception {OrderForm oForm = (OrderForm) form; // Use the form to build an Order object that // can be saved in the persistence layer. // See the full source code in the sample app. // Obtain the wired business service object // from the service locator configuration // in BaseAction. // Delegate the save to the service layer and // further upstream to save the Order object getOrderService () saveNewOrder (order);.. oForm.setOrder (order); ActionMessages messages = new ActionMessages (); messages.add (ActionMessages.GLOBAL_MESSAGE, New ActionMessage ("message.Order.saved.success,"); saveMessages (Request, Messages); Return mapping.findforward ("Success");}

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

New Post(0)