57
Frameworks in Java: Hibernate, Apache Struts2, Spring. Darshan Patel 1

Frameworks in java

Embed Size (px)

DESCRIPTION

This presentation is the research work that i had made during my academic years.

Citation preview

Page 1: Frameworks in java

1

Frameworks in Java:

Hibernate,Apache Struts2,

Spring.

Darshan Patel

Page 2: Frameworks in java

2

Acknowledgement

I would like to thank Professor Sunil Joshi for being my dissertation tutor and examiner. Their patient, responsible attitude and meaningful advice help me steer clear of various serious mistakes and direct successfully my dissertation to the final destination. Darshan Patel

Page 3: Frameworks in java

3

• Java web framework has been widely used in industry Java web applications in the last few years, its outstanding MVC design concept and supported web features provide great benefits of standardizing application structure and reducing development time and effort.

• However, after years of evolution, numerous Java web frameworks have been invented with different focuses, it becomes increasingly difficult for developers to select a suitable framework for their web applications.

• In this dissertation, I conduct a general comparison of three popular Java web frameworks: Hibernate, Struts and Spring and I try to help web developers or technique managers gain a deep insight of these frameworks through the comparison and therefore be able to choose the right framework for their web applications.

Page 4: Frameworks in java

4

Introduction • With the increasing need for the maintainability and extensibility of web

applications, it is very important to select a robust, efficient and suitable framework to standardize and bring structure to web application development. Among numerous technologies now existing, many web developers show great preference for the Java web frameworks because of the outstanding design concepts and the popularity of Java programming language. Java web framework is a platform based on Model-View-Control (MVC) design pattern which dictates structure and separates web application into different components to help safeguard it from a potential mess of tangled code. Currently as almost every Java web application adopts Java web frameworks as the implementation of the web presentation tier, the Java web framework has already became an indispensable part of the Java web development.

Page 5: Frameworks in java

5

• In the early days of building Java web applications, developers often used JSP scriptlets and printed out content they wanted to display directly within their scriptlets—the same place where critical business logic was located. Although to some degree this could greatly reduce the time spending and increase the efficiency of development, it soon becomes clear that this technique too tightly coupled the core business code with the presentation, which greatly limits the readability, maintainability and extensibility of a web application. As the elicitation of the concept: “Web MVC”, it is now possible to divide web applications easily into “Model-View-Controller" three tier structure with each tier capable of being developed and tested independently without affecting each other. Although extra integration work for the different tiers is needed, the benefit we could procure from the separation is incontestable. The first mature Java Web MVC implementation is the “JSP Model 2” structure defined by Sun Microsystem, which has been proved as the foundation of building Java web applications .

Page 6: Frameworks in java

6

• The success of the Web MVC has triggered a proliferation of the Java web presentation frameworks. During the last few years, there are a glut of Java web frameworks invented, each of which has its special design concept, advantage and disadvantage, it has thus becomes increasingly difficult for Java web developers to choose the right framework to use. Moreover, because of the complexity and distinctness of design concepts between different frameworks, it often takes months for developers to learn a new framework. Considering the time and effort needed to spend for choosing and learning java web frameworks, the term “framework” has

Page 7: Frameworks in java

7

• actually turned into a “burden” for project teams. To solve this problem, a few researches related to this field have been preformed such as “Architectural models of J2EE Web tier frameworks” [Timo Westkämper, 2004] and “Art of Java Web development” [Neal ford, 2003]. However, the purpose of these researches is to help readers to understand java web presentation tier development, and although they listed and introduced several popular java web frameworks, not enough feature comparison of web frameworks is provided. In addition, Java open source expert Matt Raible has given several conference presentations for comparing java web frameworks, for instance, “Java web framework sweet sport” [Matt Raible,2006] and “Comparing Java web frameworks” [Matt Raible,2007], although in these presentations pros and cons of different framework features have been pointed out, measurements were restricted to concept discussion, there were no detailed examples and practical issues presented, Indeed developers with little experience of a specific framework can barely comprehend the points referring to that framework.

Page 8: Frameworks in java

8

