Lightweight J2EE Development Based on Struts + Spring + Ibatis

xiaoxiao2021-03-06  43

Lightweight J2EE Development Based on Struts Spring Ibatis

content:

1. Preface 2. JPETStore Brief 3. Reconstruction of JPETSTORE 4. Conclusion Reference Information About the author's evaluation of this article

subscription:

DeveloperWorks News DeveloperWorks Subscribe (Subscribe CD and Download)

Wu Peak

(Shuwgf@21cn.com) Changde Cigarette Factory Information Technology in February 2005

JPETSTORE 4.0 is the latest sample program for IBATIS, based on the Struts MVC framework (Note: non-traditional Struts development mode), with iBATII as a persistent layer. The sample program is elegant, clear, can learn and as a high efficiency programming model. Based on the basis, Spring is used to modify its intermediate layer (business layer). Make the development of further reduced, and there are some benefits of Spring ...

1. Preface JPETSTORE 4.0 is the latest sample program for iBATIS. Ibatis is an open source lasting layer product, including SQL Maps 2.0 and Data Access Objects 2.0 framework. The JPETSTORE sample program is very good to show how to use iBATIS to develop a typical J2EE web application. The JPETSTORE has the following features:

IBATIS data layer POJO business layer POJO domain Struts MVC JSP representation The following is the key technologies used in this article, this article assumes that you have a certain understanding of Struts, SpringFrameWok, Ibatis, if not, please refer to the reference in appendix first. .

Struts is the king that is currently not struggling in the Java Web MVC framework. After five years of development, Struts has gradually grown into a stable, mature framework, and accounts for the largest market share in the MVC framework. But Struts has been lagging behind emerging MVC frameworks. In the face of Spring MVC, WebWork2 is more accurate and more scalable, and Struts has received unprecedented challenges. But standing on product development perspectives, Struts is still the most secure choice. The prototype of this article JPETSTORE 4.0 is based on Struts, but the traditional fixed use of Struts is not crusting, for example, only a custom Action class, and is also groundbreaking on the definition of the Form Bean class, it is refreshing, slightly After the specifically analyzes. Spring Framework is actually a specific implementation of the design idea described in Expert One-ON-One J2EE Design and Developments. Spring framework features a lot. A few parts of AOP, ORM, DAO, CONTEXT, Web, MVC, etc. Web, MVC is not considered, JPETStore 4.0 uses more mature struts and jsp; DAO is not considered due to the popularity of Hibernate, JDO, Ibatis, JPETSTORE 4.0 is IBATIS. So the most needed is AOP, ORM, and Context. In Context, the most important thing is BeanFactory, which can separate the interface and implementation, very powerful. The current AOP application is most mature or in transaction management. iBATIS is a powerful practical SQL MAP tool, which is different from other ORM tools (such as hibernate), which is mapped to the Java object, and for ORM tools, its SQL statement is generated based on mapping definitions. IBATIS provides greater free space for system design with SQL development workload and database graft. With IBATIS code generated, you can automatically generate iBATIs code according to DDL, which can reduce a lot of workload. 2. JPETSTORE Brief Description 2.1. The background was originally Sun J2EE PetStore, its most important purpose is to learn J2EE, but its shortcomings are also obvious, it is over-design. The Oracle then compares the performance of each application server with J2EE PetStore. Microsoft launched PET SHOP based on the .NET platform for competition J2EE PetStore. JPETSTORE is a modified Struts-based lightweight frame J2EE web application, compared to the JPETStore design and architecture, and all layers are clear, using a lot of best practices and patterns, avoiding a lot of "reverse models" For example, embed the SQL statement in the Java code, store HTML in the database, and so on. The latest version is JPETSTORE 4.0. 2.2. JPETSTORE development of operational environments 1. Development Environment Java SDK 1.4.2 Apache Tomcat 4.1.31 Eclipse-SDK-3.0.1-Win32 HSQLDB 1.7.2 2, Eclipse plugin

