Development of WebSphere application based on spring framework

Source: Internet
Author: User
Tags aop define definition implement connect sql access websphere application server
Web Overview Overview

Lightweight enterprise application development is increasingly popular with Java application developers, and the spring Framework is an outstanding representative of lightweight containers. Because of the growing use of spring, there are many applications based on WebSphere Application Server (was) that use the spring framework. This article first introduces the basic issues of using spring to develop Web applications, and then combines the WebSphere application server to describe how the spring application combines the services provided by the container. The purpose of this article is to explore with you how to better use the spring framework to develop applications based on WebSphere application servers.

   1, the main idea of Spring framework description

The core idea of the spring framework can be described in two words, which is decoupling. Try to create a loosely coupled structure between the parts of the application, both inside and between the code and the platform, making the application more flexible. The application of internal decoupling is mainly achieved by a technique called control inversion (IOC). The basic idea of control inversion is that the logic of the call, which is originally controlled by the application itself, is changed into passive control by external configuration file. Usually we use a so-called Hollywood principle (Don T call me.) I'll call you to figure out the relationship between this control reversal. Because the concept of control reversal is relatively broad, many application servers actually implement varying degrees of control reversal technology, but these application servers are too intrusive to the application. So Martin Fowler wrote an article on the concept of control reversal and proposed a more accurate description of the concept, called Dependency Injection (Dependency injection).

Each part of the spring framework fully uses the technology implementation of this dependency injection, giving the application the greatest degree of flexibility. In fact, the parameterized application control of dependency injection is not the first of spring, for example, IBM's multi-channel Application integration platform (Branch transformation TOOLKIT,BTT) has long used this kind of external parametric control technology. The "Object Factory" in BTT is similar to the beanfactory in the spring framework.

Another important technology of the spring Framework is its support for slicing-oriented programming (AOP). As application complexity increases and demand for application flexibility increases, so does the call for it logic and business logic to be separated as much as possible. As a better way to realize this separation, AOP technology has been paid more and more attention. Spring provides a dynamic AOP implementation that dynamically inserts the appropriate processing code before and after the target object's methods through proxy mode. The decoupling of applications from the underlying application server platform can also be achieved with the help of AOP technology. Spring's built-in AOP support is a feature that is icing on the cake. It makes some functions that must be supported by the container, such as transaction control can be separated from the opening of the container to achieve "slimming" purpose. This is one reason why the spring framework is often used as a lightweight container.

The spring framework can be used in conjunction with many existing framework technologies. An important feature of the application of Java EE technology is that the relevant open source community is very active. There are a number of excellent open source frameworks available at different levels of Web applications. For example, the web layer of the Struts,or mapping layer of hibernate and so on. The spring framework does not reinvent the wheel, and it does not appear to replace these existing frameworks. Instead, the spring framework can be designed to build applications either independently or together with existing frameworks. Another place to point out is that the spring framework has very little coupling between the modules, so the spring framework can be used in a step-by-step manner depending on the actual need, rather than being copied.

   2. Web application base based on spring

Typical level of 2.1 Web applications

Web applications are generally logically divided into the following layers according to functionality:

1. Display Layer

This layer mainly generates the interface that is displayed to the end user and contains as few business logic as possible. JSP is one of the most common technologies for Web applications based on Java EE. Spring's support for the presentation layer is very flexible, in addition to supporting JSP directly, it also supports performance layers based on Freemarker templates, interfaces based on velocity templates or other document types.

2. Business Layer

The business layer typically contains the main business logic, especially those that correspond to the use case. In addition, this layer is suitable for the logic that includes transaction management and security control. A good business layer design enables the presentation layer to adopt different technologies without impacting the business layer. The function of the business layer can be likened to the stateless session bean hierarchy in Java EE technology.

3. Data Access Object (DAO) interface layer

DAO is actually the data interface layer, which is recommended to be embodied through interfaces in the application. The existence of DAO enables data access to be separated from the concrete implementation of the underlying persistence layer. Generally in the DAO interface is mainly to implement the data object query, storage, deletion and other operations. Theoretically, the DAO layer and the underlying data storage mode is independent, that is, does not necessarily require a relational database. The spring framework also takes into account the situation of other relational database data sources when it is designed.

4. Persistent Business Objects

Persistent Business objects are persistent representations of business objects in the problem domain, such as a user object, a bank account, and so on. We generally use some O/R mapping technology to achieve the persistence of these business objects. A persistent business object is one that can contain business logic, and what is different from the business logic contained in the business layer is that the persistent business object contains the business logic that is directly related to the specific business object and is more general.

