Category Archives: Spring

Spring Book – Chapter 11 – Spring Web

Large number of enterprise web applications is developed using Java and forms a very integral part of any organization in modern day. Web applications have become more and more complex and it poses more and more challenges day by day. Having a good web framework should be able to address most of these challenges there by reducing the effort on the developer and allowing them to focus on implementation of actual business logic.

This Chapter introduces you to the Spring Frameworks web support and the various components in the Spring web stack. This is just an introduction to the Spring’s frameworks role in the web application development support.

The Chapter starts off by explaining the Spring web stack and the various components which it comprises. Later on it delves deep into each component and explains each one in detail. Following with the Spring philosophy it then covers the various integration possible with your Spring application. Since some integration is really important, these are covered as separate chapters later on.

A Little History

Before going deep into the Spring web stack, a little history about the Spring web stack development from its early days to present.

Spring started its journey in 2002 and Spring Web was part of the original Spring ecosystem and contained servlet/web tier tool for aiding web application development. Then came Spring Frameworks own MVC framework in the form of Spring MVC. Following the core principles of Spring, it allowed to integrate with other frameworks.

Then came the inclusion of Spring Portlet MVC which was contributed initially by Rutgers in April 2004. John Lewis started contributing changes and it got included in the main Spring code base along with Spring 2.0 release.

Spring Web Flow started as a sub project and its first release was in March 2005. Due to its innovative ideas and good acceptability in the industry after inception, it soon became an independent project and got its independent release version 1.0 released in the same year.

Over the period Spring MVC and Spring Web Flow evolved and is considered among the renounced web technology stack.

Spring Web Stack

Modern day web application posses high level of challenges, including the following:

  • Complexity continues to rise at an alarming rate
  • Necessity of exposing services to a larger audience
  • Ability to give users the best possible experience in the shortest possible of time
  • High expectations
  • Ability to build simpler applications
  • Cloud enablement

Ideally any web framework chosen for web application development should address the above challenges reducing much of the complexity for the developer. Spring provides a full stack web framework by gathering multiple libraries and frameworks useful for web development into a single unified software stack for web developers to use. It tries to address the rising complexities raised by web application development by building on top of the lightweight Spring container. Figure 11-1 shows the various components provided by the Spring web stack for developing web application using this foundation.

Figure 11-1. Spring Web Stack components

The Spring Web Stack gives you:

  • A unified programming model
  • Capability to handle multiple client types using the same foundation
  • Adaptability to choose the right approach according to the required use case

The various Spring web stack components are:

  • Spring Framework and Spring MVC
  • Spring Web Flow
  • Spring Security
  • Spring JavaScript
  • Spring Faces
  • Spring BlazeDS Integration

Page Visitors: 2708

Spring Book – Part III – Web Application Development Support by Spring

For any organization, business applications based on web has become a sort of mandate due to its evolvement over the period of time. Spring Framework provides modules which aids in developing web application infrastructure for the server side.

This part of the book contains Chapters which will help you in developing web application with the help of Spring Framework. More importantly it lets the reader understand the web application development support by the Spring Framework.

Chapter 11, “Spring Web”, introduces you to the Spring web stack as a whole. It introduces you to various components in the Spring web stack and also covers some basics around Spring web and other web technology facts like MVC framework and so forth.

Chapter 12, “Spring and Struts Integration”, purely looks into the integration of Spring Framework with the famous MVC framework, Struts in detail.

Chapter 13, “Spring and JSF Integration”, similar to Chapter 12, looks at integrating Spring Framework with another famous MVC framework Java Server Faces (JSF) in detail.

Chapter 14, “Spring MVC and Spring Web Flow”, goes into detail of Spring MVC, Spring Frameworks implementation of MVC pattern and Spring Web Flow in detail.

Chapter 15, “Web Application Security with Spring”, covers the most important aspect of any enterprise application, security. It covers Spring Security in detail with respect to web application security.

Chapter 11: Spring Web

Chapter 12: Spring and Struts Integration

Chapter 13: Spring and JSF Integration

Chapter 14: Spring MVC and Spring Web Flow

Chapter 15: Web Application Security with Spring

Page Visitors: 335

Spring Book – Chapter 10 – Caching

Cache is a component that transparently stores data so that future requests for that data can be served faster. The data that is stored within a cache might be values that have been computed earlier or duplicates of original values that are stored elsewhere. If requested data is contained in the cache (cache hit), this request can be served by simply reading the cache, which is comparatively faster. Otherwise (cache miss), the data has to be recomputed or fetched from its original storage location, which is comparatively slower. Hence, the greater the number of requests that can be served from the cache, the faster the overall system performance becomes.