• The goal of this dissertation is to help web developers or technique managers gain deep insight of these frameworks through a comparison and therefore are able to choose the right framework for their web application. This work investigates three popular Java web frameworks: Hibernate, Struts and Spring. After the introduction chapter, the background technology information is presented in chapter two which includes a basic introduction of technologies used in Java web, MVC design pattern information and the concept of Java web frameworks. After second chapter the description of the frameworks will be started which will cover Hibernate, Struts and Spring. The last chapter includes a general conclusion for this dissertation and some future work.

Page 9: Frameworks in java

9

Technology used in Java web

• The core technology used in the Java web is JSP and Servlet. However, in order to build an integrated Java web application, the technologies listed below are also needed:

• Java Bean components • EJB components • JavaServer Pages Standard Tag Library (JSTL) and Expression Language • XML language

Page 10: Frameworks in java

10

Page 11: Frameworks in java

11

Java Servlet technology

• Servlet is designed as a general extensible framework and provides a Java class-based mechanism for handling the web request-response mode.

• When a web client try to visit a Servlet, the Servlet container will first create a “ServletRequest” and “ServletResponse” instance for the clients, then it encapsulates the request information and passes both of the instances to the appointed Servlet. After the execution of the Servlet, the response result will be written into the “ServletResponse” instance and return back to the clients via the Servlet container. The whole process is illustrated in figure 2.2:

Page 12: Frameworks in java

12

JavaServer Page

• JavaServer Page (JSP) offers a simplified, fast way to create dynamic web content, it was developed in 1999 by Sun Microsystem, Inc and introduced to overcome the problems raised by using the pure Servlet for web applications, such as tedious web content generation and the difficulty of maintenance.The nature of the JSP is actually a Servlet, the Servlet container will use an internal “JSP Engine” to compile the JSP pages and save them into RAM memory as a Servlet class if the compilation is successful. However, in contrast to the pure Java code Servlet, the JSP adopt a more flexible mechanism –combination of static HTML page, Java scriptlets, JSTL and its Expression Language– to generate the dynamical content for the web clients which is much more efficient and convenient than directly editing the Servlet java source code. Another difference between Servlet and JSP is that the JSP-Servlet would not be compiled and generated until the first call from the web clients, and if the original JSP page was modified, the container would automatically detect and recompile it without restarting the web application.

Page 13: Frameworks in java

13

JavaBean component

• JavaBean is a Java class which conforms to the special standard based on Sun’s JavaBean specification , it provides a series of private properties and defines public accessing method for each of these properties.

• In JSP page, there are some special tags used to define and visit JavaBean

• <jsp:useBean id=”YourID” scope=”request/session/application” class=” CounterBean”>

• <jsp:setProperty name=”YourID” property=” count” value=”0”>• <jsp:getProperty name=”YourID” property =”count”>

• Originally JavaBean was designed as a reusable software component that can be manipulated visually in a builder tool to make the GUI application more efficient,

Page 14: Frameworks in java

14

• When JSP and JavaBean come into play together, the JSP page focuses on the dynamical generation of web content, it supplies web templates for the application data to fit in, whereas JavaBean components offer business logic and data to the web page.

Page 15: Frameworks in java

15

Enterprise JavaBeans (EJB)

• the Enterprise JavaBeans technology is quite a bit more complex than the "Standard Edition" JavaBeans technology. According to J2EE specification defined by Sun, the EJB components are distributed and must be contained in the EJB containers which could be supplied by the third-part producers and offer the service of security, resource sharing, continuing operations, parallel processing and transaction integration to EJB.

• Same as JavaBeans, EJB supplies the business service for the web application, it does not concern with the user view or anything related to the presentation tier.

Page 16: Frameworks in java

16

JavaServer Pages Standard Tag Library

• JavaServer Pages Standard Tag Library (JSTL) is the technology introduced to overcome the serious shortcoming of JSP: mixing presentation and business logic and difficult to understand and maintain. It supports for common, structural tasks such as iteration and conditionals, tags for manipulating XML documents, internationalization tags, and SQL tags.

• Following are two examples of JSP page showing the request variable “username” value with JSP scriptlets and with JSTL and Expression language technology:

• (1) With JSP Scriptlet: • <%String username = request.gerParameter(“username”); • Out.println(username);%> • (2) With JSTL and its Expression language • <c:out value='${param.username}'/>