5. Enterprise Information System

Enterprise Information system refers to Web applications need to connect the background system, generally can be divided into three categories, namely, ERP system, Enterprise legacy system and relational database. Most Web applications are based on relational databases, which are the enterprise information systems that are primarily considered in common frameworks like spring.

Well-designed web applications tend to rely on the next level in the hierarchy, but the next level is not dependent on the previous layer. We can briefly summarize the principle of "downward and not upward dependence". Interface coupling is recommended in order to minimize dependency between levels. This is where the spring framework plays its external configuration advantages.

The choice of 2.2 MVC

Although the pattern of MVC was long before the advent of the Java language, this pattern was widely accepted by Web application developers in the era of EE. For a variety of frameworks based on MVC, the issues to be addressed can be divided into the following sections:

1. Encapsulates input from a Web page into a data object, such as a form in Struts bean,spring the command class in MVC.

2. Depending on the request, the controller responsible for distributing maps and invokes the corresponding logical processing unit and passes the above data object as a parameter.

3. The logical processing unit completes the corresponding processing and then puts the result into a data object.

4. The returned data object is displayed in some way in the selected presentation interface.

When you use spring to build MVC, you can choose to use Spring's own MVC implementation directly, or take advantage of spring's support for some of the MVC frameworks that you already have. Spring, for example, can support struts,webwork and so on, and use them in combination. Spring's proud non-invasive features are not as impressive in spring MVC. It has a higher degree of coupling with the servlet API than other parts, and requires some spring interfaces and classes.

The main distributor implementation of Spring MVC is Org.springframework.web.servlet.DispatcherServlet, which is the Access portal to spring MVC. Spring provides classes such as Simpleformcontroller,abstractcommandcontroller to help you build a variety of controller actions and use the Modelandview class to contact presentation and logical return data. As described in the previous section, spring MVC can support different interface presentation techniques, and the display of the interface and the implementation of the controller behind it are decoupled, as is the change of the interface display technology without modifying the implementation of the controller, simply by using Spring's control reversal technology to modify the external configuration file. For example, when using JSP to display technology, the viewresolver definition of an external configuration file is as follows:

<bean id= "Viewresolver"
Class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name= "Viewclass"
<value> Org.springframework.web.servlet.view.JstlView </value>
</property>
<property name= "prefix" > <value>/view/</value> </property>
<property name= "suffix" > <value>. JSP </value> </property>
</bean>
If you switch to Freemaker template technology, in addition to the page template changes, the main thing is to change the corresponding external configuration file, as shown below. The concrete display logic part does not need to do any modification.

<bean id= "Viewresolver"
Class= "Org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver" >
<property name= "Viewclass"
<value>
Org.springframework.web.servlet.view.freemarker.FreeMarkerView
</value>
</property>
<property name= "suffix" > <value>. FTL </value> </property>
</bean>
<bean id= "Freemarkerconfig"
Class= "Org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer" >
<property name= "Templateloaderpath"
<value>/view/</value>
</property>
</bean>


Spring is also supported if you want to combine some of the existing MVC frameworks without using the Spring MVC framework. Spring provides support for common MVC frameworks, including Struts,webwork,tapestry and JSF. One of the benefits of using these frameworks is that you can use some of the familiar technologies that are already in place, and the AOP interceptor in spring can be relatively easy to handle things that are common to frame actions, such as log processing of actions. If you choose these MVC frameworks, you will need to modify the configuration file for the framework and the spring configuration file for the application. For example, when using struts, The mapping action type in the Struts-config.xml configuration file is typically set to Org.springframework.web.struts.DelegatingActionProxy, or the controller is set to ORG.SPRINGFRAMEWORK.WEB.S Truts. Delegatingrequestprocessor. You then need to define the bean corresponding to the struts action in the appropriate webapplicationcontext. This allows you to take advantage of Spring's control reversal technology to manage struts action.

Another problem to be solved when using these frameworks is the loading of the context. For example, using struts, you can use Contextloaderplugin to load web contexts. This contextloaderplugin replaces the original way of loading by Dispacherservlet. You need to add the following entry in the Struts-config.xml file: . This way, the web context of spring can be loaded with the initialization of the struts Actionservlet.