–          wikipedia.org

“Cache” is a specialized form of computer memory.

–          About.com

A cache stores recently-used information in a place where it can be accessed extremely fast.

–          techterms.com

 To store data locally in order to speed up subsequent retrievals.

–          pcmag.com

One of the new features added in Spring Framework in its version 3.1 is its support for transparently adding caching into an existing Spring application. Similar to transaction management, it allows developers to incorporate consistent use of various caching solution available in market with minimal or no impact on the source code.

In this chapter we will first go through various caching concepts and why it should be used in your application. We will then delve deep into as to how we can do this in your Spring application. In these sections we will cover the various nitty-gritties involved in configuring caching for your application. We will also see Spring’s support for other third party cache libraries available today and then finally wrap the chapter with the concept of distributed caches to some extent.

After reading this chapter you should have a clear idea of the cache abstraction provided by the Spring framework and also have a very clear idea of using caching in your existing and new application build on Spring Framework.

Why Caching?

Caching has been one of the methods employed to speed up an application and relieve its workload. Its usefulness is particularly apparent today with the rise of social web applications, visited by thousands of people at the same time. Moreover caching should be something orthogonal, having minimal or nil side-effects to the business logic that a developer writes. There are many cache libraries in Java world, both commercial and open source.

Caching is an essential tool for scaling web applications. It avoid disk access, I/O, CPU power and network traffic – primarily to the backend relational database in modern web applications.


Application without Caching Layer

An application that doesn’t have a caching layer has the following  known problems:

  • Every call creates new objects in CPU memory and Java heap.
  • Duplicate objects in Java heap due to repeated database calls.
  • All data comes from database which involves network call and is very expensive in nature.
  • Due to network involvement in various steps in the overall execution, response times get affected.
  • A single call might in turn call multiple data sources to get all required data, in which case it becomes more expensive and more time consuming.
  • Due to high amount of objects in Java heap, it could trigger Java garbage collection which is very expensive.
  • There is an additional requirement of CPU in doing the marshalling of data from database to the format required in the application layer.

Figure 10-1 shows a typical application without caching layer. It shows applications interacting with more than one data source to retrieve all the required data in your application. It also shows interaction of application directly with various data sources which are very expensive and also time intensive.

Figure 10-1. Application interactions without caching layer

Page Visitors: 13512

Spring Book – Chapter 9 – Transaction Management

The concept of transaction is essential to any business application. A transaction, in layman’s term, makes sure that only contracted-upon, dependable, and satisfactory state changes are made to a system, regardless of any failure in the system or issues arising due to concurrent access to the system’s resources.

The present application architectures brings along with it lot of complexities, having veracious systems joined together achieving a business case into reality. This brings along challenges to existing transaction models, which application frameworks keep on innovating to achieve it. Spring provides excellent transaction management capabilities considering modern day application’s transaction requirement and complexities.

The initial sections of this chapter deal with fundamental concepts in and around transactions in general. Later sections concentrate on how Spring comes into picture to address these transaction concepts.

Why Transactions?

In simple terms transaction can be thought of as an interaction with a system resulting in a state change of the system. It is a common practice to mention transaction as a “unit of work”.  In most of the cases, these interactions can be successful, but any number of unforeseen events can interrupt this interaction, leaving the system in an incomplete, inconsistent and unstable form which is not good for the overall application system.

By putting the interaction with the system inside a transaction boundary, you get a guarantee that the interaction is achieved successfully, and in case if it is not, it keeps the system in consistent and stable form.

In simpler terms, in reality, any application is bound to fail at some point in its life. This might result from programming problems, loss of power supply, hardware issues, incorrect input data, user error and so forth. The causes are many, but the end result is same; you application in an inconsistent manner. Putting your interaction with the application inside a transaction boundary can mitigate it to some extend and this is the reason you should use transaction in your application.


ACID Transactions

In any modern day applications, transactions are required to satisfy the so called ACID properties, that is, the set of operations involved in a transaction should occur atomically, should be consistent, should be isolated from other operations, and their effects should be durable in time. We will explain each of the following properties:

  • Atomicity
  • Consistency
  • Isolation
  • Durability

Atomicity

It is the property of a transaction to either complete successfully or not at all in the event of complete or partial failure. All the activities within a particular transaction should be indivisible, that is, atomic in nature.