Page 17: Frameworks in java

17

XML language

• The Extensible Markup Language (XML) is a general-purpose markup language. It is classified as an extensible language because it allows its users to define their own tags. XML language primary purpose is to facilitate the sharing of structured data across different information systems, particularly via the Internet.

• XML files often behave as the configuration files of the software, in the context of Java web application, the “web.xml” file is the one which define the configurations for Java Servlet, Tag library, security, resource reference and some other initialization configuration.

• The biggest advantage we could receive from the XML configuration file is that we have no need to modify and recompile the source code once we change the low level configurations, we just need to edit the configuration variable in the XML file and restarting the web application.

Page 18: Frameworks in java

18

• The following example consists of four XML sentences which represents the communication information.

• <friend>• <name> abc</name>• <phone> 9925546899</phone>• <address>def</address>• </friend>

Page 19: Frameworks in java

19

Introduction to MVC

• The Model-View-Controller (MVC) design pattern was originally brought forward by Trygve Reenskaug and applied in the SmallTalk-80 environment for the first time, the purpose of it is to implement a dynamic software design which simplifies the maintenance and extension of the software application. MVC seeks to break an application into different parts and define the interactions between these components, thereby limiting the coupling between them and allowing for each one to focus on its responsibilities without worrying about the others. MVC consists of three categories of the components: Model, View and Controller. This means that it separates the input, processing, and output for the applications and constructs them into a Model-View-Controller three tier structure.

Page 20: Frameworks in java

20

Traditional MVC has become outdated

• Although the original MVC pattern worked well for desktop GUI applications, it failed to map directly to the World Wide Web. In the traditional MVC, after the “View” component interacting with the user, typically a button submitting from users, the “Controller” component receives the view-changing events and modified the relative data in the “Model” component, then the “View” component acquires the model-change event from the “Model” and refresh itself to show the updated data to users. However, this process is broken when applying to a web application because of different hardware and software structure between a desktop application and a web application.

Page 21: Frameworks in java

21

Page 22: Frameworks in java

22

Web version MVC: Front Controller Pattern

• the front controller pattern utilizes a core controller, commonly implemented as a Servlet, as the initial point of contact for handling a URL request. This core controller provides a centralized entry point that addresses common services such as security services, delegating business processing, exception strategy and configuration initialization so that the web application could have a centralized, unitive control without resulting in duplicated code.

• In the traditional MVC, the view management and navigation is integrated into the “Controller” component, there is no obvious partition between the view management and other functions. In the context of web MVC, the Front Controller Pattern brings forward the “dispatcher” concept and abstracts them out of the traditional “Controller”. A dispatcher is mainly responsible for view management and navigation, managing the choice of the next view to present to the user,

Page 23: Frameworks in java

23

Page 24: Frameworks in java

24

• Figure 2.4 shows the sequence diagram representing the Front Controller Pattern. When the “Controller” receives UI events such as users’ submit, it will transfer the control right to the “Dispatcher” and “Helper” components, the “Dispatcher” chooses and sends the appropriate view page as a response to the clients according to the result code returned by the “Helper” class. From the figure we could see that the “Controller”, “Dispatcher” and “Helper” together act as the “Controller” role in MVC pattern, and “View”, normally a web page, act as “view” role in MVC pattern.

Page 25: Frameworks in java

25

Introduction to frameworks

• A framework dictates the overall architecture of the application and predefines features in the form of reusable classes, utility classes, and base classes for developers to extend and utilize.

Page 26: Frameworks in java

26

They are the enhancement of JSP and Servlet API

• As people build more and more Java web application, it becomes increasingly clear that although the JSP and Servlet API are extremely useful, they can not deal with the common tasks without the tedious code, the natural of Servlet API is stateless and operation-centric, it just covers the basic infrastructure necessary for building web applications and offers low level abstraction for the developers, developers always need extra effort to deal with problems such as type conversion, exception handling, internationalization and so on, these problems are where the java web framework set foot in.

Page 27: Frameworks in java

27

JSP Model 2