Therefore, if the user's existing application is based on an MVC framework, or if the user is familiar with a framework, you can use spring to combine support for these frameworks. Because our purpose is to solve the problem rather than to use some kind of technology. But for other users, if you're not familiar with some of the existing MVC frameworks, you can use the Spring MVC framework directly.

2.3 Web Context Settings

Spring context settings, which are not dependent on the application server, are usually obtained by filesystemxmlapplicationcontext or Classpathxmlapplicationcontext in the application code. For example, use this code to get the context:

ApplicationContext CTX = new Filesystemxmlapplicationcontext ("Config.xml");
However, according to the principle of control reversal, the application code should know the settings of the context as little as possible. Therefore, in a spring based Web application, such code can also be omitted. Spring can be configured to have the Web container automatically mount the context configuration file. In essence, the ServletContext of Web applications is where spring is used to store the application context. There are several classes in spring that are related to the web context load:

1. Contextloaderlistener: General application Server such as was can load listener first, if not, then only use Contextloaderservlet.

2. Contextloaderservlet: You need to configure <load-on-startup> to make it first load. The class that really loads the context is contextloader, and the top two classes are just two different ways to invoke Contextloader. The actual call inside the Contextloader is Xmlwebapplicationcontext, whose default profile is/web-inf/applicationcontext.xml.

If you use Contextloaderlistener, its configuration in Web.xml is generally as follows:

<listener>
<listener-class>
Org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
If you use Contextloaderservlet, its configuration in Web.xml is generally as follows:

<servlet>
<servlet-name> Context </servlet-name>
<servlet-class>
Org.springframework.web.context.ContextLoaderServlet
</servlet-class>
<load-on-startup> 1 </load-on-startup>
</servlet>
The application itself may, in addition to the HTTP-based Web channel, provide services externally through other channels, so it is a good practice to separate the configuration associated with the presentation from the configuration of the subsequent business processes. This way, if you change the access channel for your application, you only need to modify the corresponding configuration file. As a result, spring provides a webapplicationcontext concept. The webapplicationcontext typically contains configuration definitions related to Web Access, including definitions of various control actions, definition of interface display, and so on.

Webapplicationcontext are typically initialized by Dispatcherservlet. It can be seen as a applcationcontext of the context hierarchy. By default, the profile name of the Dispatcherservlet mount is-servlet.xml for its Servlet name, but can be customized by contextconfiglocation parameters. An example of the definition of Dispatcherservlet in Web.xml is as follows:

<servlet>
<servlet-name> Dispatcher </servlet-name>
<servlet-class>
Org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup> 2 </load-on-startup>
</servlet>
<init-param>
<param-name> contextconfiglocation </param-name>
<param-value>/web-inf/context/webcontrollers.xml </param-value>
</init-param>
2.4 Data Persistence layer

Although Web applications using the Java EE technology can connect many different enterprise information systems (EIS), the database is undoubtedly one of the most important and common. Because of this, spring provides very complete support for database access. The data Access object (DAO) pattern is a very important one in the Java EE model. Its main purpose is to make the persistence layer separate from the business logic layer, thus shielding the concrete implementation of the persistence layer. We can divide spring's DAO support into two broad categories: data access directly based on the spring JDBC template, and data access based on the O/R mapping framework. The relationship between the DAO interface and the actual implementation class can be defined by using the spring's control inversion feature and the external configuration file. The O/R mapping framework currently supported by the spring framework includes Hibernate, JDO, TopLink, Ibatis, and so on.

Suppose we define a userdao. When using JDBC to implement this DAO, the defined classes can be as follows:

public class Userdaojdbc extends Jdbcdaosupport implements userdao{...}
If you use Hibernate to implement this DAO, the classes defined are as follows:

public class Userdaohibernate extends Hibernatedaosupport implements Userdao {...}
Spring has a corresponding abstract class supply for other O/R mapping mechanisms, such as sqlmapclientdaosupport for Ibatis, Jdodaosupport for JDO, and so on.

Let's look at how to define the relationship between the DAO and the implementation in the spring configuration file. Assuming that our Userdao is specifically implemented through Hibernate, then a DAO in Applicationcontext.xml can be defined as follows:

<bean id= "Userdao" class= "Com.fgw.dao.hibernate.UserDAOHibernate"
<property name= "Sessionfactory"
<ref local= "Sessionfactory"/>
</property>
</bean>
Here our actual DAO interface definition is: Com.fgw.dao.UserDAO, and the concrete implementation class is: Com.fgw.dao.hibernate.UserDAOHibernate. Obviously, for other DAO implementations, we only need to modify the corresponding implementation class in the configuration file (the specific implementation class is certainly less than the necessary) and attributes. For example, for the DAO implementation of JDBC, the attribute is defined as the corresponding data source.

   3, Spring and WebSphere Application Server collaboration