EMF SDK 2.0.1: Eclipse modeling framework, Lomboz plug-in, you can use the Runtime version. Lomboz 3.0: J2EE plugin, used to develop J2EE applications in Eclipse Spring IDE 1.0.3: Spring Bean Configuration Management Plugin XMLBuddy_2.0.10: Edit XML, use the free version of TomcatPluginv3: Tomcat Management Plugin Properties Editor: Edit Java Attribute file, and you can preview and automatic storage to Unicode format. Free troubles from manual or Ant call Native2ASCII. 3, Example Source Program IBATIS Sample Program JPETSTORE 4.0 http://www.ibatis.com/jpetStore/JPetStore.html Retrofit Source Sequence ( Spring) 2.3. Architecture Figure 1 JPETSTORE Schematic Figure 1 is JPETStore Architecture diagram, more detailed content, please refer to the juedStore's white paper. Referring to this architecture, let us analyze the source code and draw the specific implementation map of JPetStore 4.0 (see Figure 2), and suddenly suddenly open. The non-traditional Struts development model mentioned in the preface is the key on the Struts Action class and the Form Bean class. The Struts Action class has only one: beanaction. Yes, it is really one! Different from traditional Struts programming. Recuely study the BeanAction class, found that it is actually a general class, using the reflection principle, which is determined which method to call the FORMBEAN according to the URL. BeanAction greatly simplifies Struts programming mode, which reduces Struts dependencies (several classes related to Struts and Web containers are placed under the com.ibatis.struts package, and other classes can be reused). With this model, we will easily transplant it to new frames such as JSF, Spring. This is transferred to the Form Bean, it is not the form bean in the ordinary sense. View the source code, you can see that it has not only data and verification / reset methods, but also has behavior, from this sense, it is more like a BO (Business Object). This is what talked before, the BeanAction class uses the principle of reflection, and determines which method of calling the form bean according to the URL (behavior). The signature of these methods of form beans is simple, for example:

Public string myActionMethod () {

//..work

Return "Success";

}

The return value of the method is directly the string, the corresponding is the name of Forward, and no longer an actionforward object, the task of creating an ActionForward object has been processed by the Beanction class. In addition, the program also provides an ActionContext tool class, which encapsulates the data access operations in Request, Response, Form Parameters, Request Attributes, Session Attributes, and Application Attributes, simple and threaded, and the Form Bean class uses the tool class. Further decoupling from the performance layer frame. It is important to point here that the BeanAction class is a useful attempt to expand the Struts, although it provides a very good application development mode, but it is still very new, it has been developing. Figure 2 JPETSTORE 4.0 implementation 2.4. Code analysis Next, let us begin further analysis of the source code of JPETSTORE4.0, paving the following. Beanaction.java is the only Struts Action class, located under the com.ibatis.struts package. As in the above, it is a general control class that utilizes a reflective mechanism to transfer control to a method of form bean. The detailed process refers to its source code, which is simple and clarity. The Form Bean class is located under the com.ibatis.jpetstore.presentation package, and the naming rule is *** bean. All the Form Bean class is inherited in the BaseBean class, and the BaseBean class actually inherits to Actionform, so the Form Bean class is automatically populated by the Struts framework attribute data. In fact, JPETSTORE4.0 extends the application in Struts: The Form Bean class also has behavior, more like a BO, and its behavior (method) is called by the beanaction as a struts-config.xml URL. Even so, we still position the Form Bean class in the performance layer. There are three mapping methods in the configuration of Struts-Config.xml to tell BeanAction to handle which method of rotating to which Form bean object. Connect to this request http: //localhost/jpetstore4/shop/ViewOrder.do 1. URL PATTERN

Name = "Orderbean" Scope = "session"

Validate = "false">

In this way, the control will be forwarded to the "Vieworder" method (behavior) of the "OrderBean" FORM BEAN object. The method name is "/" the last part of "/" with the "path" parameter. 2. Method parameter

Validate = "false">

In this way, the control will be forwarded to the "Vieworder" method (behavior) of the "OrderBean" FORM BEAN object. The "Parameter" parameter in the configuration represents the method on the Form Bean class. The "parameter" parameter takes precedence over the "Path" parameter. 3. No Method Call

Name = "Orderbean" parameter = "*" scope = "session"

Validate = "false">

This method is represented that there is no method to be called on the Form Bean. If there is a "name" attribute, Struts fills the data into the Form Bean object, forward the control to "Success". Otherwise, if Name is empty, forward directly to "Success". This is equivalent to the function of the Struts built-in org.Apache.Struts.Actions.ForwardAction

Parameter = "/ Order / vieworder.jsp" scope = "session" validate = "false">