Consistency

It is the property of a transaction to begin and end in a state which is consistent and not breaking any integrity constraints. A database or other persistent store defines referential and entity integrity rules to ensure that data in the store is consistent at all times. A transaction that changes the data must ensure that the data remains in a consistent state and that data integrity rules are not violated, regardless of whether the transaction is a success or failure. The data in the store may not be consistent during the duration of the transaction, but the inconsistency is invisible to other transactions, and consistency must be restored when the transaction completes.

Isolation

It is the property of a transaction to perform operations isolated from all other operations in a particular application. One transaction should not see other transaction’s data in an intermediate state at any stage. When multiple transactions are in progress, one transaction may want to read the same data another transaction has changed but not committed. Up until the transaction commits, the changes made by it should be treated as transient state, because the transaction could roll back the change. If other transactions read intermediate or transient states caused by a transaction in progress, additional application logic must be executed to handle the effects of some transactions having read potentially erroneous data. This property tells how concurrent transaction should behave in which it actions on same set of data in an application.

There are various isolation levels which exist in the case of transaction, which will be covered in later sections of this chapter.

Durability

It is the property of a transaction wherein, state changes made within a transactional boundary in an application must be persisted onto permanent storage media, such as disks, databases, or file systems. If due to any reason application fails after the transaction has committed, the system should guarantee that the effects of the transaction will be visible to the application when it restarts. Any change committed by one transaction must be durable until another valid transaction changes the data.

Transaction Types

There are various means by which a transaction is classified into different types. Some of the well-known transaction type terminology is explained below so that you have a clear idea when these are used at various stages of this chapter.

Local Transactions

Transactions that deal with just one resource such as one database are known as local transactions. Coding using local transactions can be easier but has significant disadvantages attached to it. They are:

  • It cannot work with multiple transactional resources.
  • Invasive/disturbing to the underlying programming model.

Global/Distributed Transactions

Transactions that span multiple resources such as more than one database or a database and a messaging engine are called global transactions. They too have advantages attached to it, which can be summarized as below:

  • The application server manages global transactions using JTA (Java Transaction API), which can be cumbersome API to use.
  • Usually, JTA in an application server is sourced from JNDI, which indirectly brings in dependency of JNDI to your application.

Spring addresses disadvantage of both local and global transactions alike, by addressing these disadvantages, as well as introducing its own unique advantages which are covered in the section named “Advantages of Spring Transaction Management” below.

Note: For Java Standard Environment, stand-alone JTA implementations can be wired to use the Spring’s JtaTransactionManager, which is covered in the following sections of this chapter. This way Spring addresses both the disadvantages mentioned in the above section.

Page Visitors: 9653

Spring Book – Chapter 8 – Data Access

One of the very important aspect in any enterprise application is the ability to get data in and out of your application with ease. Thinking on the same lines, Spring framework provides extensive support for data access. In this Chapter we will first explore the various data access technologies and then see the support provided by Spring for using these technologies in your application.

Spring effectively makes data access easier by managing the various resource for you, by providing abstraction and easy API helpers and by supporting all major data access technologies available in the industry so that you don’t have to get yourself bogged down to a particular technology. Going along with the Spring philosophy it lets your Spring application integrate to any data access technology with ease.

In this Chapter we will see the support given the Spring framework in interacting between data access layer and the service layer in your application. Spring compressive support for transaction management will be covered briefly as we have dedicated Chapter 9 for this specific topic. In this chapter we will also be covering various data access frameworks and technologies which the Spring framework integrates with almost ease.

Enterprise Data Access

Spring integrates and works just fine with all leading data access technologies at present available in market. Accessing eternal system like a database requires various resources at various stages. You will also have to look for resource contention and make sure that resource which is limited is managed properly and efficiently. Such resource management becomes critically important in mission critical enterprise application.

Putting the burden of maintaining these resources in an application to a developer not only puts additional pressure in a developer but also puts an additional risk on the overall application’s success. Spring provides comprehensive resource management capability which takes this burden away from the developer and entrust him with writing the actual business application logic.

Resource Management

As discussed earlier Spring integrates seamlessly with almost all data access technologies like JDBC, Hibernate, iBatis, JPA or JDO in a consistent way. Using Spring, you are not locked down to a particular technology and as case may be, you have the freedom of switching between the various technologies without worrying too much about the technology specific nitty-gritties. Figure 8-1 also shows the various classes which will be used to in the code samples in this chapter in various sections.