Spring and the underlying Java EE application servers still have some place to combine, giving some of the points of being.

3.1 Using the WAS data source

In a Java application, there are generally two ways to connect a database. One way to get a database connection is through Java.sql.DriverManager. This approach does not depend on the support of the application service, but does not provide the functionality of the database connection pool. Another way to get a database connection is through a javax.sql.DataSource approach. The traditional application based on Java EE needs to get the data source (Javax.sql.DataSource) object through Jndi, and then get the corresponding database connection through the data source. Common application servers support this approach, and generally provide support for database connection pooling. Although we generally recommend the use of database connection pooling, there are also times when we need to detach from the environment where the application server is open (such as unit testing, such as application porting, etc.). However, when the application uses these two methods, the code is not the same, so only the code can be used to strain. Spring provides a solution that unifies the data source, and then uses an external configuration file to specify the data source used by the control reversal mechanism. This can unify the two ways to get the database connection, on the other hand does not need to like the usual Java EE application through cumbersome Jndi code to get the data source. The application does not need to know what kind of data source to use.

Spring provides a Drivermanagerdatasource class to unify the first method of data source acquisition. If you use the Cloudscape database in was, the external configuration file can be configured as follows:

<bean id= "DataSource" class= "Org.springframework.jdbc.datasource.DriverManagerDataSource"
<property name= "Driverclassname"
<value> Com.ibm.db2j.jdbc.DB2jDriver </value>
</property>
<property name= "url" >
<value> Jdbc:db2j:d:\\dbname </value>
</property>
</bean>
Spring provides a Jndiobjectfactorybean class to support the second way of data source acquisition. Assuming that the data source name that was already configured in was jdbc/mydb, the external configuration file can be configured as follows:

<bean id= "DataSource"
Class= "Org.springframework.jndi.JndiObjectFactoryBean" >
<property name= "Jndiname" > <value> java:comp/env/jdbc/mydb </value> </property>
</bean>
Or
<bean id= "DataSource"
Class= "Org.springframework.jndi.JndiObjectFactoryBean" >
<property name= "Jndiname" > <value> jdbc/mydb </value> </property>
<property name= "Resourceref" > <value> true </value> </property>
</bean>
From the above configuration we can learn that by using spring, applications can unify the implementation of different data sources. If the usage environment changes, you only need to modify the spring configuration file. For Web applications deployed on was, the database connection pool that was implemented was recommended in the production environment. On the one hand because the connection pool to achieve relatively perfect. On the other hand, using the database connection pool provided by was provides a perfect support for JTA transactions.

3.2 JTA Using was

Web applications often involve a choice of transaction types when using transactions. Is it to select a local transaction like a JDBC transaction or to use a global transaction supported by JTA. This is closely related to the type and number of transaction managers that the application needs to relate to. Spring itself does not support distributed transactions, so distributed transactions require low-level JTA. But spring provides an abstraction of the transaction, where the underlying true transaction implementation can switch without affecting the application code. This allows applications to rely on the underlying was, or easily, from the environment in which the application server is opened. This is very similar to the abstraction of the previous data source.

Was itself has two support methods for transaction partitioning, one is declarative, and of course this management requires the support of the EJB container, the so-called container Management transaction (CMT). Another approach is programmatic, using program code to directly use the JTA programming interface. Spring's partitioning of transactions can be divided into both declarative and programmatic ways. For spring programming, the transaction partitioning approach can be divided into two broad categories in general. A class is one that implements the Platformtransactionmanager interface directly by using it. The other is that by using the Transactiontemplate template class, the use of template classes can simplify transaction control code. Spring's support for declarative transaction partitioning is actually taking advantage of its AOP mechanism. This AOP-based approach is more flexible than programming transaction partitioning, and is almost zero intrusive to code. Therefore, it is recommended that you use this transaction partitioning method without special needs. The commonly used transaction partitioning method based on AOP can be used Proxyfactorybean plus transactioninterceptor, or using the Transactionporxyfactorybean method. The previous approach is relatively flexible, while the latter is relatively simple to use.