• JSP Model 2 is the first successful Java MVC structure which combines the different Java web technologies together. It makes use of JavaBeans to represent the “Model” and utilizes JavaServer Pages (JSP) and Servlet technique to act as “View” and “Controller” role of MVC.

Page 28: Frameworks in java

28

Page 29: Frameworks in java

29

• The Java Servlet controller in “JSP Model 2” takes charge of handling the requests of clients, creating and managing the JavaBean instances and manipulating and redirecting the suitable view pages for the web clients. The view tier, normally implemented as JSP pages (or other template languages), processes no business logic, it only searches the JavaBean instance created by Servlet and put the dynamic contents into the static view templates. This breakthrough design method clearly defines the circumscription between the presentation tier and business domain model and nails down the work division for the web page designers and application programmers, as a result the more complexity the web application has the more benefit it could obtain from the JSP Model 2 structure.

• Most of Java web frameworks (including the three chosen framework in this dissertation) are built on the basis of the JSP Model 2.

Page 30: Frameworks in java

30

HibernateOverview

• Hibernate is the ORM tool given to transfer the data between a java (object) application and a database (Relational) in the form of the objects. Hibernate is the open source light weight tool given by Gavin King.

• Hibernate is a non-invasive framework, means it wont forces the programmers to extend/implement any class/interface, and in hibernate we have all POJO classes so its light weight.

• Hibernate can run with in or with out server, i mean it will suitable for all types of java applications (stand alone or desktop or any servlets)

• Hibernate is purely for persistence (to store/retrieve data from Database).

Page 31: Frameworks in java

31

Page 32: Frameworks in java

32

Draw Backs of JDBC:

• In JDBC, if we open a database connection we need to write in try, and if any exceptions occurred catch block will takers about it, and finally used to close the connections.

• Here as a programmer we must close the connection, or we may get a chance to get our of connections message…!

• Actually if we didn‘t close the connection in the finally block, then jdbc doesn‘t responsible to close that connection.

• In JDBC we need to write Sql commands in various places, after the program has created if the table structure is modified then the JDBC program doesn‘t work, again we need to modify and compile and re-deploy required, which is tedious.

• JDBC used to generate database related error codes if an exception will occurs, but java programmers are unknown about this error codes.

• In the Enterprise applications, the data flow with in an application from class to class will be in the form of objects, but while storing data finally in a database using JDBC then that object will be converted into text. Because JDBC doesn‘t transfer objects directly.

Page 33: Frameworks in java

33

Page 34: Frameworks in java

34

Advantages of hibernates:• Hibernate supports Inheritance, Associations, Collections• In hibernate if we save the derived class object, then its base class object will also be stored into the

database, it means hibernate supporting inheritance• Hibernate supports relationships like One-To-Many,One-To-One, Many-To-Many-to-Many, Many-To-

One• This will also supports collections like List,Set,Map (Only new collections)• In jdbc all exceptions are checked exceptions, so we must write code in try, catch and throws, but in

hibernate we only have Un-checked exceptions, so no need to write try, catch, or no need to write throws. Actually in hibernate we have the translator which converts checked to Un-checked

• Hibernate has capability to generate primary keys automatically while we are storing the records into database

• Hibernate has its own query language, i.e hibernate query language which is database independent• So if we change the database, then also our application will works as HQL is database independent• HQL contains database independent commands• While we are inserting any record, if we don’t have any particular table in the database, JDBC will

rises an error like “View not exist”, and throws exception, but in case of hibernate, if it not found any table in the database this will create the table for us

• Hibernate supports caching mechanism by this, the number of round trips between an application and the database will be reduced, by using this caching technique an application performance will be increased automatically.

• Hibernate supports annotations, apart from XML• Hibernate provided Dialect classes, so we no need to write sql queries in hibernate, instead we use

the methods provided by that API.

Page 35: Frameworks in java

35

Disadvantages of hibernates:

• Its saying hibernate is little slower than pure JDBC, actually the reason being hibernate used to generate many SQL statements in run time, but i guess this is not the disadvantage

• But there is one major disadvantage, which was boilerplate code issue, actually we need to write same code in several files in the same application, but spring eliminated this

Page 36: Frameworks in java

36

Implementation

Page 37: Frameworks in java

37

Apache Struts 2Overview