Figure 8-1. Spring Integration with well know data access technologies

Spring internally take care of the various resource management functionalities specific to data access technologies so that the developer concentrates on the actual application logic rather than data access technology specific coding.

Some of the key features which the Spring framework provides in resource management are:

  • Transaction Management
  • Connection Management
  • Exception Handling

In a typical application, the resource management capabilities are related with connection and transaction management. While trying to manage connection and transaction, there are exceptions that arise and resource management should also be capable of dealing these exceptions in timely and orderly fashion. Figure 8-2 shows a typical resource management scenario in an application.

Figure 8-2. A typical resource management scenario in any application

The following sections will look into these features of Spring in some detail so that you get a clear picture of what are the features which Spring transparently does for you in developing your application.

Page Visitors: 10641

Spring Book – Chapter 7 – Testing

Testing is an integral part of enterprise software development. It is one of the most important phases of the Software Development Lifecycle (SDLC) and has gained more importance in last decade or so. Having said that, there are many constraints either from framework level or project level, which makes testing effort in a project more challenging and time consuming. In this chapter we will first touch upon the importance of testing and see what are the various testing techniques employed in a typical application. Along the way we will see the problems imposed by various frameworks in achieving full test coverage.

After that we will see, how the Spring framework supports you in making your application more testable.

Why Testing Is Important?

As definition goes, testing is the practice of making objective judgments regarding the extent to which the system meets, exceeds or fails to meet stated objectives. Software Testing is the process used to help identify the correctness, completeness, security, and quality of developed computer software. Testing is a process of technical investigation, performed on behalf of stakeholders, that is intended to reveal quality-related information about the product with respect to the context in which it is intended to operate.

There are two fundamental purposes of testing; verifying specifications and managing risk.  First, testing is about verifying that what was specified is what was delivered. It verifies that the product meets the functional, performance, design, and implementation requirements identified in the specifications. Second, testing is about managing risk for both the acquiring organization and the system’s vendor/developer.

To find the importance of testing, you need to understand the goals of testing. Below are some of the important goals of testing:

  • Verify against a written and agreed specification
  • Assess quality of the software
  • Reveal failures if any in the delivered software
  • Verify contract such as legal, standards etc.
  • Learn how program works

TDD

Test-driven development (TDD) is an evolutionary approach to development which instructs you to have test-first development intent. You start by writing a test and then you code to elegantly fulfill the test requirements.

The steps in a typical TDD are shown in Figure 7-1 below. The first step is to quickly add or expand a unit test to your test suite. Next you run the test suite to ensure that the new test does in fact fail. You then update your functional code until it passes the test suite. Once the test suite does not fail, you should refactor the code; and then start over again.

Figure 7-1. TDD Steps

Refactoring – is a development practice for restructuring an existing code, altering its internal structure without changing its external behavior. Refactoring keeps the code clean and easy to understand.

Types of Testing

Tests can be grouped by where they are added in the software development process, or by the level of specificity of the test. The main levels during the development process are unit, integration, and system testing.

Unit Testing

Unit testing is a testing methodology employed to test a specific unit in an application. It does this verification process totally in isolation from other components. This testing has become so prominent that in some software development methodologies (Agile), the unit test cases have to be written before the actual class implantation which does the real work.

Unit tests must follow the FIRST Rules; these are Fast, Isolated, Repeatable, Self-Validated and Timely. Unit tests should be written in such a manner so as to test all the methods in the class along with all exception paths in the methods. The main aim of unit testing is to quickly test any new code or change to any existing code without spending much effort an time.

Though there are advantages, there are inherent limitations to this type of testing.  These don’t address the testing of the actual functional requirements of the application. These tests only cover testing of each module in the application. Also, we can’t test scenarios like asynchronous services which require configuring of JMS message queues inside the application server. Having said that, this is one of the testing types which is very important and can be used to test as much application functionality as possible.

Multiple unit test cases constitute to form a test suite. There are several open source products which allow the application team to setup and run these unit test cases. One of the well-known products is called JUnit. Being most popular, it has good integrations with other tools (Eclipse) and frameworks (Ant, Maven).

These types of tests are usually written by developers as they work on code to ensure that the specific intended function is working. Unit testing alone cannot verify the functionality of a piece of software, but rather is used to assure that the building blocks using which the software is built, work independently of each other.

Page Visitors: 5840

Spring Book – Chapter 6 – Enterprise Integration

