Using Open Source Product Assembly Your web application architecture

xiaoxiao2021-03-06  88

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 (Schematic of Framework)

Title of application

Most of the web applications can be divided into 4 layers in their duties. 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 PRENTATION LAYER

In general, 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.

Below 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.

* Treatment exception, throw Struts Action

* Provide a model for display

* 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.

THE PERSISTENCE LAYER

Another end of a typical web application 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.

Business Layer

The intermediate portion of 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:

* Handling the business logic and business verification of the application

* Management

* Allow interfaces that interact with other layers

* Manage the dependence of the target of the business layer.

* 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).

Domain Mode Block (THE DOMAIN Model Layer)

Since we are committed to an application that is not a very complex web, we need an object collection 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

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 interacting, 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, our coding begins with this layer. In the example, ORDER and OrderItem are one one-to-many relationship. Here is two objects of Domain Object Layer:

· Com.meagle.bo.order.java: Contains a summary information of an Order

· Com.meagle.bo.orderLineItem.java: Contains details of ORDER

Consider how your package is named, this reaction is how you are layered. 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. Persistence Layer Configuration

It takes several steps to establish a persistence of Hibernate. 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 sessionFactory is used to tell the procedure to communicate with which database communication, which connection pool or uses 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 will want business service objects, use them to execute the program's logic, call the persistence layer, get the requests of the UI layer, 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

Here is an example of 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)

The setter method in Business Object 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 :).

Here is an interface business service object, DAO code snippet:

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 Orderexception;

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:

Public interface iorderdao {

Public Abstract Order Findorderbyid

Final Int ID);

Public Abstract List FindordersplaceByuser

Final String PlacesDBY;

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:

Class = "org.springframework.orm.hibernate.localsessionFactoryBean">

COM / meage / bo / order.hbm.xml

COM / MeAgle / Bo / OrderLineItem.hbm.xml

Net.sf.hibernate.Dialect.MysqldiaLect

False

C: / myWebapps /.../ Web-inf / proxool.xml

Spring

SessionFactory (Alternative to JTA) ->

Class = "ORG.

Springframework.

ORM.

Hibernate.

HibernateTransactionManager ">

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:

Class = "ORG.

Springframework.

TRANSACTION.

Interceptor.

TransactionProxyFactoryBean>>

Propagation_Required, Readonly, -OrdeRexception

Propagation_Required, -OrdeRexception

Hibernate IMplementation ->

Class = "com.meagle.

SERVICE.

Spring.

ORDERSERVICESPRINGIMPL ">

Class = "COM.

Meagle.

SERVICE.

DAO.

Hibernate.

ORDERHIBERNATEDAO ">

Figure 4 is an outline of our objects. As can be seen, each object is contacted Spring and can be injected into other objects via Spring. Compare it to the Spring profile, observe the relationship between them

Figure 4. Spring is based on the configuration file, set each bean together.

This example uses a TransactionProxyFactoryBean, which defines a setTransactionManager (). This object is useful, he can very convenient to deal with what you declared, there is Service Object. You can define how to deal with the TransactionAttributes property. Want to know more or refer to TransactionAttributeEditor.

TransactionProxyFactoryBean has a setter. This will be referenced by our Business Service Object (ORDERTARGET), and the ORDERTARGET defines the business service layer, and it also has an attribute, referenced by setorderdao (). This property

Spring and beans have to pay attention to: beans can be created in two ways. These are all defined in single case mode (SINGTON) and prototype modes. The default approach is Singleton, which means that the shared instance will be bound. The prototype mode allows new instances to be created when Spring uses Beans. When each user needs to get the copy of their own bean, you should only use Prototype mode. (For more, please refer to the single example and prototype mode in the design mode) Provide a service locator (providing a service locator)

Since we have set our Services and DAO. We need to display our service to other layers. This is usually encoded in Struts or Swing. A simple method is to return to Spring Context with the service locator. Of course, you can do it by calling beans in Spring directly.

Below is an example of a service locator in a struts actin.

Public Abstract Class baseAction extends action {

Private iorderservice OrderService;

Public void setServlet (ActionServlet

ACTIONSERVLET) {

Super.setServlet (ActionServlet);

ServletContext servletContext =

ActionServlet.getServletContext (); WebApplicationContext Wac =

WebApplicationContextUtils.

GetRequiredWebapplicationContext

servletContext);

this.orderService = (iorderservice)

Wac.getbean ("ORDERSERVICE");

}

Protected iorderservice getorderService () {

Return ORDERVICE;

}

}

UI layer configuration (UI Layer Configuration)

This example uses Struts framework. Here we have to talk about the Struts section when we are giving the program. Let's start with the configuration information of Action in a struts-config.xml file.

Struts-config.xml file.

TYPE = "com.meagle.action.saveorderDerction"

Name = "Orderform"

Scope = "request"

Validate = "True"

INPUT = "/ neworder.jsp">

Save New Order

PATH = "/ neworder.jsp"

Scope = "request"

TYPE = "com.meagle.exception.orderexception" />

PATH = "/ neworder.jsp"

Scope = "request"

TYPE = "COM.

Meagle.

EXCEPTION.

OrderminimumAmountException "/>

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:

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 what

// 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 = new actionMESSAGES ();

Messages.add (

ActionMessages.global_message,

New ActionMessage

"message.Order.saved.successful"));

SaveMessages (Request, Messages);

Return mapping.findforward ("Success");

}

to sum up

This article covers a lot of low-level basic information in technology and architecture, and the main intention of the article is to let you realize how to lay a layering for your application. The hierarchy can "decouple" your code - allowing new components to be added, and your code is easy to maintain. The techniques used here are only focused on the "decidentity". In any case, use such an architecture allows you to replace the current layer with other techniques. For example, you may not use Hibernate to implement persistence. Since you are programming in the DAO, you can use iBatis instead. Alternatively, you may also want to replace the current UI layer with other techniques or frames outside Struts (conversion long, the realization layer should not directly affect your business logic and business service layer). Built your web application with an appropriate frame, in fact, it is not a cumbersome work, more mainly it "decoupled" all layers in your program.

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

New Post(0)