• Apache Struts 2 is an elegant, extensible framework for creating enterprise-ready Java web applications.

• The framework is designed to streamline the full development cycle, from building, to deploying, to maintaining applications over time. Apache Struts 2 was originally known as WebWork 2.

• Struts2 is popular and mature web application framework based on the MVC design pattern. Struts2 is not just the next version of Struts 1, but it is a complete rewrite of the Struts architecture.

• The WebWork framework started off with Struts framework as the basis and its goal was to offer an enhanced and improved framework built on Struts to make web development easier for the developers.

• After some time, the Webwork framework and the Struts community joined hands to create the famous Struts2 framework.

Page 38: Frameworks in java

38

Architecture

• From a high level, Struts2 is a pull-MVC (or MVC2) framework. The Model-View-Controller pattern in Struts2 is realized with following five core components:

• Actions• Interceptors• Value Stack / OGNL• Results / Result types• View technologies

• Struts 2 is slightly different from a traditional MVC framework in that the action takes the role of the model rather than the controller, although there is some overlap.

Page 39: Frameworks in java

39

Page 40: Frameworks in java

40

• The above diagram depicts the Model, View and Controller to the Struts2 high level architecture. The controller is implemented with a Struts2 dispatch servlet filter as well as interceptors, the model is implemented with actions, and the view as a combination of result types and results. The value stack and OGNL provide common thread, linking and enabling integration between the other components.

• Apart from the above components, there will be a lot of information that relates to configuration. Configuration for the web application, as well as configuration for actions, interceptors, results, etc.

• This is the architectural overview of the Struts 2 MVC pattern.

Page 41: Frameworks in java

41

Request life cycle:

• Based on the above digram, one can explain the user's request life cycle in Struts 2 as follows:

1. User sends a request to the server for requesting for some resource (i.e pages).

2. The FilterDispatcher looks at the request and then determines the appropriate Action.

3. Configured interceptors functionalities applies such as validation, file upload etc.

4. Selected action is executed to perform the requested operation.5. Again, configured interceptors are applied to do any post-processing if

required.6. Finally the result is prepared by the view and returns the result to the user.

Page 42: Frameworks in java

42

Struts 2 framework features(Advantages):• POJO forms and POJO actions - Struts2 has done away with the Action Forms that were an

integral part of the Struts framework. With Struts2, you can use any POJO to receive the form input. Similarly, you can now see any POJO as an Action class.

• Tag support - Struts2 has improved the form tags and the new tags allow the developers to write less code.

• AJAX support - Struts2 has recognised the take over by Web2.0 technologies, and has integrated AJAX support into the product by creating AJAX tags, that function very similar to the standard Struts2 tags.

• Easy Integration - Integration with other frameworks like Spring, Tiles and SiteMesh is now easier with a variety of integration available with Struts2.

• Template Support - Support for generating views using templates.• Plugin Support - The core Struts2 behaviour can be enhanced and augmented by the use of

plugins. A number of plugins are available for Struts2.• Profiling - Struts2 offers integrated profiling to debug and profile the application. In addition to

this, Struts also offers integrated debugging with the help of built in debugging tools.• Easy to modify tags - Tag markups in Struts2 can be tweaked using Freemarker templates. This

does not require JSP or java knowledge. Basic HTML, XML and CSS knowledge is enough to modify the tags.

• Promote less configuration - Struts2 promotes less configuration with the help of using default values for various settings. You don't have to configure something unless it deviates from the default settings set by Struts2.

• View Technologies: - Struts2 has a great support for multiple view options (JSP, Freemarker, Velocity and XSLT)

Page 43: Frameworks in java

43

Struts 2 disadvantages:

• Bigger learning curve - To use MVC with Struts, you have to be comfortable with the standard JSP, Servlet APIs and a large & elaborate framework.

• Poor documentation - Compared to the standard servlet and JSP APIs, Struts has fewer online resources, and many first-time users find the online Apache documentation confusing and poorly organized.

• Less transparent - With Struts applications, there is a lot more going on behind the scenes than with normal Java-based Web applications which makes it difficult to understand the framework.

Page 44: Frameworks in java

44

SpringOVERVIEW