Regardless of which kind of transaction divides the way, the bottom layer needs a transaction management mechanism as the support. If it is a single transaction resource manager, then depending on the type of background transaction management resource being used, the Platformtransactionmanager implementation that can be chosen is Datasourcetransactionmanager, Hibernatetransactionmanager, Jdotransactionmanager, Persistencebrokertransactionmanager, and Jmstransactionmanager. You can use the Jtatransactionmanager class, whether it is a single or multiple transaction resource managers. If you use Jtatransactionmanager, all transaction management is actually delegated to the JTA implementation of the underlying application server.

For example, if you use JDBC or ibatis, then we can use a simple datasourcetransactionmanager, and the external configuration file fragment is as follows:

<bean id= "TransactionManager"
Class= "Org.springframework.jdbc.datasource.DataSourceTransactionManager" >
<property name= "DataSource"
<ref local= "DataSource"/>
</property>
</bean>
If you use Hibernate, then we can use Hibernatetransactionmanager, and the external configuration file fragment is as follows:

<bean id= "TransactionManager" class= "Org.springframework.orm.hibernate".
Hibernatetransactionmanager ">
<property name= "sessionfactory" ><ref local= "sessionfactory"/> </property>
</bean>
Using the JTA support of was, All we need to do is change the class attribute in the corresponding bean to the class attribute to Org.springframework.transaction.jta.JtaTransactionManager, and then change the attribute to the WebSphere corresponding TRANSACTI Onmanager, refer to the following:

<bean id= "Wastxmgr"
class= "Org.springframework.transaction.jta.WebSphereTransactionManagerFactoryBean"/>
<bean id= "TransactionManager"
Class= "Org.springframework.transaction.jta.JtaTransactionManager" >
<property name= "TransactionManager"
<ref local= "Wastxmgr"/>
</property>
</bean>
By using spring's transactional support, the decision on how the underlying transaction is made does not have to be decided at the outset. Because we are able to switch real transaction support through spring's external configuration file. However, while there is also third-party JTA support, is was able to provide very stable XA support, so the use of is recommended JTA, especially when the application involves distributed transaction processing. This can be solved uniformly regardless of the application involving several transaction resources.

3.3 How to load a spring jar package

The core jar package for the spring framework is spring.jar, but some extensions jar packages and dependent jar packs are needed depending on the actual usage. What about the jar package files that were handled in was? A simple and straightforward way of dealing with Web applications is to copy these used jar files to the corresponding Web-inf/lib directory. This approach is simple, but when there are more than one spring application, this process requires a copy of the same jar file in each application's Web-inf/lib directory. This can be done by sharing the library in a way that solves the problem of class library sharing.

Shared libraries are a mechanism that was specifically designed to address the sharing of jar or local library files between different applications. A shared library consists of a name, a Java classpath, and/or a loaded JNI library local library path. It can be defined separately at the Unit, node, and server level. But a shared library definition does not mean that it will be loaded, it will only be loaded if the shared library is associated with an application or application server. If a shared library is associated with an application, the shared library is loaded by the Application class loader. If a shared library is associated with an application server, the shared library needs to be loaded with a specially defined classloader. This class loader needs to be defined by the user itself. It operates as follows: Select an application server such as the Server1 ' class loader ' Create a new class loader loader associated with a shared library.

It is generally necessary to define a shared library before creating this class loader. According to the above, it is two steps to solve the jar pack sharing problem for spring application through shared libraries. First, define the jar packages that need to be shared in the spring application as a shared library. Second, select the corresponding was server instance and associate it with the shared library created above. All applications on this was server instance will be able to use the jar packages defined in the shared library. When using shared libraries this way, be careful to understand the order and manner in which classes are loaded. If this is the shared library jar package associated with the was server instance, its class loader is on the hierarchy above the Application class loader, which is its parent loader. The class loader structure and policies about was can be further referenced by the was Information center.

   4. Concluding remarks

The core content of the spring framework does not depend on any container, but it is clear that web-based applications are the main application type of spring. Understanding and using the Spring Framework simplifies application development and testing on the one hand, and the other side can deepen the understanding of Java EE technology. Another lightweight web application development is becoming a trend, so why not. What is discussed above is something that is common in spring usage, and the spring framework itself is becoming more and more complex. Of course, some of the ideas embodied in the framework of Spring, Hibernate, and so on, are being drawn from the JEE 5 specification, especially in EJB 3, where control reversals are applied and pojo are used in large quantities. In fact, whether it is JEE technology standards or spring frameworks, the purpose is to simplify the development of enterprise applications, but as a standard, JEE to consider the content of a broader, more in-depth.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.