Spring vs Struts 2.0

While creating J2EE applications, it needs to be decided some times which technology we should go for – Struts or Spring. This is some points comparison between Spring and Struts.

1. In most of the key features compared, Spring MVC and Struts 2 are equally good, except in the UI supports. It seems to me Spring MVC just provides tags for basic HTML form tags while Struts/WebWork 2 provides many out-of-box JSF-styled complex and composite tags, such as:
a) Struts 2 integrates with Dojo AJAX framework closely and provides many complex UI components out-of-box, such as datepicker, tooltips, etc.
b) Struts 2 has AJAX theme.
c) Struts 2 tags are stylesheet-driven, making it easier to develop consistent pages.
d) Struts 2 checkboxes are stateful, and require no special handling.
The recent release of Spring 2.0 does not seem to have any work on this area.

2. Struts is mainly a presentation layer framework, like redirecting to a particular page ,doing client side validations etc which otherwise very tedious using jsp and servlets. Spring is a complete J2EE framework having seven independent layers which can be used all together or few layers integrated with some other framework. Spring provides declarative transaction management and AOP. One layer of spring is for presentation purpose like struts but for only presentation layer, struts is better than spring.

3. Struts has been around a long time and has been popular for years – there’s a wealth of knowledge about it in the user community and more literature around

4. If you want a bunch of taglibs that generate form fields and so forth, Struts is probably the better choice.

5. Our UI is mostly click-driven and light on data and validation. It seems to me that most people run into difficulties with Struts when they start moving a lot of data from HTTP into the model. We didn?t have that problem .

6. Spring does not present a framework for implementing business/domain logic. It helps you create a Controller and a View for your application, no Model though. Spring is a fully fledged application framework, that has a large stack of sub projects.

7. As for spring, if we look at its history, it started as an effort for supplying a solution for enterprise java applications, and to replace EJBs (while it also provided integration with EJBs for people who didn’t want to ditch that). Spring is much more than an MVC framework. It provides dependency injection, AOP, integration with almost every known framework, a security framework (a separate sub-project), and a lot of other stuff. Struts 2 and hibernate integrate easily with spring, so you might like to add it to your stack, without ditching struts 2
8. If you’re going to use Spring for other middleware services, and you have no Struts expertise in house, then it would be simplest to go with SpringMVC. If you know Struts well or have team members who do, or you already have a Struts project, it may make sense to stick with it.

So, basically, it depends on the requirements and the resources what and how you want to achieve which will decide what is to be used, Stuts 2.0 or Spring.


Life Cycle Management of a Spring Bean

1) Introduction

This article would brief about how a Spring Bean is managed in IOC (Inversion of Control) Container. Spring Beans exist within the Container as long as they are needed by the Appplication. There are various life-cycle interfaces and methods that will be called by the IOC Container.

2) Bean Life Cycle

A Spring Bean represents a POJO component performing some useful operation. All Spring Beans reside within a Spring Container also known as IOC Container. The Spring Framework is transparent and thereby hides most of the complex infrastructure and the communication that happens between the Spring Container and the Spring Beans. This section lists the sequence of activities that will take place between the time of Bean Instantiation and hand over of the Bean reference to the Client Application.

  1. The Bean Container finds the definition of the Spring Bean in the Configuration file.
  2. The Bean Container creates an instance of the Bean using Java Reflection API.
  3. If any properties are mentioned, then they are also applied. If the property itself is a Bean, then it is resolved and set.
  4. If the Bean class implements the BeanNameAware interface, then the setBeanName() method will be called by passing the name of the Bean.
  5. If the Bean class implements the BeanClassLoaderAware interface, then the method setBeanClassLoader() method will be called by passing an instance of the ClassLoader object that loaded this bean.
  6. If the Bean class implements the BeanFactoryAware interface, then the method setBeanFactory() will be called by passing an instance of BeanFactory object.
  7. If there are any BeanPostProcessors object associated with the BeanFactory that loaded the Bean, then the method postProcessBeforeInitialization() will be called even before the properties for the Bean are set.
  8. If the Bean class implements the InitializingBean interface, then the method afterPropertiesSet() will be called once all the Bean properties defined in the Configuration file are set.
  9. If the Bean definition in the Configuration file contains a 'init-method' attribute, then the value for the attribute will be resolved to a method name in the Bean class and that method will be called.
  10. The postProcessAfterInitialization() method will be called if there are any Bean Post Processors attached for the Bean Factory object.
  11. If the Bean class implements the DisposableBean interface, then the method destroy() will be called when the Application no longer needs the bean reference.
  12. If the Bean definition in the Configuration file contains a 'destroy-method' attribute, then the corresponding method definition in the Bean class will be called.