The Service class is located under the com.ibatis.jpetstore.Service package belongs to the business layer. These classes encapsulate business and corresponding transaction control. The Service class is called by the Form Bean class. The class under the com.ibatis.jpetstore.Persistence.iface package is a DAO interface, which is a business layer that shields the underlying database operation, which is called for specific service classes. The DAOCONFIG class is a tool class (DAO factory class), the Service class obtains the corresponding DAO interface through the DAOCONFIG class, without having to care about the specific database operation of the underlying, implements decoupling in FIG. 2 {coupling 2}. The class in the com.ibatis.jpetstore.Persistence.sqlmapdao package is the specific implementation of the corresponding DAO interface, and iBatis is used in JPETSTORE4.0 to implement ORM. These implementations inherit the BaseSQLMAPDAO class, while the BaseSQLMAPDAO class inherits the SQLMAPDaTemplate class in the iBATIS DAO framework. Ibatis's configuration file is stored in the com.ibatis.jpetstore.Persistence.sqlmapdao.sql directory. These classes and profiles are located in the com.ibatis.jpetstore.domain packet located in the data domain Domain class, which is ordinary JavaBean. It is used here as a data transmission object (DTO), through the view layer, the service layer, and the data layer for transmitting data between different layers. The remaining part is relatively simple, please see the specific source code, very clear. 2.5. The key to JPETSTORE4.0 that needs to be transformed is on the Struts Action class and the Form Bean class, which is one of its essence (although this implementation is experimental, to be expanded and verified), in this transformation we want Keep down, that is, the control layer does not change, the performance layer gets the way the corresponding business class has changed (to load the Spring environment), and the other remains unchanged. The change in particular attention is that the business layer and persistence layer are lucky. The JPETSTORE4.0 is very well design, which is very small, and it can be followed by the mode, as follows: 1. The business layer and the data layer use Spring BeanFactory mechanism management. 2. The business of the business layer is done by the Spring's AOP. 3. Form bean Gets the business class to achieve a custom factory class to implement (loading the Spring environment). 3. JPETSTORE Transformation 3.1. After the transformation, the red portion is part of the increased portion, and the blue part is part to modify. Let us take one by one. 3.2. Spring Context Load To load Spring Context in Struts, the last added part of Struts-Config.xml is usually added:

Value = "/ Web-inf / ApplicationContext.xml" />

Spring is designed to take into account synergy with Struts, providing a good combination point between the two Struts Plug-in between the two. However, because we don't change the JPETSTORE's control layer (this is one of the essences of JpetStore4.0), this article is not prepared to load ApplicationContext. We use the Spring Framework's BeanFactory mechanism, use custom tool classes (Bean factory class) to load Spring profiles, which can see how spring is more flexible, it provides a variety of different ways to use different ways Part of / hierarchy, you only need to use it, you can use it without need. Specifically, the CustomBeanFactory class is created under the com.ibatis.spring package, and the Spring profile ApplicationContext.xml is also placed in this directory. The following is all code of this class, it is very simple: public final class custombeanfactory {

Static xmlbeanfactory factory = NULL;