• Spring framework is an open source Java platform that provides comprehensive infrastructure support for developing robust Java applications very easily and very rapidly.

• Spring framework was initially written by Rod Johnson and was first released under the Apache 2.0 license in June 2003.

• Spring is the most popular application development framework for enterprise Java. Millions of developers around the world use Spring Framework to create high performing, easily testable, reusable code.

• Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 2MB.

• The core features of the Spring Framework can be used in developing any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring framework targets to make J2EE development easier to use and promote good programming practice by enabling a POJO-based programming model.

Page 45: Frameworks in java

45

Architecture

• Spring could potentially be a one-stop shop for all your enterprise applications, however, Spring is modular, allowing you to pick and choose which modules are applicable to you, without having to bring in the rest. Following section gives detail about all the modules available in Spring Framework.

• The Spring Framework provides about 20 modules which can be used based on an application requirement.

Page 46: Frameworks in java

46

Page 47: Frameworks in java

47

Core Container:The Core Container consists of the Core, Beans, Context, and Expression Language modules whose detail is as follows:• The Core module provides the fundamental parts of the framework, including the IoC and

Dependency Injection features.• The Bean module provides BeanFactory which is a sophisticated implementation of the

factory pattern.• The Context module builds on the solid base provided by the Core and Beans modules and it

is a medium to access any objects defined and configured. The ApplicationContext interface is the focal point of the Context module.

• The Expression Language module provides a powerful expression language for querying and manipulating an object graph at runtime.

Data Access/Integration:• The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS and Transaction

modules whose detail is as follows:• The JDBC module provides a JDBC-abstraction layer that removes the need to do tedious

JDBC related coding.• The ORM module provides integration layers for popular object-relational mapping APIs,

including JPA, JDO, Hibernate, and iBatis.• The OXM module provides an abstraction layer that supports Object/XML mapping

implementations for JAXB, Castor, XMLBeans, JiBX and XStream.• The Java Messaging Service JMS module contains features for producing and consuming

messages.• The Transaction module supports programmatic and declarative transaction management for

classes that implement special interfaces and for all your POJOs.

Page 48: Frameworks in java

48

Web:The Web layer consists of the Web, Web-Servlet, Web-Struts, and Web-Portlet modules whose detail is as follows:• The Web module provides basic web-oriented integration features such as multipart file-

upload functionality and the initialization of the IoC container using servlet listeners and a web-oriented application context.

• The Web-Servlet module contains Spring's model-view-controller (MVC) implementation for web applications.

• The Web-Struts module contains the support classes for integrating a classic Struts web tier within a Spring application.

• The Web-Portlet module provides the MVC implementation to be used in a portlet environment and mirrors the functionality of Web-Servlet module.

Miscellaneous:There are few other important modules like AOP, Aspects, Instrumentation, Web and Test modules whose detail is as follows:• The AOP module provides aspect-oriented programming implementation allowing you to

define method-interceptors and pointcuts to cleanly decouple code that implements functionality that should be separated.

• The Aspects module provides integration with AspectJ which is again a powerful and mature aspect oriented programming (AOP) framework.

• The Instrumentation module provides class instrumentation support and class loader implementations to be used in certain application servers.

• The Test module supports the testing of Spring components with JUnit or TestNG frameworks.

Page 49: Frameworks in java

49

Advantages of Spring Framework:• Spring enables developers to develop enterprise-class applications using POJOs. The benefit of

using only POJOs is that you do not need an EJB container product such as an application server but you have the option of using only a robust servlet container such as Tomcat or some commercial product.

• Spring is organized in a modular fashion. Even though the number of packages and classes are substantial, you have to worry only about ones you need and ignore the rest.

• Spring does not reinvent the wheel instead, it truly makes use of some of the existing technologies like several ORM frameworks, logging frameworks, JEE, Quartz and JDK timers, other view technologies.

• Testing an application written with Spring is simple because environment-dependent code is moved into this framework. Furthermore, by using JavaBean-style POJOs, it becomes easier to use dependency injection for injecting test data.

• Spring's web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks such as Struts or other over engineered or less popular web frameworks.

• Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into consistent, unchecked exceptions.