Spring’s core support includes its capability of configuring application, enterprise integration, its testing capabilities and data access methodologies. In Chapter 4, I introduced you to various configuration styles available in Spring. In Chapter 5, I continued on to explain the various simplifications that you can do in your application. In this Chapter I will be covering enterprise integration which is one of the core support provided by the spring framework in detail.

I always like to call an application enterprise. For an application to be called enterprise, it needs to have enterprise components/objects on which it is built. I call an object enterprise when it has capability to handle transactions, capable of existing in a secured environment, has capability to integrate with other system, and so forth.

Using Spring framework, you can make simple POJOs getting transformed into what I call as enterprise objects, with minimal involvement of developers. Developers spend more time writing the actual business logic and the Spring container does all the magic behind the scenes.

Spring framework provides comprehensive infrastructural support for what we call an enterprise application. One such important component in any enterprise application is its capability to integrate. Spring handles plumbing involved in integrating various components in an enterprise application so that you can focus on actual business logic/business use case. Integrating enterprise application can be done in many ways. Each way has its own advantages and disadvantages. We will be discussing the various enterprise integration styles available in some detail in subsequent sections and will also cover the support rendered by Spring to achieve these integration styles in your enterprise application.

Integration Styles

Enterprise Application Integration (EAI) is an application of technology defined as the integration of data and services between applications. The patterns of modern day EAI are usually attributed to Enterprise Integration Patterns, by Gregor Hohpe, et. al., that categorizes and explains many of the integration patterns common to integration solutions. Hohpe, et. al., list four types of integration styles:

1. Shared Database: two systems query the same database for data to be passed. An example of this is when you have two EARs deployed whose entity classes (JPA, Hibernate, etc.) shared common tables for performing various business processes.

2. Remote Procedure Call: each of two systems expose services that the other can call. An example of this is EJB services, or SOAP and REST services.

3. Messaging: two systems connect to a common messaging system and exchange data and invoke behavior using messages. An example of this is the familiar hub-and-spoke JMS architecture.

4. File Transfer: two systems produce files whose payload is the message to be processed by the other system. An example of this is polling a directory or an FTP directory for a file and putting appropriate business logic and processing it.

These styles are disparate because no one solution will work all the time. According to requirement in your application, choose the right style which best fits your requirement. These architectural styles are different with each having its own unique advantages and disadvantages. The standards in JEE fall short to some extent and don’t provide complete solution when integration with other systems.

Shared Database

Integration between two systems can be as simple as joining two tables. Nevertheless, there arise several issues when you try to integrate two systems using this integration methodology. First of all it is difficult to come up with a single schema that will suit the needs of both the application and second is the creation of interdependencies between two systems having diverse requirements and mixing it could as good as mixing oil and water. That means it will never gel together in the ideal enterprise application as we think.

Having said that Shared database has its own advantages like it’s simple and transactional. Some of the disadvantages which can be attributed to this style of integration are that it could be slower and retard or obstruct the database schema evolution over a period of time with more and more features added onto the enterprise application due to changing business dynamics.

Figure 6-1. Shared Database Integration style

Spring framework provides extensive support for this integration style. The support by Spring for this integration style is as below:

  • Extensive support for transaction management
  • Ease of using JDBC using JdbcTemplate
  • Support for Object Relational Mapping (ORM)  integration
  • DataAccessException hierarchy makes exception handling easy
  • Spring Data, an umbrella project in the Spring framework

These will be explained to some extent in the following sections.

Transaction Management

Transaction management is critical in any form of applications that will interact with the database. The application has to ensure that the data is consistent and the integrity of the data is maintained.

Comprehensive transaction support is among the most convincing reasons for using the Spring framework. The Spring framework provides a consistent abstraction for transaction management that delivers various benefits. Some of which are:

  • Consistent programming model across different transaction APIs such as Java Transaction API (JTA), Java Database Connectivity (JDBC), Hibernate, Java Persistence API (JPA), and Java Data Objects (JDO)
  • Declarative transaction management
  • Simpler API to code on
  • Excellent integration with Spring’s data access abstractions

We will be covering Spring’s support for managing transactions in Chapter 8, “Data Access” in detail. I just wanted to bring in this point here so that you will be able to link when we discuss this topic later in subsequent chapter.

Spring JDBC

Using conventional could be clumsy and not so clear way of doing things. Spring makes coding in JDBC easy and elegant using JdbcTemplate.

We will be covering Spring’s support for JDBC in Chapter 8, “Data Access” in detail.

Page Visitors: 2884