Request life cycle of Spring web applications

This post will analyse the request life cycle of Spring web applications with the codes of Spring Framework MVC application I did in lab.

1. Browser sends request, received by DispatcherServlet.

DispatcherServlet is set in war/WEB-INF/web.xml.



All the reqests as the name of *.htm will be handled by springapp, which is a DispatcherServlet.

2. To figure which controller to use.

<bean id=”urlMapping”>
<property name=”mappings”>
<prop key=”/hello.htm”>springappController</prop>
<prop key=”/priceincrease.htm”>priceIncreaseForm</prop>

This codes in war/WEB-INF/springapp-servlet.xml is mapping /hello.htm and /priceincrease.htm to 2 controllers separately.

3. Dispatcher server requests Controller, controller returns ModelAndView object.

In src/web/SpringappController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String now = (new java.util.Date()).toString();
logger.info(“returning hello view with ” + now);

Map myModel = new HashMap();
myModel.put(“now”, now);
myModel.put(“products”, getProductManager().getProducts());

return new ModelAndView(“hello”, “model”, myModel);

The controller returns a ModelAndView object whose viewName is “hello”, modelName is “model” and model object is a Map object named as myModel.

4. If ModelAndView contains logical name for a View, DispatcherServlet queries ViewResolver for the View object that will render the response.

<bean id=”viewResolver”>
<property name=”viewClass”>
<property name=”prefix”><value>/WEB-INF/jsp/</value></property>
<property name=”suffix”><value>.jsp</value></property>

This codes will add prfix and suffix to the viewName of ModelAndView object, in this example, hello will be fixed as /WEB-INF/jsp/hello.jsp .

5. DispatcherServlet requests the View Object. /WEB-INF/jsp/hello.jsp will be shown on browser.

Inversion of Control / Dependency Injection

In early 2004, Martin Fowler asked the readers of his site: when talking about Inversion of Control: “the question, is what aspect of control are they inverting?”. After talking about the term Inversion of Control Martin suggests renaming the pattern, or at least giving it a more self-explanatory name, and starts to use the term Dependency Injection. His article continues to explain some of the ideas behind Inversion of Control or Dependency Injection. If you need a decent insight: http://martinfowler.com/articles/injection.html

Overview of Spring

Spring contains a lot of functionality and features, which are well-organized in seven modules shown in the diagram below. This section discusses each the of modules in turn.

The Core package is the most fundamental part of the framework and provides the Dependency Injection features allowing you to manage bean container functionality. The basic concept here is the BeanFactory, which provides a factory pattern removing the need for programmatic singletons and allowing you to decouple the configuration and specification of dependencies from your actual program logic.

On top of the Core package sits the Context package, providing a way to access beans in a framework-style manner, somewhat resembling a JNDI-registry. The context package inherits its features from the beans package and adds support for text messaging using e.g. resource bundles, event-propagation, resource-loading and transparent creation of contexts by, for example, a servlet container.

The DAO package provides a JDBC-abstraction layer that removes the need to do tedious JDBC coding and parsing of database-vendor specific error codes. Also, the JDBC package provides a way to do programmatic as well as declarative transaction management, not only for classes implementing special interfaces, but for all your POJOs (plain old java objects).

The ORM package provides integration layers for popular object-relational mapping APIs, including JDO, Hibernate and iBatis. Using the ORM package you can use all those O/R-mappers in combination with all the other features Spring offers, like simple declarative transaction management mentioned before.

Spring’s AOP package provides an AOP Alliance compliant aspect-oriented programming implementation allowing you to define, for example, method-interceptors and pointcuts to cleanly decouple code implementing functionality that should logically speaking be separated. Using source-level metadata functionality you can incorporate all kinds of behavioral information into your code, a little like .NET attributes.

Spring’s Web package provides basic web-oriented integration features, such as multipart functionality, initialization of contexts using servlet listeners and a web-oriented application context. When using Spring together with WebWork or Struts, this is the package to integrate with.

Spring’s Web MVC package provides a Model-View-Controller implementation for web-applications. Spring’s MVC implementation is not just any implementation, it provides a clean separation between domain model code and web forms and allows you to use all the other features of the Spring Framework like validation.