• Lightweight IoC containers tend to be lightweight, especially when compared to EJB containers, for example. This is beneficial for developing and deploying applications on computers with limited memory and CPU resources.

• Spring provides a consistent transaction management interface that can scale down to a local transaction (using a single database, for example) and scale up to global transactions (using JTA, for example).

Page 50: Frameworks in java

50

Dependency Injection (DI):

• The technology that Spring is most identified with is the Dependency Injection (DI) flavor of Inversion of Control. The Inversion of Control (IoC) is a general concept, and it can be expressed in many different ways and Dependency Injection is merely one concrete example of Inversion of Control.

• When writing a complex Java application, application classes should be as independent as possible of other Java classes to increase the possibility to reuse these classes and to test them independently of other classes while doing unit testing. Dependency Injection helps in gluing these classes together and same time keeping them independent.

• What is dependency injection exactly? Let's look at these two words separately. Here the dependency part translates into an association between two classes. For example, class A is dependent on class B. Now, let's look at the second part, injection. All this means is that class B will get injected into class A by the IoC.

• Dependency injection can happen in the way of passing parameters to the constructor or by post-construction using setter methods. Dependency Injection is the heart of Spring Framework.

Page 51: Frameworks in java

51

Aspect Oriented Programming (AOP):

• One of the key components of Spring is the Aspect oriented programming (AOP) framework. The functions that span multiple points of an application are called cross-cutting concerns and these cross-cutting concerns are conceptually separate from the application's business logic. There are various common good examples of aspects including logging, declarative transactions, security, and caching etc.

• The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. Whereas DI helps you decouple your application objects from each other, AOP helps you decouple cross-cutting concerns from the objects that they affect.

• The AOP module of Spring Framework provides aspect-oriented programming implementation allowing you to define method-interceptors and pointcuts to cleanly decouple code that implements functionality that should be separated.

Page 52: Frameworks in java

52

Web feature Comparison(Data Analysis)Struts 2 over Spring

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

Page 53: Frameworks in java

53

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

• 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

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

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

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

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

Page 54: Frameworks in java

54

Spring over Struts2• Spring provides a very clean division between controllers, JavaBean models, and views. • Spring's MVC is very flexible. Unlike Struts, which forces your Action and Form objects into

concrete inheritance (thus taking away your single shot at concrete inheritance in Java), Spring MVC is entirely based on interfaces. Furthermore, just about every part of the Spring MVC framework is configurable via plugging in your own interface. Of course we also provide convenience classes as an implementation option.

• Spring, like WebWork, provides interceptors as well as controllers, making it easy to factor out behavior common to the handling of many requests.

• Spring MVC is truly view-agnostic. You don't get pushed to use JSP if you don't want to; you can use Velocity, XLST or other view technologies. If you want to use a custom view mechanism - for example, your own templating language - you can easily implement the Spring View interface to integrate it.

• Spring Controllers are configured via IoC like any other objects. This makes them easy to test, and beautifully integrated with other objects managed by Spring.

• Spring MVC web tiers are typically easier to test than Struts web tiers, due to the avoidance of forced concrete inheritance and explicit dependence of controllers on the dispatcher servlet.

• The web tier becomes a thin layer on top of a business object layer. This encourages good practice. Struts and other dedicated web frameworks leave you on your own in implementing your business objects; Spring provides an integrated framework for all tiers of your application.

Page 55: Frameworks in java

55

Future Direction

• This dissertation is limited to comparative study of 3 most common frameworks. But java technology contains more than 30 frameworks which are used for different purposes in IT industries.

• Still more comparative study is possible with following frameworks which are also widely used now a day.

Page 56: Frameworks in java

56

Page 57: Frameworks in java

57

Summary

• Java web framework is a set of related classes and other supporting elements that make Java web application development easier by supplying pre-built parts. Frameworks become popular because they ease the complexity and enable web developers to write at a high level of abstraction without compromising the application content. However, to take full advantage of frameworks` benefit, necessary studies must be done to find out the optimum framework applied to the application. The main purpose of this dissertation was to help web developers or technique managers gain deep insight of three popular Java web framework: Hibernate, Struts2, and Spring through the comparison conducted in this these and try to conclude the best suited web application types of these frameworks.