STATIC {

Resource is = new

InputStreamResource (CustomBeanfactory.class.getResourceceAsStream ("ApplicationContext.xml));

Factory = new xmlbeanfactory (IS);

}

Public static Object getBean (String Beanname) {

Return Factory.getBean (BeanName);

}

}

In fact, it is to encapsulate Spring's XMLBeanFactory, and Spring's profile only needs to be loaded once. You can use CustomBeanFactory.getBean ("Somebean") (for example, SomeBean) without knowing specific class. CustomBeanFactory class is used for decoupling of {coupling 1}. The CustomBeanFactory class is only used by the Form Bean object for the performance layer. Because we didn't configure the Form Bean object in ApplicationContext.xml. However, why not configure the Form Bean class of the performance layer, so you don't need this CustomBeanFactory, Spring helps us create everything you need? The answer to the question is that the Form Bean class is the ActionForm class of Struts! If you are familiar with Struts, you will know that the Actionform class is Struts automatically created: In a request, Struts determines that if the ActionForm instance does not exist, create an ActionForm object, save the form data submitted to the Actionform object. Therefore, the object of the FormBean class cannot be created by Spring, but the Service class and the DAO class of the data layer can, so only they are configured in Spring. So, very natural, we created the CustomBeanFactory class to connect struts and Spring in the performance layer. It is as simple as the decoupling of {coupling 1} in another way. 3.3. The performance level is analyzed that struts and springs are connected in the performance layer, then the performance layer is to make a slight change, that is, the object of the required service class is created. Take the AccountBean class of the performance layer as an example: the original source code is the following private static final accountservice accountservice = accountservice.getInstance ();

Private static final catalogservice catalogservice = catalogservice.getInstance ();

The source code after the transformation is as follows

Private static final accountservice accountservice = (AccountService) CustomBeanFactory.getBean ("AccountService");

Private static final catalogservice catalogservice = (catalogservice) CustomBeanFactory.getBean ("CatalogService");

Other Several Presentation classes are modified in the same manner. In this way, the expression layer is completed. Regarding other parts of the performance layer, such as JSP, etc. Maybe you will say, didn't you see what specialist is good? You still have an additional factory class. Don't worry, the curtain just opened, Spring is introduced in the performance layer, but you didn't find it:

The Presentation class is only programmed for interfaces of the Service class. Which of the specific "AccountService" is class, the Presentation class does not know, is configured in the Spring configuration file. (In this case, in order to maximize the original code, there is no abstract interface). Spring encourages interface programming because it is so convenient and natural, of course you can do this. Why is CustomBeanFactory this factory class simple because it directly uses Spring BeanFactory. Spring is a DI container from its core, and its design philosophy is an univoutered high-scalability framework. In order to achieve this goal, Spring has introduced Java's Reflection mechanism, avoiding hard coding methods by dynamic calling, and establishing its core components BeanFactory based on this as its implementation basis for its dependency injection mechanism. The Org.SpringFramework.beans package includes the implementation class of these core components, the core in the core is BeanWrapper and BeanFactory classes. 3.4. The lasting layer before discussing the business layer, let's take a look at the persistence layer, as shown below: In the above, we return the DAO interface under the iFace package to the business layer, where there is no need to make changes. Ibatis's SQL configuration file does not need to be changed. To change the DAO implementation class and configure it in the Spring profile. 1. Modify all DAO implementations of the base class inherit in the Basesqlmapdao class. Modify the Basesqlmapdao class as follows: public class basesqlmapdao extends SqlmapclientDaosupport {

protected static final int point_size = 4;

Protected SqlmapClientTemplate SmcTemplate = this.getsqlmapclientTemplate ();

Public BaseSqlmapdao () {

}

}

Change the BaseSqlmapdao class to inherit the SQLMapClientDaosupport class provided by Spring, and define a protection attribute SMCTemplate whose type is SQLMAPClientTemplate. For a detailed description of the SQLMapClientTemplate class, please refer to the "Spring Chinese Reference Manual" 2 in the appendix 2, modify the DAO implementation class all DAO implementation classes or inherit in the BaseSqlmapdao class, implement the corresponding DAO interface, but its corresponding DAO operation entrust SQLMAPCLIEntTemplate to execute Taking the Accountsqlmapdao class as an example, some code is as follows:

Public List getUsernamelist () {

Return SmcTemplate.QueryforList ("getusernamelist", null;

}

Public Account GetAccount (String UserName, String Password) {

Account Account = New Account ();

Account.setUserName (username);

Account.setPassword (Password);

Return (Account) SmcTemplate.QueryForObject ("getaccountbyuserNameAndpassword", Account);

}

Public void insertaccount (Account Account) {SmcTemplate.Update ("INSERTACCOUNT", Account;

SMCTemplate.Update ("Insertprofile", Account;

SMCTemplate.Update ("InsertSignon", Account;

}

Just as simple, all the signatures of all functions are the same, just find the replacement! 3. Remove the factory class and the corresponding profile to remove DAOCONFIG.JAVA this DAO factory class and corresponding profile DAO.XML, because DAO's acquisition now uses Spring to manage. 4, DAO configuration in Spring (ApplicationContext.xml)

Class = "Org.springframework.jdbc.datasource.driverManagerDataSource">

Org.hsqldb.jdbcdriver

jdbc: hsqldb: hsql: // localhost / xdb

sa

Class = "Org.springframework.orm.ibatis.sqlmapclientFactoryBean">

ClassPath: COM / IBATIS / JPETSTORE / PERSISTENCE / SQLMAPDAO / SQL / SQL-MAP-Config.xml

Class = "Org.springframework.jdbc.datasource.dataasource">>

Class = "com.ibatis.jpetstore.Persistence.sqlmapdao.accountsqlmapdao">

For specific syntax, please refer to the "Spring Chinese Reference Manual" in the appendix. Just just explain here: 1. We first create a data source Datasource where you are configured here that the HSQLDB database. If it is an Oracle database, the value of DriverClassName is "Oracle.jdbc.driver.OracleDriver", the value of the URL is similar to "JDBC: Oracle: Thin: @wugfmobile: 1521: CDCF". The data source is now managed by Spring, then we can now remove the database.properties this configuration file under the Properties directory; do not forget to modify SQL-MAP-Config.xml, remove Reference to it. 2. SQLMAPCLIENT node. This is a SQLMapClientFactoryBean configuration for iBATIS SQLMAP. In fact, a creative factory class for SQLMAPClient is configured. The ConfigLocation property is configured with the name of the IBATIS map file. The DataSource property points to the data source used so that all DAOs using SQLMAPClient use the data source by default, unless otherwise explicitly specified in the DAO configuration. 3. TransactionManager node. Defines the transaction, use the DataSourceTransactionManager. 4. You can define the DAO node, such as Accountdao, its implementation class is com.ibatis.jpetStore.Persistence.sqlmapdao.accountsqlmapdao, using the SQL configuration read from SQLMapClient, the database connection is not particularly listed, then the default Data source DataSource configured using SQLMAPClient. In this way, we have finished the persistence layer, and other DAO configurations are similar to Accountdao. how about it? Simple. This time you have an interface :) Accountdao interface -> Accountsqlmapdao implementation. 3.5. The location of the business layer and related classes, as shown below: Only 3 business classes in this example, we are transformed as an OrderService class, which is the most complicated, which involves transactions. 1. Add a bean configuration in the ApplicationContext configuration file:

Class = "org.springframework.transaction.interceptor.TransactionProxyFactoryBean">

PropAgation_required

Define a ORDERSERVICE, or it is easy to understand. For simplicity, the nested bean is used, which is a class is com.ibatis.jpetstore.Service.OrderService, which references ItemDao, OrderDao, Sequencedao, respectively. The bean's INSERT * implements transaction management (AOP mode). TransactionProxyFactoryBean automatically creates a transaction Advisor that includes a transactional property-based PointCut, so only transactional methods are intercepted. 2. The modification of the business class is taken as an example of ORDERSERVICE:

Public class orderservice {

/ * Private fields * /

PRIVATE ITEMDAO ITEMDAO;

Private Orderdao OrderDao;

Private sequencedao sequencedao;

/ * Constructors * /

Public ORDERVICE () {

}

/ **

* @Param ItemDao To set the itemdao.

* /

Public final void setitemdao (itemdao itemdao) {{ip

this.itemdao = itemdao;

}

/ **

* @Param ORDERDAO To set the orderdao.

* /

Public final void setorderdao (OrderDao OrderDao) {

THIS.OrDerdao = OrderDao;

}

/ **

* @Param sequencedao to set the sequencedao.

* /

Public final void setsequencedao (sequencedao sequencedao) {

THIS.SEQUENCEDAO = SEQUENCEDAO;

}

//the remaining part

.......

}

The red part is a modified part. Spring uses Type2 setting dependent injection, so we only need to define attributes and corresponding value functions, itemdao, orderdao, and sequencedao's values ​​are injected during run during operation. The constructor can be empty, and it is not necessary to write code processing transactions (declaration in the transaction), daomanager.startTransAction (); etc. You can also remove the statement related to transaction. Compare with the original code, is it a lot of hardcore! You can pay more attention to the implementation of the business. 4. Conclusion iBATIS is a powerful and practical SQL Map tool that directly controls SQL, providing a larger free space for system design. It provides the latest sample program JPETSTORE 4.0, elegant design, which has been used so far, which is very suitable for learning, and creates a lightweight J2EE web application on this basis. JPETSTORE 4.0 is based on Struts. On this article, the JPET is based on this, and the extent of the original design is maintained and the minimum code change amount is introduced in the business layer and the persistence layer. After you read this article and after the transformation source code, you will deeply feel the benefits of spring brought: naturally interface-oriented programming, business object's dependency injection, consistent data access framework and declarative transaction processing , Unified configuration files ... More importantly, Spring is both comprehensive and modular, Spring has a hierarchical architecture, which means you can choose to use any independent part, just like this, and it The architecture is internally consistent. Reference JPETSTORE related information and source programs http://www.ibatis.com/jpetStore/JPETSTORE.HTML Spring Chinese Reference Manual http://www.jactiongroup.net/reference/html/index.html Spring Development Guide Summer Struts http://struts.apache.org/

Regarding the author Wu Gaofeng, I have been interested in J2EE and various open source projects in ZTE's research and development. Now the Changde Cigarette Factory Information Technology is engaged in EAI construction. Contact: shuwgf@21cn.com

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

New Post(0)