You are on page 1of 97

Academic Year 2013/2014

Warsaw University of Technology


Faculty of Electronics and Information Technology
Electrical and Computer Engineering

MASTER OF SCIENCE THESIS

Ewelina Katarzyna Smyk

Overview of technologies and methods designed to build


Java Enterprise web applications. Comparison of Spring
and Play Frameworks based on proprietary application.

Supervisor
Dr inż. Łukasz Skonieczny

Evaluation: ............................................. .........


Signature of the Head
of Examination Committee
Electrical and Computer Engineering

Date of Birth: 1990.02.08

Starting Date of Studies: 2013.02.20

Curriculum Vitae

I was born in Krasnystaw on 8th February, 1990. Between 2006 and 2009 I attended
Cyprian Kamil Norwid Secondary School in Krasnystaw. I gained my bachelor’s degree in
computer science at Lublin University of Technology in 2013. In 2013 I started a M.Sc.
studies in Electrical and Computer Engineering at Faculty of Electronics and Information
Technologies, Warsaw University of Technology. During the studies I worked as a Java
programmer.

..................................................
Signature of the Student

Master of Science Examination

Examination was held on: ..............................................................................................20__

With the result: ........................................................................................................................

Final Result of the Studies: .....................................................................................................

Suggestions and Remarks of the B.Sc. Examination Committee: ..........................................

..................................................................................................................................................

..................................................................................................................................................

2
SUMMARY
The scope of the thesis covers an overview of technologies and methods designed to build
Java Enterprise Web applications as well as examining the possibility of combining
various solutions by trying to implement a test application created using the Spring
Framework with Java Server Faces – view technology intended for the Java Enterprise
Edition platform. The thesis also compares Spring and Play Frameworks based on a
proprietary application.

Keywords:

Spring, Play, JavaServer Faces, JavaServer Pages, web applications

PRZEGLĄD TECHNOLOGII PRZEZNACZONYCH DO BUDOWY APLIKACJI


INTERNETOWYCH DLA PRZEDSIĘBIORSTW W JĘZYKU JAVA. PORÓWNANIE
SZKIELETÓW APLIKACJI SPRING ORAZ PLAY NA PODSTAWIE AUTORSKIEJ
APLIKACJI.

Przedmiotem niniejszej pracy jest przegląd technologii oraz metod wytwarzania


oprogramowania przeznaczonych do budowy aplikacji internetowych dla przedsiębiorstw
w języku Java jak również sprawdzenie możliwości łączenia poszczególnych rozwiązań
poprzez próbę implementacji aplikacji napisanej za pomocą szkieletu Spring z użyciem
JavaServer Faces – technologii widoku przeznaczonej dla platformy Java Enterprise
Edition. Praca porównuje również dwa szkielety aplikacji internetowych Spring oraz Play
na podstawie autorskiej aplikacji

Słowa kluczowe:
Spring Framework, Play Framework, JavaServer Pages, JavaServer Faces, aplikacje
webowe

3
Table of Contents
1. Introduction.......................................................................................................................6
2. Objectives and scope of Master Thesis............................................................................8
3. Web applications..............................................................................................................9
3.1. A brief introduction..................................................................................................9
3.2. How do web applications work..............................................................................10
3.3. Three-layered web application model.....................................................................12
3.4. Http protocol............................................................................................................13
4. Java web technologies specifications and implementations............................................15
4.1. Introduction to Java Enterprise Edition platform....................................................15
4.2. JEE application model............................................................................................16
4.3. Distributed multitiered applications .......................................................................17
4.4. Application server....................................................................................................18
4.5. Web container..........................................................................................................21
4.6. Servlet Container or Application Server.................................................................23
5. Java View technologies and frameworks........................................................................25
5.1. Servlets ................................................................................................25
5.2. Servlet life-cycle......................................................................................................26
5.3. Request-response.....................................................................................................28
5.4. Introduction to JavaServer Pages............................................................................29
5.5. JavaServer Page Lifecycle.......................................................................................30
5.6. Introduction to JavaServer Faces.............................................................................32
5.7. JavaServer Faces Architecture.................................................................................34
5.8. JavaServer Faces Life-cycle....................................................................................36
6. Spring Framework...........................................................................................................39
6.1. Introduction to Spring Framework..........................................................................39
6.2. The advantages of using the Spring Framework.....................................................41
6.3. Inversion of Control and Dependency Injection......................................................42
6.4. Spring Web MVC introduction...............................................................................45
6.5. Spring Web MVC architecture................................................................................46
6.6. Spring Web MVC basic configuration....................................................................48
7. Play Framework..............................................................................................................50
7.1. Introduction to Play Framework..............................................................................50
7.2. The advantages of using the Play Framework.........................................................52
7.3. Play Framework architecture...................................................................................54
7.4. Application structure...............................................................................................55
7.5. Controllers in Play...................................................................................................57
7.6. The Play Scopes.......................................................................................................59
8. Comparison of Spring and Play Frameworks based on a prototype of application for
school management system..................................................................................................62
8.1. Application overview..............................................................................................63
8.2. View technologies...................................................................................................67
8.3. Redirection between the views...............................................................................69
8.4. Passing parameters between Controllers and Views...............................................71
8.5. Model.......................................................................................................................73
9. Comparison of Spring and Play Frameworks based on technical domains....................78
9.1. Scalability................................................................................................................80
9.2. Performance.............................................................................................................81

4
9.3. Separation of concerns.............................................................................................82
9.4. Testability ...............................................................................................................82
9.5. Persistency...............................................................................................................83
9.6. Security...................................................................................................................84
9.7. Maintainability........................................................................................................85
9.8. Summary..................................................................................................................86
10. Comparison of Spring and Play Frameworks based on performance tests of school
management system.............................................................................................................87
10.1. Test number 1 – Displaying the list of student subjects........................................87
10.2. Test number 2– Handling the form data ...............................................................90
10.3. Test number 3 – maximum load............................................................................93
11. Conclusions...................................................................................................................94
12. Bibliography..................................................................................................................96
12.1. Basic bibliography.................................................................................................96
12.2. Additional bibliography.........................................................................................96

5
1. Introduction

In an attempt to analyze how application development has changed within the past
few years, we might have noticed a significant shift from desktop applications to web
applications. The Web has evolved as the major platform for enterprise applications. The
increasing popularity of web applications caused the emergence of new technologies. With
so many platforms, technologies, methodologies and tools emerging with the web
development industry, application architects must face the problem which solutions to
choose. Forrsights Software Survey report from 2010 [IX] stated that the most popular
development platforms for medium and large companies were Java and .NET. Over the
years those two platforms have developed many internal solutions. Comparing or
describing those platforms goes beyond the scope of this Master Thesis. Due to the fact
that I work as a Java programmer, I have learned new technologies and developed current
solutions in ‘Java world’. As a result, I would like to expand my knowledge in this sector
and to overview the methods and technologies developed in Java Platform in my Master
thesis.
Java has become dominant in the world of enterprise application development. This
dominance was due to launching the Java Enterprise Edition Platform onto the market, thus
providing an application programming interface and runtime environment for developing
and running enterprise software. Without doubt, some significant changes have appeared in
programming world since 2010. Architects and developers had considered Java Enterprise
Edition Platform to be too heavy and turned to lightweight solutions named Frameworks.
We may say that frameworks are abstractions, tools, methods designed to help create
software which will be easy to maintain, expand, re-use or transfer to another developer
team. Frameworks enable functionality and provide modules offering a number of services.
As a result, they simplify the process of software development. They define lists of good
programming practices and conventions that significantly affect the minimization of time
and effort required to create a good product. Most of web java frameworks, for example
Spring, are based on the Java Enterprise Edition platform which allows us to use developed
functionalities, but unfortunately it carries a cost, the main problems being too much
layers in the web application architecture, difficult HTTP requests debugging and long

6
application deployment. To avoid these issues developers were forced to create solutions
which are based on Java and Java virtual machine but are also independent from JEE
platform. The example of such solution is Play Framework.
As we can see, even if we have decided which programming platform to choose,
there is also a wide range of strategies, technologies and tools involved. The choice is not
easy and may influence the maintenance of the system. Every professional architect should
be aware of all possible solutions to be able to choose the best one for their current project.
In my thesis I will try to make an overview of the selected web technologies based on the
java virtual machine, as well as to present their advantages and disadvantages.

7
2. Objectives and scope of Master Thesis

The aim of my Master’s thesis is to study the web application development process
as well as the process of choosing the most suitable technologies connected with objectives
and needs which applications must face. The next goal is an overview of selected
technologies and methods designed to build Java Enterprise Web applications as well as
examining the possibility of combining various solutions by trying to implement a test
application created using the Spring Framework with Java Server Faces – view technology
intended for the Java Enterprise Edition platform. The main objective is to compare Spring
and Play Framework basing on a prototype of an application for school management
system.

Scope of the Master’s thesis includes:

1. Representation of how a web application works.


2. Introduction of Java web technologies specifications and implementations.
3. Overview of Java View technologies and frameworks.
4. Characterization of Spring and Play frameworks.
5. Elaborating on the concept and development of a web application designed to
improve the information flow at Schools, consisting of three main modules:
- evaluation of student’s achievements;
- students’ attendance;
- Canteen.
6. Comparison of Spring and Play frameworks based on a proprietary application.
7. Description of results and conclusions

8
3. Web applications
3.1. A brief introduction
A web application is application software installed on a server communicating with
user by a web browser. It is created in a browser-supported programming language and
stands out from a website by being self-sufficient. Websites are designed to encourage
users to browse and surf between other sites with limited number of complex functionality.
Projecting web apps puts special emphasis on interactivity of interface, integration with
web-based available technologies and advanced functionality. Websites are oriented on the
provision of information while web applications are primarily a tool for a specific task,
however, presented distinction is not clear and rigid. Moreover, the most important in web
applications is the emphasis on interaction, working with the data and efficient
implementation of the objectives, rather than gaining attention.

9
3.2. How do web applications work
The web application is a collection of dynamic and static web pages. Static page
remains unchanged at the time when user requests it. It is sent by the web server to the
browser without any modifications. A dynamic page is modified by the server before
sending to the browser. Static website consists of a set of interrelated HTML pages and
files. It is stored on a computer that is running the web server. A web server is software
that provides web pages in response to requests sent out by the browser. Page request is
generated when the user clicks on a link on a web page, selects the tab in the browser, or
enters a URL in the browser address bar. The final content of a static web page is
determined by the creator of the page and does not change when the page is downloaded.
When a site visitor requests the static page, web server receives this request, reads it, finds
adequate page and sends it to the browser. This process is presented in figure 3.1

Figure 3.1: Processing static web pages[I]

1. A web browser requests a static page.


2. A web server finds a page.
3. A web server sends a page to the requesting browser.

10
When a web browser requests a dynamic page, server passes the page to software
responsible for processing it. Software which finishes the page is called an application
server. Application server reads page code and complements the content according to the
instructions in the code. Example of this process is shown in the figure 3.2.

Figure 3.2: Processing dynamic pages[I]

1. A web browser requests a dynamic page.


2. A web server finds the page and passes it to the application server.
3. An application server scans a page for instructions and finishes the page.
4. An application server passes the finished page back to the web server.
5. A web server sends the finished page to the requesting browser.

11
3.3. Three-layered web application model
The first layer is a web browser, which can be named as a web client. It displays the
pages receiver from the server. Pages are generated in the form of html,xhtml, xml
documents. Such documents are converted by dynamic content generation technology tools
such as servlets, java server pages, java server faces and displayed in the web layer. Client
and web layers are regarded as presentation layer. Such division allows focusing on the
aspect of visualization without dipping into the details of the business logic. The second
layer is the business layer, where all calculations, operations on data and analyses take
place. The third layer is the database with customer data. It is named Enterprise
Information Systems and includes all sources of data for the business logic layer. Such
sources include: databases and information systems existing in the enterprise.
Model of three –layered web application is presented in the figure 3.3.

Figure 3.3: Three-layered web application model.

12
3.4. Http protocol
A web client communicates with application server by HTTP protocol. The HTTP
is a text protocol based on TCP, it uses the communication model of a client-server. After
connecting with server HTTP, the client gives him a message containing the HTTP
request. Each request causes a further embodiment of the presentation logic code. The
HTTP server responds to the request and sends document. After this process, the server
closes the connection.
During the client-server communication, the client passes parameters to call
application server. These parameters can be transferred via the HTTP protocol in two
ways:
 GET is the order in which the parameters are included in the URL
 POST parameters are in the body of the HTTP request, the body represents the data
sent by the HTTP client to the server.

Communication is done using the standard addressing system resource URL:

http:// <host> [: <port>] [ <path> [? <query>]]

where:
• <host> - the name of the server or IP address,
• <port> - specific server port,
• <path> - path to the resource in the server file system,
• <query> - zestaw parametrów dodatkowych żądania.

What is very important, HTTP is a stateless protocol. It treats each request as an


independent transaction without any connections to previous requests. Communication
consists of pairs of request and response which are independent for each other. Such
protocol does not require the server to retain session information. This means that the
server is not able to determine whether the HTTP requests from the same user or from
other independent users. This is a great handicap for web applications. This problem is
solved by providing a mechanism emulating the session - Http Session. The principle of

13
this mechanism is simple, each client receives a unique identifier - identifier of the session,
from the server. Typically, it is stored in the Cookie variable. Thanks to this application,
server receives the user identifier during following requests. The application server has
tables where the session identifier is associated with a set of JAVA programming objects
that represent the state of the session. As the JEE servlets are low-level mechanisms they
have the ability to read and write objects corresponding to the session state. Session state
can be deleted after a certain time limit or after the explicit deletion.

14
4. Java web technologies specifications and
implementations
4.1. Introduction to Java Enterprise Edition platform
Java Enterprise Edition is a set of standards and practices of software development
introduced by Sun Microsystems. J2EE was designed to improve the quality of business
software by introducing multiple layers designed app, so business or logic part of
application is always separated from the visual. J2EE technology is Service Oriented
Architecture based on the Java programming language. In practice, it is a group of
omnifarious technologies and frameworks enabling creating enterprise applications. This
standard was introduced in 1999, only four years after the Java language. For several years
it was the dominant technology in projects based on web architecture. Unlike most
business platform, JEE is not a closed solution developed by the creator and sole supplier,
but an open set of standards used by many software vendors, which ensures much more
support for this technology in the future. Thanks to the existence of many tools and
transparent standards for application development, JEE platform is essentially a technology
to construct systems from ready, proven components. This approach greatly reduces the
time required for the design, programming and implementation. What’s more the open
architecture lowers the price of the target system which is not encumbered by high
licensing costs. The most important goal of the platform is to simplify development. It can
be achieved by providing a common foundation for the various kinds of components. The
Platform provides productivity improvements, such as annotations replacing XML
configuration, Plain Old Java Objects and simple packaging.

15
4.2. JEE application model

Model of JEE applications is based on the Java virtual machine and the Java
programming language. It provides the much needed values for business applications such
as productivity, portability, security. The platform is designed to create applications that
implement services for each members of the business world. There is a distinction
between: ERP systems, project management, warehouse management and many others.
The application can be used by employees of each sector suppliers, employees, customers.
Precisely for this reason, applications are complicated and complex internally. It is possible
to have access to the data from different sources. In order to efficient management and
possibility for control, support for business part of application is located in the middle tier.
This layer runs on a dedicated server and works closely with the business services of the
company. In “Classic” JEE Architecture business logic is implemented as Enterprise Java
Beans components. EJB has traditionally been regarded as essential to implementing JEE
applications. Described application model is designed in a way that allows implementation
of business services as multi-tier applications. This approach provides simpler application
management, availability and scalability. In this model standard system services are
provided by the platform, while the developer implements the business layer and the
presentation logic.

16
4.3. Distributed multitiered applications
Distributed Multitier Application model is used by Java EE platform for enterprise
applications. Logic of application is divided into components conforming to provide
functions. These components are placed on diverse machines, depending on the tier to
which they belong. There can be distinguished three main machines such as the client
machine, Java EE server and Enterprise information system.
• Client machine : client-tier components
• Java EE server : web-tier components, business-tier components
• Enterprise information system: EIS-tier software
Components are software units that are self-contained and assembled into an application
with its related classes and files. Figure 4.1 shows multitier Java EE application divided
into the tiers described above.

Figure 4.1: Three-tier JEE architecture [II]

Three or the four tiered applications extend standard client-server applications by placing
multithreaded server between the client and back-end storage.

17
4.4. Application server
In the previous chapter three-layered web application model was presented in very
general way. There were awarded three parts of application: user interface, application
server and data base. This chapter particularizes issue on the second layer, namely
application server. It can be said that a system software upon which web or desktop
applications run is an application server. It acts as a set of components available to the
programmer through an API defined by the platform itself. Application Servers consist of
runtime libraries, web server connectors, database connectors, computer programming
languages and the administration code needed to configure, deploy, manage and connect
these components on a web host. Web applications run on top of application servers and
call the components and runtime libraries the application server offers. There are many
application servers and the choice impacts the reliability, cost, scalability, maintainability
and performance of web application. In general programmers develop programs according
to the specification of the application server. The biggest drawback of this approach is
dependence on a particular vendor. In the case of java language Java Enterprise Edition
Platform defines the core set of API and features of Java Application Servers. Java
application programmers do not develop programs according to the application server but
according to the Java EE specification. Such application is vendor independent and can be
deployed in any java EE server.
Comparison of features and functionalities of application servers hosting Java environment
is presented in the table 4.1.
Last Servle
Java EE JSP
Product Vendor Edition release t License
compatibility spec
date spec
2013-07-
ColdFusion Adobe Systems 10.0.11 6 2.5 2.1 Proprietary
09
Dynamo AS ATG 6.3 2005-03 1.3 2.3 1.2 Proprietary
2005-03-
Enhydra Lutris 5.1.9 No GPL
23
Enterprise Server Borland 6.7 2007-01 1.4 2.4 2.0 Proprietary
2013-05- Apache
Geronimo ASF 3.0.1 6 Full Platform 3.0 2.2
28 License
GlassFish CDDL,
GlassFish 4.0 2013-05 7 Full Platform 3.1 2.3
Community GPL

18
Last Servle
Java EE JSP
Product Vendor Edition release t License
compatibility spec
date spec
2007-09-
GlassFish Server Oracle Corporation 9.1 5 2.5 2.1 Proprietary
17
iPlanet Web 2007-12-
Oracle Corporation 7.0u5 Yes 2.5 2.1 Proprietary
Server 21
JBoss Enterprise
2013-12-
Application Red Hat 6.2.0 6 Full Platform 3.0 2.2 LGPL
05
Platform
2014-05- Apache
Jetty Eclipse Foundation 9.1.5 7 (partial) 3.1 2.3
05 2.0, EPL
JEUS TmaxSoft 7 2012-06 6 Full Platform 3.0 2.2 Proprietary
OW2 Consortium
2013-10-
JOnAS (formerly 5.3 6 Web Profile 3.0 2.2 LGPL
04
ObjectWeb)
2007-11-
JRun Adobe Systems 4 updater 7 1.3 2.3 1.2 Proprietary
06
NetWeaver
2011-05-
Application SAP AG 7.3 5 2.5 2.1 Proprietary
31
Server
Oracle Containers
Oracle Corporation 10.1.3.5.0 2009-08 1.4 2.4 2.0 Proprietary
for J2EE
Orion Application 2006-03-
IronFlare 2.0.7 1.3 2.3 1.2 Proprietary
Server 09
Resin Servlet
Caucho 2013-04-
Container (Open 4.0.36 6 Web Profile 3.0 2.2 GPL
Technology 25
Source)
Resin
Professional Caucho 2013-04-
4.0.36 6 Web Profile 3.0 2.2 proprietary
Application Technology 25

Server
2011-07-
Siwpas MechSoft 2.0.0 yes 3.0 2.2 Proprietary
29
TomEE ASF 1.6.0 2013-11- 6 Web Profile 3.0 2.2 Apache
20
License
WebLogic Server Oracle Corporation 12.1.3 2014-06- 6 Full Platform 3.0 2.2 Proprietary
26

19
Last Servle
Java EE JSP
Product Vendor Edition release t License
compatibility spec
date spec
(formerly BEA

Systems)
2008-09-
WebObjects Apple Inc. 5.4.3 partial Proprietary
15
WebSphere
2012-06-
Application IBM 8.5.0.0 6 Full Platform 3.0 2.2 Proprietary
15
Server
WebSphere AS
2013-06-
Community IBM 3.0.0.4 6 Full Platform 3.0 2.2 Proprietary
21
Edition
2014-05-
WildFly Red Hat 8.1.0.Final 7 Full Platform 3.1 2.3 LGPL
30
Table 4.1: Comparison of Java application servers[III]

An application server usually runs behind a web Server, which stores process and
delivers web pages to clients, and in front of a database as it is shown in figure 4.2.

Figure 4.2: Java-based server-side technology[IV]

20
4.5. Web container
Web container in Java is referred to Servlet Container. It has concrete
implementation of the abstract Servlet API. It is the component of a web server, figure 4.3.
Container creates a completely independent environment for running servlets and Java
server pages for the purpose of offering dynamic content to website visitors. Servlet
container is responsible for handling requests for servlet, mapping a URL to a particular
servlet, managing the lifecycle of servlets, creating servlet instances and performing other
servlet management tasks. For web components servlet container specifies a runtime
environment that includes lifecycle management, transaction, concurency, deployment,
security and other services.

Figure 4.3: Web container as a part of a Web Server[IV]

According to Java development research reports conducted by ZeroTurnaround’s most


often used servlet Container in 2014 year is Tomcat with 50%, on the second place is
JBoss -16%.

21
Figure 4.4: App Server most often used [V]

22
4.6. Servlet Container or Application Server
Whether to use Application Server or Servlet Container is a very common question
especially among inexperienced developers. Servlet Container is a part of Application
Server, the appropriate question is 'when is it enough to use Servlet Container without
Application Server?'. The first and obvious difference in possibilities both of them is
support for EJB. Application Servers have EJB Containers, Servlet Containers does not. Of
course it is possible to use Embeddable EJB container along with Servlet Container but
then it is not possible to fully avail the true power of EJBs. For those who do not want to
use Enterprise Java Bean -like me, the problem remains unsolved.
If it is enough to use Servlet Container becomes an issue where to place framework
libraries, which will be used as development API in business application, with the
WAR/EAR file in WEB-INF/lib or in the server library directories.

Figure 4.5: Simplified development architecture of Java Frameworks and Java EE applications[VI]

In pure JAVA EE approach, framework is a part of the server and is separated from
application which consist of business code. In Spring/Play development frameworks API is
part of the Java application (WAR or EAR file) deployed to an arbitrary Java runtime,
figure 4.5.
With this knowledge it remains to choose whether it is needed to mix chosen
Framework with Java JEE, and then use Application Server, or stay with pure Spring or

23
other Framework application architecture. This decision is undertaken by architects
separately for each application. Some factors considered during making such decision are:
• flexibility for subsequent architectural, design or implementation decisions;
• production-readiness of infrastructure during server migration;
• fast response to new client requirements.
For the purpose of this study the Servlet Container is enough.

24
5. Java View technologies and frameworks
5.1. Servlets
The basis of all web applications, both created using standard JEE and additional
frameworks is the servlet. It is a java class, which may receive the request and generate a
response. JEE provides a servlet mechanism for running arbitrary protocols, in practice,
most servlets are those that use HTTP protocol. Servlet class must implement the interface
javax.servlet.Servlet which contains five methods:
• init(ServletConfig),
• service(ServletRequest, ServletResponse),
• destroy(),
• getServletConfig(),
• getServletInfo()

All this methods has to be implemented by servlet class. They are protocol-
independent and concern the life-cycle of servlet.
Javax.servlet package provides two classes:
• javax.servlet.http.HttpServlet
• javax.servlet.GenericServlet

that have implemented javax.servlet.Servlet interface so there is a possibility of inheritance


one of them and depending on the needs possibility to overloading methods.
Abstract class GenericServlet is a basic implementation of Servlet and
ServletConfig interfaces, it gives access to servlet’s settings and parameters. It contains
simple implementations of both interfaces methods, and thanks to that is a base for
HttpServlet class.
HttpServlet class beyond own implementations of methods, shares do* methods,
inter alia doGet() and doPost(). As a result, developer has to define only those methods,
which he plans to support.

25
5.2. Servlet life-cycle
Running on the operating system console or graphics applications, in most cases, it
is possible to identify when they start and end their operations. In the case of dynamic web
pages technologies for example PHP, files are interpreted on Current Issues, there is also
the possibility of their indirect compilation. This section will be an explanation of
compilation and life-cycle of servlet.
The description can be started from uncompiled source code. Before the server
starts working, all class files have to be compiled. Resulting files are copied to appropriate
directories; then server can run. Nowadays, most of servers have also ability to detect and
actualize classes in server operation. Servlet life begins at the moment, when the container
finds the servlet class file based on the deployment descriptor "web.xml". Servlet
declaration in the deployment descriptor:
<servlet>
<servlet-name>first</servlet-name>
<servlet-class>com.FirstServlet</servled-class>
</servlet>
<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>/first</url-pattern>
</servlet-mapping>

The first step is finding servlet class. Loading that class is a second step,
implementation of which takes place either at boot container, or when handling the first
request from the client. This property can be set in the deployment descriptor by using the
element of "load-on-startup". If its value is a number greater than 0, then it means that the
servlet is to be loaded when the application starts. All servlets are initialized in the order
specified by the value of this attribute:
<servlet>
<servlet-name> first </servlet-name>
<servlet-class>com. FirstServlet </servled-class>
<load-on-startup>1</load-on-startup>
</servlet>

26
When you load the servlet, container creates an object by calling the constructor and the
init() method. Only when you call init() method, servlet object receives all attributes and
references to the objects ServletContext and ServletConfig.
1. ServletContext - is created one for the entire web application. It represents the
parameters within the application. It should be used to obtain information
concerning the container and the web application. Context parameters can be
defined in the deployment descriptor using the <context-param>.
2. ServletConfig - is created for each servlet separately, is used to pass information
that we know at the time of application deployment to a servlet. Its performance is
also configured in the deployment descriptor using the <init-param>.
After init() method server invokes service() method and servlet can begin service requests.
From this moment in case of getting the request, servlet will attempt to invoke appropriate
method of scheme name/doName().The graph of service lifecycle is being presented in
figure 5.1.

Figure 5.1: A Servlet's Life cycle[VII]

27
5.3. Request-response
After calling the init() method, the servlet is ready for action and can handle HTTP
requests. At the time of service request from the client, the container creates a new thread
and assigns to it the newly created request and response objects of type HttpServletRequest
and HttpServletResponse. The container calls the service (HttpServletRequest,
HttpServletResponse) method . Service() method provides support for all types of HTTP
requests:
• GET - requests the return of a resource on the specified URL. GET requests should
not be a source of changes on the server side (eg. Should not change the values in
the database GET request). They should only be used to acquire certain resources
on the server side.
• POST - GET extension with additional information contained in the body of the
HTTP protocol. The reason for the POST is the ability to update data on the server
side.
• TRACE- requests a referral request message, so that the customer can easily see
what arrives at the other end
• HEAD - same as GET, but transfer only the status line and header section.
• PUT- prompted to place the embedded information of the specified URL
• OPTIONS - requests the list of HTTP methods for which the resource located at the
given address can answer
• CONNECT- seeks to connect goal tunneling protocols
• DELETE- requests the removal of a resource on the specified URL
For each type of request, except CONNECT, service() method calls the appropriate method
– for example for GET requests calls doGet (). This method can be overwritten in servlet
class. Each servlet ends its life when application is removed from the server. Then it calls
the destroy() method of the object servlet.
Number of objects created by the servlet container is dependent on the container
and the Java virtual machine. For a single Java virtual machine at least one servlet object is
created. Container can create a pool of servlets stored in memory for efficient requests
handling. Since each servlet can handle multiple requests, only local variables and request
attributes ensure the safety of multithreading .

28
5.4. Introduction to JavaServer Pages
Java Server Pages is a technology that allows inserts various structures to plain
HTML, or other text files. These structures can be: plain Java code -what is not
recommended, special expressions using Expression Language, special JavaServer Tag
Library tags. JSP can be thought of as an extension to servlet, all the features of the servlet
can be used in JSP. Java Server Pages are easy to maintain because it is easy to separate
business logic from presentation logic. In servlet technology those two logics are mixed.
What’s more, JSP allow fast development, there is no need to recompile and redeploy after
modifying the page as it was in the case of servlets. Another advantage is reduction of the
code, thanks to using tags such as jstl, action tags, custom tags or EL the code is much
simpler than in servlets. There are two ways to enable JSP pages in the normal life cycle of
a Web application:

• place the file in the appropriate web application folder,


• a reference to the file in the selected servlet using a special mechanism.

In the first method, JSP files are directly available. This method can be associated
with the use of usual websites files such as HTML or CSS. JSP file must be placed in a
specific folder of the project and must be visible to the user. After placing the file in the
folder, one do not need to perform any operation, it will be loaded and ready to use
automatically. The advantage of this approach is the ease of integration with the
application files. JSP file is able to display and easily use the data form. Unfortunately, this
method is not suited to the more advanced cases.
The second approach uses Request Dispatcher. At the beginning servlet performs
its operations. Entered by the user or specified on the form URL address must refer to this
specific servlet. After performing the operation request and response objects are sent by the
dispatcher servlet to a JSP file.

29
5.5. JavaServer Page Lifecycle
A JSP Lifecycle, introduced in the figure 5.2, consists of following steps:

• Translation of JSP Page

• Compilation of JSP Page


• Classloading (classloader is loading class file)

• Instantiation (Generated Servlet Object is created).


• Initialization (container invokes jspInit() method).

• Reqeust processing (container invokes jspService() method).


• Destroy (container invokes jspDestroy() method).

Figure 5.2: JavaServer Pages Life-cycle[VIII]

30
• Compilation: after browser request, the JSP engine checks whether the page needs
to be compiled. If the page has been modified since last compilation or if it has
never been compiled, the JSP engine compiles the page. This process involves three
steps:

-parsing the JSP

-turning the JSP into a servlet

-compiling the servlet

• Initialization: before servicing any request a container invokes the jspInit() method

• Execution: after loading and initializing the page, the JSP engine invokes the
jspService() method. THisd method is invoked once per request. It generates the
response for request and is responsible for generating responses to all seven of the
HTTP methods.
• Cleanup: when a JSP is being removed from use by a container, the method
jspDestroy() is called, this method is equivalent to the destroy method for servlets.

31
5.6. Introduction to JavaServer Faces
For basic web technologies the choice is limited, servlets and JSP(JavaServer
Pages) are irreplaceable. Otherwise looks overview of web frameworks. One of the most
popular technologies is the JSF(JavaServer Faces). Within the Java EE implementation,
there is a basic implementation. In addition, there are many extending capabilities of the
standard JSF implementations, for example PrimeFaces, MyFaces or ICEFaces extends
JSF on AJAX technology. JSF is the framework for web application development,
operating in accordance with the idea of the MVC design pattern.
Model-View-Controller was designed in 1979 by the Norwegian Trygve Reenskaug
programmer who was working on Smalltalk language in Xerox laboratories. It was
originally called the Model-View-Editor. The idea behind this pattern is to separate the
code responsible for processing the data from the code responsible for displaying them.
Model-View-Controller assumes the division of the application into three main parts. JSF
may be defined as a manager of cooperating different technologies, which is closest to the
controller, but also has much in common with the view. MVC pattern is shown in the
figure 5.3 :

Figure 5.3: MVC pattern

• Model - is a representation of the problem or application logic.


• View - describes how to display a part of the model within the user interface.

32
• Controller - accepts user input and responds to his actions, managing the model
update and view refresh.

JSF Framework is not responsible for the operation of all three layers of the MVC
pattern. In the case of the view layer JSF introduces its own model of graphical
components, event handling and validation. An important role falls to one of the external
technology, for JSF 2.0, Facelets framework supports the view. Other technologies can
also be used in the presentation layer. Additionally, downloading the data by using the
different types of controls plays an important role for the view. For several years the
standard has been an Ajax technology, where handling the input data is done directly by
the JSF.
JSF is the least interested in the model. Most common with this layer have managed
beans. These are special beans, which allow the use of data obtained from model layer in a
view layer.

33
5.7. JavaServer Faces Architecture
Like other Java technology-based web applications JSF application runs in a Java
servlet container, the application contains:

• JavaBeans components as models containing application-specific functionality and


data

• A custom tag library for representing event handlers and validators

• A custom tag library for rendering UI components

• UI components represented as stateful objects on the server

• Server-side helper classes

• Validators, event handlers, and navigation handlers

• Application configuration resource file for configuring application resources

Figure 5.4: JavaServer Faces architecture

34
JSF architecture consists of:
• User interface –it is up to designer to pick the desired representation of mechanism
for rendering an individual component;
• Business logic –can be utilized by managed beans;
• Controllers –used to perform user actions;

35
5.8. JavaServer Faces Life-cycle
Introduced in picture 5.5 life-cycle of JSF application consists of following phases:

• Restore view phase

• Apply request values phase -process events

• Process validations phase -process events

• Update model values phase -process events

• Invoke application phase -process events

• Render response phase

Figure 5.5: JavaServer Faces life-cycle

Phase 1: Restore view

JSF implementation begins the restore view phase when a request for a page is made. The
request may be click on a button or a link. During this phase implementation of JSF builds
the view of the page, wires validators and event handlers to components in the view, and
saves the view in the FacesContext instance. All information required to process a request
will be stored in FacesContext instance. All the application's event handlers, component
tags, validators, converters have access to the FacesContext instance. In case of initial

36
request, an empty view is created and the life cycle advances to the render response phase.
The empty view will be populated when the page is processed during a postback. If the
request is a postback, a view corresponding to page already exists. During this phase view
is restored by using the state information saved on the client or the server.

Phase 2: Apply request values

After the component tree is restored or created, components in component tree extract their
new values from the request parameters by using decode method. Values are then stored
locally on the components. In case of failure during the conversion of the value, an error
message is generated and queued on FacesContext. If renderResponse is called by event
listener on the current FacesContext instance, the JSF implementation skips to the Render
Response phase.

Phase 3: Process Validations Phase

All validators registered on the components are processed during this phase. It compares
component attribute rules to the values stored for the components. If local values are
invalid, error message is added to the FacesContext instance, life cycle advances to the
render response phase. The page is being displayed again with the error message.

Phase 4: Update Model Values Phase

After determination if the data is valid, Java Server Faces implementation set the
corresponding server-side object properties to the components' local values. Updated will
be only those bean properties which were pointed at by an input component's value
attribute. If renderResponse has been called by any updateModel method, the JSF moves to
render response phase.

37
Phase 5: Invoke application Phase

During this phase, any application-level events, like linking to another page or submitting a
form are handled. If component has fired an event, or if the view being processed was
reconstructed from previous request, these events are broadcast to interested listeners.

Phase 6: Render Response Phase

IF the application is using JSP pages, JSF delegates authority for rendering the page to the
JSP container. In case of initial request, all components will be added to the component
tree as the JSP container executes the page. If it's not an initial request, components don’t
have to be added to the tree again.

38
6. Spring Framework
6.1. Introduction to Spring Framework
Spring Framework is an open source library to create the whole range of
applications, which enables simplifying the process of development enterprise software by
using Java language. Spring Framework provides model components and a set of simple
and consistent APIs that will effectively isolate developers from the complex code required
in extended applications. The library consists of about 20 modules divided into six core
functional areas:
• The Core Container
Dependency Injection Container is the core element of Framework and supplies the
fundamental capabilities used by other modules. The container provides the functions
to separate the creation, configuration, and management of beans from application
code.
• Data Access(Integration)
Data Access and Integration Module provides support for the Java Database
Connectivity (JDBC) API, object-relational mapping(ORM), xml mapping (OXM),
transactional support and Java Message Service (JMS) . Owing to that developers are
relieved from writing tedious and error-prone boilerplate code. What is more, this
module supports most popular ORMs such as Hibernate, Java Data Objects, iBATIS,
and Java Persistance API.
• Web
Spring's Web module provides standard mechanism to integrate Spring into web
applications, web-based remoting capabilities and multipart file upload. Spring
provides its own Model-View-Controller framework, which integrates with popular
web-development frameworks and technologies like Velocity, JavaServer Pages(JSP),
JavaServer Faces(JSF), Struts.
• Aspect- Oriented Programming (AOP);
Spring supports aspect-oriented programming with AspectJ approach or simpler,
Spring AOP approach. AOP, aims to encapsulate into aspects cross-cutting concerns,
such as security, transaction management, logging, to retain modularity and

39
reusability. Without AOP, these concerns can not be separated from the rest of the
system, which causes the duplication of the code, the formation of the relationship
between the systems, or both at the same time. AOP support is both independently
useful to developers and used to implement different parts of framework
functionality. Because transactions are cross-cutting concern, Spring implements
AOP support for declarative transaction management.
• Instrumentation
Instrumentation is one of the key features to review application performance. It is the
ability needed to diagnose errors, to write trace information and monitor the level of
product's performance. Spring supports instrumentation through AOP and Logging.
• Test
Spring supports testing of application. It provides support for TestNG and JUnit
frameworks.

The block diagram of 6 main modules of the Spring Framework has been presented in the
figure 6.1.

Figure 6.1: Spring Framework modules[1]

Thanks to this modularity, developers aren't obligated to include the entire framework, but
have freedom to choose which parts, modules of the framework to use.

40
6.2. The advantages of using the Spring Framework
Simple, consistent API and component model insulates developers from the
complex and errors-sensitive code. In addition to these basic advantages, also other
features can be distinguished:

• Modularity - the framework has evolved into roughly 20 modules, developers


have freedom to choose which parts to use without the need to include the entire
library.
• Popularity – Spring Library is almost ubiquitous, it can be deduced from the
multiplicity of publications, Web sites and job offers.
• Promotes best practices -Spring programming model based on Plain Old Java
Objects (POJO) promotes unit testing , decoupled component models, and other
best practices
• Quality - from modules design, packages, structures of the classes and the API to
implementation and code coverage, library is high-quality open source software.
• Modest learning curve - due to the consistency and simplicity of the APIs,
hundreds of print and online resources including message boards, there is many
ways to learn Spring

Spring offers a lot of possibilities. Unfortunately it takes a lot of time to understand,


master and appreciate the landscape. But effort is well worth it. By learning to use the
Spring library and applying it to solve problems, it can be seen how to bring together
different technologies and incorporate them into consistent applications. The configuration
parameters are not stored permanently in the code, but centrally in the standard locations.
Relationships between classes are designed with the use of interfaces, which is better
suited to handle changing requirements. Finally, thanks to Spring it can be more done with
less effort and in less time. Spring handles the plumbing and thanks that developer can
focus on solving business problems.

41
6.3. Inversion of Control and Dependency Injection
Inversion of Control is an architectural pattern aimed at transferring the
responsibility for the control of selected activities outside of the component. Examples of
implementation of the IOC can be:

• Dependency Injection
• Aspect programming
• Strategy Pattern

The core of the Spring Framework is its Inversion of Control (IoC) container. The
IoC container manages java objects – from instantiation to destruction – through its
BeanFactory. Java components that are instantiated by the IoC container are called beans,
and the IoC container manages a bean's scope, lifecycle events, and any AOP features for
which it has been configured and coded. The IoC container enforces the dependency
injection pattern for components, leaving them loosely coupled and allowing to code to
abstractions.

Dependency Injection (DI) is a design pattern involving the removal of a direct


relationship between the components for the architecture of the plug-in. It prefers to create
external connections (dependencies) between software components which makes them
loosely coupled. It is a pattern, in which the responsibility for creation and concatenation
of the object is transferred to the IoC container.

The best way to explain how Dependency Injection works is to introduce an


example. It can be a simple application which draws Circles and Triangles. The first idea is
to make two classes: Circle with method draw(), and Triangle also with method draw() and
use them to write objects, figure 6.2.

42
Figure 6.2: Separated Circle and Triangle classes

Presented in the figure 6.2 process is inefficient and inelegant. It can be seen that
both classes are representatives of a shapes and what is more, both use method draw. In
this case good programming practice will introduce programming to interfaces; this way
has been shown in figure 6.3.

Figure 6.3: Programming to interfaces

This is standard way, following which shapes may have to be drawn in Object
Oriented Programming. However, in case of expanding the application by adding new
shape, for example a square, with presented code, developer has to write a new class
Square which will also inherit from interface Shape, and make something what is the most
problematic here, change the code of application class. New line of the code has to be
written in the main application class. Following this way of programming, each new idea

43
and each change from client, requires changes in all application as well as new code is
needed in basic classes. What is more, Application class specifies a dependency on a
Triangle and Circle class. In case of introducing new shape, it will also be dependent from
new shape. Instead of this approach, Spring offers Dependency Injection. While
implementing Dependency Injection the application can be composed like it's shown on
figure 6.4.

Figure 6.4: Drawing class using Dependency Injection

Thanks to Dependency Injection, the Drawing class is completely independent from


the concrete shape, which is drawing. Subsequently, developer can use it without any
changes in the code in order to draw the shape whichever is needed.
Specification of dependency chain can be made by two ways, by using XML or
Annotations.

44
6.4. Spring Web MVC introduction
Spring Web MVC is Spring’s web-centric MVC framework. It’s primary task is to
use MVC pattern in order to divide the application functionality. It provides a clean
separation of concerns by the three layered organization of web application. Featured
layers are: controller, model and view. The controller chooses the view by view name, not
by view object or by path, but exactly by name. Dependency injection allows for the
treatment of view names as injected values.

Another major design goal for Spring Web MVC is flexibility. There are many
ways to customize its operation. It depends on developer which way he will use. He can
choose POJO controllers or define an interface for controllers. There is possibility to
control how view names are generated and resolved to views, as well as how requests are
mapped to controllers. Exception handling and interceptor chains for controllers can be
defined. What is more, there is a possibility to choose from different strategies for
multipart resolvers, resolving locales or UI themes.

45
6.5. Spring Web MVC architecture
The core element of the Spring MVC Architecture is a top-level controller named
DispatcherServlet. It’s a front controller that dispatches requests to registered request
handlers. In Spring handler is a term used to refer to User Interface controller. The idea of
handlers is the same as the one of UI controllers but handlers include HTTP-based remote
service endpoints, which wouldn’t normally be considered UI controllers. In reality they’re
doing roughly the same thing: grabbing data and exporting it in a desired format.
Handlers perform a service and specify a view to which the front controller passes the
request. The handlers can be endpoints for HTTP-based remote services or UI controllers.
A conceptual view of control flow in Spring Web MVC is presented in the figure 6.5

Figure 6.5: A conceptual view of control flow in Spring Web MVC [1]

46
Control flow presented in Figure 6.5, begin by the arrival of http request into the
DispatcherServlet consists of following parts:
1. The DispatcherServlet choose from all registered handlers the right one to service
the request. The decision is made based on the request path.
2. The DispatcherServlet passes the user command/form data to a handler for
processing.
3. The handler queries or updates the model (or both)
4. The handler reads the data returned by model
5. The handler returns the data and a logical name of the view back to the
DispatcherSevlet
6. The DispatcherServlet resolves the view name into a view
7. The DispatcherServlet search the view based on the name
8. The DispatcherServlet passes the model data along to that view
9. The view generates the page

47
6.6. Spring Web MVC basic configuration
The most important file for Java web applications is a deployment descriptor named
web.xml. This file resides in the application's WAR under the WEB-INF/ directory. It's the
part of the servlet standard for web applications. In Spring web MVC, web.xml is a place
where the DispatcherServlet is defined. Definition of front controller and indication of
requests pattern is presented in Listing 6.1. With this configuration all request such as
/main/* will be handled by DispatcherServlet.

Listing 6.1: Simple DispatcherServlet configuration in web.xml [1]

Another important configuration is definition of the Context of the application. Each


instance of DispatcherServlet creates it’s own, local application Context in the file: /WEB-
INF/servletName-servlet.xml in this case the file will be named: main-servlet.xml. The
configuration is shown on Listing 6.2.

48
Listing 6.1: /WEB-INF/main-servlet.xml, the DispatcherServlet's local app context [1]

The first definition in servlet configuration file is the definition of the controller. The
controller’s name specifies the requests that the RosterController services. Point 2 is a
ViewResolver definition, which allows to convert logical view names to views. Following
definition presented in listing 6.2, the names of views for example: main will be converted
to /WEB-INF/jsp/main.jsp. The basic configuration presented above, allows to develop
Spring web MVC application.

49
7. Play Framework
7.1. Introduction to Play Framework

Play is a web framework whose HTTP interface is flexible, convenient, powerful


and simple. It provides a fresh alternative to excessive enterprise architecture. Play was
made for Java developers but wasn't based on Java Enterprise Edition APIs. What is more,
it was made especially for web developers, it improves the most popular non-Java web
development languages and frameworks — PHP and Ruby on Rails — by introducing the
advantages of the Java Virtual Machine (JVM). The main goal of this framework is
productivity. Play 2 is written in Scala and comes with a complete Java API, so that
developers can select the language. An important aspect of Play is attention to detail and
usability. What is more, the library makes high developer productivity and elegant API and
architecture possible. Play is a full-stack framework; its stack is presented in figure 7.1

Figure 7.1: Play Framework stack [2]

Being 'full-stack' is based not only on functionality, which may already exist as a
collection of open-source libraries. Full-stack means that framework provides a
documented pattern and if developers follow them, they can be sure that separate libraries
are compatible with each other and will work together. In this way, the developer does not

50
have to waste time to integrate libraries but can devote his time to solving business
problems instead. Play has all the tools needed to create a modern web application,
including:

• OpenID support for distributed authentication


• straightforward web services consumption either in JSON or XML
• relational database support through JDBC.
• object-relational mapping using Hibernate (with the JPA API).
• Easy deployment development, web application is ready to be deployed anywhere
(application server, Google App Engine, Cloud, etc…)
• image manipulation AP
• integrated cache support, with easy use of the distributed memcached system if
needed.

The architecture of Play application is modular and allows to combine a web application
with others. Application modules cause the code or templates to be reusable in a simple
way, [4].

51
7.2. The advantages of using the Play Framework
The main Play’s goals are simplicity and usability. Play framework is also
productive and comfortable to use because of variety of its features and qualities. The key
Plays features are:

• Type-safe mapping from HTTP to an idiomatic Scala API.


• Architecture that embraces HTML5 client technologies.
• Full-stack web framework features, including persistence, security and
internationalisation.
• Live code changes during reloading the page in web browser.
• Declarative application URL scheme configuration.
• Type safe template syntax.

Each web framework focuses on its goals, which happen to be totally different.
Some features may exclude each other. For Play architects, simplicity is a particularly
important issue. In this case simplicity translates to number of code lines and configuration
complexity. For example, Java Server Faces requires numerous files of various kinds
before serving blank page, while in PHP a simple 'Hello World' application consist of
single line of code.
The next Play’s goal is usability, Play creators claim that it is strongly connected
with developer’s productivity and comfort. They repute that many programmers enjoy
figuring out difficult things, and under-appreciate the value of things Just Work, and as a
result they waste time. However, web's conventions and practices should be put first,
whereas Java's second. Play provides usability by:

• providing first-class support for URLs: Servlet-based frameworks APIs, for


example Spring, does not provide useful URL-routing support. First, they configure
web.xml file to specify to which controller all requests will be forwarded, and then
implement URL routing with additional configuration. Most web frameworks add
the additional layer on top of HTTP. Play combines the HTTP server, HTTP API

52
and web framework, which allows to implement the same thing with a single URL
routing configuration and fewer layers.
• providing more usable interface to the framework documentation and error
messages shown in the browser. It avoids the pages full of irrelevant logging and
pages of stack traces on the server's console output. Instead of this, web application
shows the last line of code within application that appears in the stack trace.

Another Play’s goal is productivity. What matters most is hot-deployment. Java


web application servers and frameworks often have long build-redeploy cycles. In Play
developer is able to make a change in the code and see the result after reloading the web
page in the browser.

53
7.3. Play Framework architecture
Most of Java web frameworks are based on the Java Servlet API, which is the part
of the Java Enterprise Edition stack providing HTTP interface. What’s more, design and
evolution of these frameworks is focused on the Java platform, the web is just external
system. Unfortunately JEE structure involves additional complexity and low developer
satisfaction. Play developers judge that the web is more important than Java. Play is a
framework whose architecture embraces the web, and whose API embraces HTTP. Play
developers consider Servlet's API's to be quite complex due to many layers it is composed
of. If framework is based on Servlet API, then complexity grows through additional layer
of a web framework. The problem is presented in the figure 7.2.

Figure 7.2: Comparison of Java EE and Play's architectures [2]

Servlets and JavaServer Pages view templates were originally intended to be an


end-user API for web developers. When new technologies such as JavaServer Faces
superceded Java ServerPages, they were layered on top instead of becoming new API.
Consequently, Servlet API makes it harder to debug HTTP requests and is costly for
developer productivity. Since Play framework consists of a few layers, debugging HTTP
requests is simple for developers. For JVM web developers, Play provides a redesigned
web stack that doesn’t use the Servlet API and works better with HTTP and the web.

54
7.4. Application structure
Default Play application has a basic structure. It includes a minimal HTTP routing
configuration file, a view tamplate, HTTP routing configuration file, a controller class for
handling HTTP requests, jQuery and a CSS style sheet. The structure of newly created
application is shown in listing 7.1.

Listing 7.1: Files in a new Play application

1. App directory -The most important directory is app directory. It contains


application code. In app directory all parts of application should be stored, in order
to be compiled, e.g. view templates or Java source files. At default App directory
includes controllers and views directories.
• Controllers are Classes that take a HTTP request, run some logic on
it, and return a HTTP result. It can be said that these are classes that contain
Java code which implements the business logic for generating the webpage.
• Views are responsible for defining the HTML page. The template
files enclose a template in Scala template syntax. This is very important
because Scala templates are actually compiled to regular classes, as a result
provide compile-time syntax and type checking in real rime.

55
2. Conf directory - This is a place for all application configurations. The directory
consists of two files: application.conf and routes.
• The application.conf file contains all application configurations. It is
a place where data base connections, logging, server ports will be
configured. The configuration file is globally readable, which means that
any code can access it. The file is loaded at startup time.
• The routes file is a place for mappings, from HTTP URLs to
application code. Every line in the file defines a single route. The pattern of
mapping is shown in figure 7.3.

Figure 7.3: Components of a route.


Routes consist of: the HTTP method, the path and the action method. For
example route in figure 7.4:
GET / controllers.Products.list()
Figure 7.4: Example of a route

Any HTTP GET request for the ‘/’ (root) URL will be handled by the list
method, declared in Products class in the controllers package.

3. Project directory - build.properties and plugins.sbt are SBT configuration files. It


includes configuration for the build tool that Play's build process and console are
based upon. Managed dependencies and application’s version number are placed in
Build.scala file. It is similar to pom.xml in maven. Great benefit of using managed
dependecies is that there is no need to keep any library files with source files. It is
also very easy to upgrade a library to a different version. Play resolves
dependencies as soon as it finds changes in this file when application starts.

4. Public directory -The contents of this directory are available as public assets. It
means that files are available to the client directly, without any processing. In this

56
folder, files such as images, stylesheets, JavaScript files and static HTML pages
can be placed.

7.5. Controllers in Play


The controller connects HTTP requests to the server business logic. A controller
exposes some application functionality at a given address or URI(unique resource
identifier). Controllers are procedural and request/response oriented. Controller life cycle is
illustrated in figure 7.5

Figure 7.5: Controller life-cycle[2]

When client sends a request, Play will process this request and delegate the
processing of the request to a controller. Then controller executes business logic, he creates
and sends back the response. The result is send back to the client by the Play. In fact, Play
controllers consist of Action methods. Such methods take in input some parameters and

57
always return a Result. An action returns a play.mvc.Result value, representing the HTTP
response. An action method is of the following form:

public static play.mvc.Result method_name(params...)

Action methods are static because they are singletons, which fit the HTTP
approach. Action methods are the entry point from HTTP to application. HTTP is mainly
procedural, it does not have the concept of object, as a result action methods are sort of
static main() methods of Java. The use of static methods also makes the reverse routing and
the routing part easier. What’s more Play makes sure that the action methods are thread
safe.

58
7.6. The Play Scopes
Using Play or any other web framework allows retrieving the data from the clients,
and sending it back to the clients after processing. But in case of storing the data for a
certain lifetime it is very important to store this data in a certain scope. Java EE
traditionally defines four scopes:
3 Application scope - the data will stay as long as application is running
4 Session scope -the data that will stay as long as web browser is open
5 Request scope -the data can be accessed while that particular request is processed
6 Page scope -data that are accessible in the view, they can be accessed during the
rendering phase
The different scopes can be conceptually viewed as shown on figure 7.6.

Figure 7.6: Conceptually view of JEE scopes[2]

In traditional Java EE environment, all data storage happens server side. Play creators
consider it as a problematic in case of adding more servers, synchronizing client storage
space between different servers. They claim that nowadays web clients are powerful and
there is no need to charge the server. Play does not store any data server side. As a result,
server side session replication is not needed, and there is no risk of loosing the data on
server side, because scaling up is very easy and quick. Play stores the data on the client
side using cookies. For this reason storing complete object tree in session is not allowed.
Only 4 KB can be stored up, and what is more, only String values can be stored.
Conceptual view of Play scopes is shown in figure 7.7

59
Figure 7.7: conceptually view of Play scopes [2]

Play defines four scopes:


• Session scope - stored objects have a session lifetime. The stored data will stay as
long as browser is open. Sessions are added to each subsequent HTTP Request,
using the Cookie mechanism. Only String values can be stored.
• Request scope - cannot be used to store objects. It is used to access the data of the
current request.
• Response scope -cannot be used to store objects, it is used to set the response
content type
• Flash scope - objects have a lifetime of exactly 2 requests. It is quite useful to retain
the data after redirection. This scope was invented for the case of error messages.
When the Client fills the form, the controller receives the request and it attempts to
validate the data. In case the validation fails, the server displays the same page with
an error message. In case of refreshing the browser, it will try to resubmit the data
providing that last execution matches POST/phonenumber, figure 7.8

60
Figure 7.8: Submitting a invalid form without using the flash scope[3]

Another possible way is to send REDIRECT instruction, so that server redirects the
Client to GET/ method. But in this case the error message will be lost. That’s why Play
introduces flash scope. Storing the error messages in the flash scope allows access to
error messages after the redirect, it has been shown in figure 7.9

Figure 7.9: Submitting an invalid form and using the flash scope[3]

61
8. Comparison of Spring and Play Frameworks based
on a prototype of application for school management
system

Nowadays Educational Institutions are required to meet even higher requirements.


Professors and Institutions need to care more about their students. They also want to have
the best possible contact with their parents. In the rapidly developing world, in which
innovation and evaluation plays a very important role, schools have also decided to join the
web community. They introduce school management systems to improve the flow of
information between students, teachers and parents. In order to compare the two
frameworks I decided to implement a prototype of a school management system twice, first
using the Spring framework and second using the Play framework. In this chapter I will
present the main functions of the application As well as the differences in the
implementation of both frameworks.

Play and Spring frameworks implement the MVC pattern, which will be very
helpful during the comparison. First, I would like to describe the application and then focus
on the differences in configurations and the technical aspects of both implementations.

62
8.1. Application overview

The application consists of three modules:


I. Evaluation -teachers give grades, students and parents have a possibility to view the
scores;
II. Attendance -teachers take attendance, students can view their attendance, parents
can view and excuse their children’s absences;
III. Canteen -canteen manager prepares a menu for each week, students and parents
can view the menu;

The use case diagram is as follows:

Figure 8.1: Use case diagram

63
The class diagram in the Unified Modeling Language presented in the picture
below shows that 4 different types of users were created for the purposes of the school
management system. There are: student, parent, teacher and canteenManager, also User
class was created to store the data about logins and passwords of each user. One of the two
most important classes are:
• StudentSubjectMark which stores the informations about student’s marks, as well
as who and when gave the mark, and which subject it refers to;
• TeacherSubjectTeam which links each team with its subjects and subjects with
teachers who run the classes.
The same concept has been shown in the logical database model presented in picture [8.2]

64
65

Figure 8.2: Class diagram


66
Figure 8.3: Logical database model
8.2. View technologies
1. Spring:
Default view technology used with Spring is JavaServer Pages. It is a server-side
programming technology that enables the creation of a dynamic, platform-independent
method of building web pages. It provides expression tags, declaration tags and the JSP
Standard tag library(JSTL), which helps write a JSP code efficiently. However, if a
developer wants to put something in the view, for example a calendar, he still has to write
this component by himself using HTML,CSS and JavaScript. In my opinion this is not the
best way. There are very good solutions which provide prepared components to be used by
a developer without spending time on creating them from scratch. One of the most popular
technology is JavaServer Faces Framework. There are many extended capabilities of the
standard JSF implementations, for example, PrimeFaces, MyFaces or ICEFaces extends
JSF on the AJAX technology and provide a wide range of ready-to-use components as well
as great documentation with examples.
JavaServer Faces is similar to the Spring a MVC framework and because of that
many architects and developers think that it is impossible to use JSF as a view technology
with Spring. As I really want to deal with PrimeFaces components, after learning about
Spring and JSF, I have finally integrated those two frameworks in my application. I
decided to use JSF only as a view, so the data is exposed by Spring Beans, not by JSF
managed Beans. Because in the view I have only .xhtml pages, non of .jsp pages, I decided
to resign from standard DispatcherServlet and to manage the request processing lifecycle I
am using a JSF FacesServlet.
The configuration is as follows:
• FacesServlet and it's mapping have to be declared in a web.xml file:
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

• To enable the recognition of Spring Beans in the view layer, the faces-config file
should be created in the WEB-INF folder of application, and it should contain the
declaration of SpringBeanFacesELResolver

67
<application>
<el-resolver>
org.springframework.web.jsf.el.SpringBeanFacesELResolver
</el-resolver>
</application>

• To fully use JavaServer Faces features also Faces Scopes should be declared -JSF
provides ViewScope, which isn't enabled by Spring, but for the purposes of this
prototype of application, this scope isn't irreplaecable, so I decided to stay with the
Spring scopes.

2. Play:
Creators of the Play framework treat Servlet API as an additional layer that makes
it harder to debug HTTP requests. Also, JSF is considered to be complex and mismatched
with HTTP. Play provides a redesigned web stack that works better with plain, unpackaged
HTTP and the web. Play is a web framework intended for web developers. It embrances
HTTP and provides APIs that use HTTP's features instead of trying to hide HTTP. Play
has also some enhancements over standard JavaScript, CSS, and XHTML by providing
LESS CSS and CoffeeScript.
The HTML page template Play uses 'Scala template', a template with syntax based
on the Scala language. Hearing about Scala language can scare developers but Scala
should be rather treated as a new template language, there is no need to learn the Scala
language. A simple example of a Scala template:
@ (name:String)
@<!doctype html>

<html>
<head>
<meta charset = “UTF-8”>s
<title>Hello</title>
</head>
<body>
<h1>Hello <em>@name</em><h1>
</body>
</html>
The first line defines the parameter list, in this case just a name parameter.
An HTML document also includes an HTML em tag whose content is an expression -the
value of the name parameter.

68
8.3. Redirection between the views.
Spring:
In the Spring implementation of the management system the FacesServlet manage
redirecting between pages and is a handler for processing a web request, providing
convenient mapping. The mapping is declared in a web.xml file:
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
These mapping provides resolving the names of the views, thanks to that, all *.jsf
and *.xhtml url-s will be mapped to corresponding views. Also Controller methods
redirecting to views, can give as a result only a name of the view, without an extension.
Example:

if (user instanceof Teacher)


{
teacher = (Teacher) user;
return "teacher";
}

If variable user will be an instance of the Teacher class, then FacesServlet will redirect the
user to teacher.xhtml page.

Play:
In Play HTTP methods are mapped into action methods declared in Controllers.
The action methods render the objects to the views or to other action methods:

a)Routes:
GET / controllers.Application.index()
GET /hello controllers.Application.hello(name: String)

69
b)Controller:
public class Application extends Controller {
public static Result index(){
return ok(“Hello world”);
}
public static Result index(String name){
return ok(views.html.hello.render(name));
}
public static Result hello(String name){
return ok(index.render(“Hello”+ name));
}
}

c)View:
app/views/hello.scala.html
@ (name:String)
@<!doctype html>

<html>
<head>

<meta charset = “UTF-8”>s


<title>Hello</title>
</head>

<body>
<h1>Hello <em>@name</em><h1>
</body>
</html>

With the code presented in points a,b and c, after typing the URL like:

http://localhost:port/hello?name=Play!

the browser will display hello view with the “Hello Play!” inscription.

70
8.4. Passing parameters between Controllers and Views
Another big difference between those two frameworks is the way how the
controller communicates with the view.

Spring:
View has access to each controller’s methods and objects without any limitation.
For example:
<h:outputText value="#{studentController.studentTeam}" />
In the outputText field the content of the studentTeam object declared in studentController
will be displayed. Another example:
<h:form>
<p:dataTable var="subject" value="#{studentController.studentSubjects}" emptyMessage="Brak ocen :
()">
<p:column headerText="subjectId">
<h:outputText value="#{subject.subjectID}" />
</p:column>

<p:column headerText="Subject name">


<h:commandButton action="#{degreeController.navigateToDegreePage}"
value="#{subject.name}">
<f:setPropertyActionListener target="#{degreeController.subject}" value="#{subject}" />
</h:commandButton>
</p:column>
</p:dataTable>

</h:form>

The dataTable will display elements of the List declared in studentController as


studentSubjects. In the first column Ids of subjects: #{subject.subjectID} will be displayed,
while the names of the subjects : #{subject.name} in the second column. The value of
subject.name is also a commandButton which redirects to degreeControler and invokes the
navigateToDegreePage method, but before invoking this method the object named subject
declared in degreeController will be saved:

<f:setPropertyActionListener target="#{degreeController.subject}" value="#{subject}" />

71
its value will be the value of the chosen commandButton. So JSF view enables the access
to each controller and also each controller’s variable or method from the view.

Play:
Compared to Spring, the way of communication between views and controllers in
Play is very limited. As said before, only Action Method have the ability to pass the
parameters to the view. What's more, objects can not be passed to the view in their pure
form. In order to transfer the Object to the view it has to be converted by the method
form(Object.class) declared in Form class. Form is what Play uses to represent HTML
forms. Form makes it possible to convert between HTTP (form) parameters and Java
objects and vice versa. The form method takes a class as a parameter, to tell it what kind of
object the form is for. For example:

To pass the List of Teams, the date and the cookies to the teacherView, the
following operations have to be made:

public static Result navigateToTeacherView() {


Session session = Context.current().session();
List<Team> createdTeams = new ArrayList<Team>();
// filling createdTeams
Date date = new Date();
Form<Date> dat = Form.form(Date.class);
dat.fill(date);
return ok(teacherView.render(createdTeams,dat,session));
}
It can be noticed, that ArrayList and session object are transferred in their pure
form, but to pass the date, a DataForm has to be created: Form<Date> dat =
Form.form(Date.class) and filled by date object: dat.fill(date).
In the first line of the View template, the definition of accepted arguments has to be stored:
@(teams: List[models.Team], data: Form[Date])(implicit session:play.mvc.Http.Session)
In the view we can operate only with arguments declared in the first line; we can't refer to
the controllers’ objects or methods in order to receive the object values.

72
8.5. Model
Spring:
In the Spring application the Hibernate framework was used to Object Relational
Mapping. What is more, just like in many other applications using Spring, it has to be
decided whether to follow Data Access Object pattern or not. To show how it is configured
the Student Class will be an example:

a) First Generic DAO interface had to be created:


public interface GenericDao<E, K> {

void add(E entity);

void update(E entity);

void remove(E entity);

E find(K key);

List<E> list();

b) To communicate with the database HibernateDao should also be created:


@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public class HibernateDao<E, K extends Serializable> implements
GenericDao<E, K> {

private SessionFactory sessionFactory;


protected Class<? extends E> daoType;

public HibernateDao() {
daoType = (Class<E>) ((ParameterizedType) getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];
}

@Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}

protected Session currentSession() {


return sessionFactory.getCurrentSession();
}

@Override
public void add(E entity) {
currentSession().save(entity);
}

73
@Override
public void update(E entity) {
currentSession().saveOrUpdate(entity);
}

@Override
public void remove(E entity) {
currentSession().delete(entity);
}

@Override
public E find(K key) {
return (E) currentSession().get(daoType, key);
}

@Override
public List<E> list() {
return currentSession().createCriteria(daoType).list();

c) After creating Generic and Hibernate DAOs, I created Student Class:


@Entity
public class Student extends Model{
@Id
public Long id;
public String login;
public String password;
public String name;
public String surname;

@ManyToOne
public Team team;

@ManyToOne
public Parent parent;

public static Finder<Long,Student> find = new Finder<Long,Student>(


Long.class, Student.class
);

public Student(String login, String password, String name, String surname, Team team, Parent
parent) {
this.login = login;
this.password = password;
this.name = name;
this.surname = surname;
this.team = team;
this.parent = parent;
User user = new User(login, password, "student");
user.save();

74
public Student() {

}
}
d) and studentDao which extends GenericDao:

public interface StudentDao extends GenericDao<Student, Long>{


boolean removeStudent(Student student);
}

e)When StudentDao interface is ready, it's implementation can be provided:

@Repository("studentDao")
public class StudentDaoImpl extends HibernateDao<Student, Long> implements StudentDao{

@Override
public boolean removeStudent(Student student) {

Query studentTaskQuery = currentSession().createQuery("from Team t where :id in


elements(t.students)");
studentTaskQuery.setParameter("id", student.getId());
// student mustn't be assigned on no group
if (!studentTaskQuery.list().isEmpty()) {
return false;
}

// ok, remove as usual


remove(student);
return true;

@Override
public List<Student> list() {
return currentSession().createCriteria(Student.class)
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
}
}

f) Done! After writing all this code there is a possibility to operate with Student Object or
rather with it's instances. In Service or Test classes a new student can be created and saved
in the database:

@Autowired
private StudentDao studentDao;

Student studentA = new Student("login", "password","name","surname","team");

75
studentDao.add(studentA);
or student which ID is known can be retrieved from database:

Student found = studentDao.find(student.getStudentID());


Play:

In Play Ebean ORM Framework has been used. Because of sessionless API,
managing entities has a very different approach here than in Hibernate.
a) First a model has to be created:
@Entity
public class Student extends Model{
@Id
public Long id;
public String login;
public String password;
public String name;
public String surname;

@ManyToOne
public Team team;

@ManyToOne
public Parent parent;

public static Finder<Long,Student> find = new Finder<Long,Student>(


Long.class, Student.class
);

public Student(String login, String password, String name, String surname, Team team, Parent
parent) {
this.login = login;
this.password = password;
this.name = name;
this.surname = surname;
this.team = team;
this.parent = parent;
User user = new User(login, password, "student");
user.save();

public Student() {

76
Two differences might have been noticed:
• all fields in Student class are public, in Play framework once a field is exposed, it’s
part of that object’s public API, and it should be supported forever. Play eliminates
all boilerplate code as getters and setters to private fields. It uses "byte code
enhancement" to add getters and setters after the original code has been compiled;
• student extends Model class. This class provides some common database-related
methods. By providing the database operations with the entity classes, it becomes
possible to do a database operation anywhere we have an entity instance, without
having to "hunt" some other object or class that provides that functionality like
DAOs.

b) When Student Class extending Model Class is created, it can be used in each Controller
or other class. New student can be created and saved in the database:

Student studentB = new Student("login", "password","name","surname","team");


studentB.save();

or student whose ID is known can be retrieved from the database:

Student found = Student.find.byId(studentId);

77
9. Comparison of Spring and Play Frameworks based on
technical domains

More and more frameworks are brought out each year. The main cause of this is an
attempt to improve developers’ productivity and simplify the process of application
development. Unfortunately, this wide range of solutions leads to a big dilemma of
choosing a proper instrument to use. There are no methods available to determine which
frameworks would be best in a given context, and there are no real methodologies for
framework comparison at all. What needs to be emphasized is the fact that each project is
different, and for each application other criteria of choosing the best solutions should be
selected. The purpose of the comparison of the Play and Spring Frameworks is not
selecting the better one, because it is absolutely impossible to objectively ascertain that one
framework is better than the other at all. The aim of the comparison is to explore the
differences between those two frameworks, which should help to find the best solution for
a specific application.

The other important issue which has to be mentioned here is the explanation why
the technical, and not functional aspects of the frameworks are taken into consideration in
this comparison. By functional aspects I mean: ease of learning, ease of use,
documentation and community, as well as the framework ecosystem. Comparisons of
Spring and other frameworks based on those criteria can be easily found in many places, as
there are a lot of articles on the Internet and a large number of theses covering these
aspects. In order to expand knowledge I decided to focus on technical domains.

In an attempt to compare frameworks, first the framework definition should be


established. Following the definition, the criteria on which to compare the frameworks
should be selected. In my opinion very exact definition of a framework is as follows:

“A framework is a reusable skeleton for applications, targeting a specific domain,


covering certain key areas and the interaction between them within that specific domain.”
[5].

78
Presented definition can be divided into smaller parts:

• “Reusable skeleton” -framework enables developers to rapidly produce new


applications.
• “Targeting a specific domain” -not every framework is applicable to every domain,
only framework targeting same areas can be compared
• “Certain key areas”. -if this areas can be defined, the comparison will be based on
those areas.

In applications created for the purpose of this thesis the specific domain is a school
management system. In this case the most important technical domains are:

• scalability
• performance
• separation of concerns
• testability
• persistency
• security
• maintainability

79
9.1. Scalability
The definition given for scalability in [5] is following:
“Scalability is the ability of a computer application or product to continue to function well
as it (or its context) is changed in size or volume. Typically, the rescaling is to a larger
size or volume.”
Distribution is an implementation of scalability. By distributing the workload over
several machines, the workload is divided over multiple machines and more data can be
processed than by using a single machine.

Play:
Play uses a fully asynchronous model built on the top of the Akka, which is an
event-driven and actor based framework for building reliable, highly concurrent and
scalable applications. An asynchronous model combined with the quality of being stateless
makes the scales simple and predictable. Play is incredibly scalable and allows for high
throughput . Support assists with integrating into other web services -build in JSON, and
enables code to be more modularized. What is more, NETTY, non-blocking I/O client web
server on which Play applications are designed to be run is also non-blocking, which
should cut down on useless waiting.

Spring:
Spring is also scalable. It offers Spring Batch for Scaling and Parallel Processing.
This component enables us to build multi-threaded apps, partition applications and do bulk
processing. To scale the memory, Spring contains the EhCache component. Also, a very
important aspect of scalability is the ability to divide an application into modules which
can be set up on different hosts -spring applications can be modularized. Spring provides
JMS(Java Message Service) and RMI(Remote Method Invocation) to enable connecting
modules with messaging.

80
9.2. Performance
One of the most important principles of software engineering is performance. This
term is defined in [6] as: “Performance is the degree to which a software system or
component meets its objectives for timeliness. Thus, performance is any characteristic of a
software product that you could, in principle, measure by sitting at the computer with a
stopwatch in your hand.”
Implementations which have a large impact on performance are connection
pooling, session handling and caching.

Play:
There is a fundamental difference between Play and most other servlet based Java
frameworks. Play does not store any data on the server side. Play stores data on the client’s
side using cookies, which forces the developers to think in terms of web development.
They can't use a session as a giant cache where complete object trees can be stored. It is
possible to store up to 4KB -a cookie size; what is more, only String values can be stored.
In order to store an entire object from a domain model -cache has to be used. This
approach has many advantages. There is no risk of loosing data on the server side, no
server side session replication is needed. Scaling up is very simple -just add a new server
and load a balancer. Play forces us to carefully consider memory usage.

Spring:
Spring is a powerfull framework for web development. It has API and its own tools
for the interaction with the server-side session. It enables storing complete object trees in
the session. Thanks to dependency injection, annotations and session scope, programming
is very easy. Its efficacy does not make the application scalability so simple as in Play and
may prolong the time of operations. Performance tests result will be submitted in the next
chapter.

81
9.3. Separation of concerns
The next term widely used in the field of software engineering is Separation of
concerns. It may be described as:
“Separation of concerns refers to the ability to identify, encapsulate, and manipulate only
those parts of software that are relevant to a particular concept.”[7]
Separation of concerns can be achieved by increasing modularity, reducing
complexity and reducing dependencines. For clear separation of concerns Play and Spring
frameworks implement the MVC pattern.

9.4. Testability
Testability can be defined as:
“The likelihood, possibly measured statistically, that the software will expose a failure
under testing, if it is faulty.” [8]
In quality insurance, software testing is a very important factor. There are many
different types of testing and many tools available to help with testing. The main issue is if
a Web Framework interact with, embed or assist with testing step.

Play:
Play uses JUnit by default and a new process will be spawned for each test. Play
has the ability to mock a whole application for test to use. It has JavaTest with
FakeApplication. If the code which is to be tested depends on running the application, the
FakeApplication can be easily created on the fly. FakeApplication can be spined up with a
real in-memory database.

Spring:
Spring is a very unit-testable framework because of official Spring MVC Test
Framework. This module loads the Spring configuration through the TestContext
framework.In order to process requests it uses DispatcherServlet. Controllers, which are
just plain Java classes with annotations, can be tested using mocked unit tests -Mockito or
EasyMock. The only inconvenience in testing Spring MVC is the view logic -JavaServer
Pages, that needs to be tested using some external tool like for example Selenium.

82
9.5. Persistency
The definition given for persistency in [9] is the following: “Persistency refers to
the characteristic of data that outlives the execution of the program that created it.”
Persistency is related to the layer it creates between the application logic and the data
storage. The type of persistence can have a great impact on the performance. Also, the type
of mapping used to change from the internal application structure to data storage is of great
importance to persistence.
Play: Fundamentally different relational-databases and object models can be mapped
onto each other by Object-Relational-Mapping. The most common Java standard for this is
JPA- Java Persistent Api. Another solution for mapping is one of the most popular
framework which performs a powerful object relational mapping and query databases
using HQL and SQL. It is Hibernate.
In Play applications we can implement both of these approaches as well as any other
persistence solutions -but there are not default solutions. A huge part of JPA specification
is based on managing entity state across for example requests. Because of its stateless
nature, Play has no use in this respect. Instead, Play comes with its own Object-relational-
framework, Ebean. Ebean takes a different approach to managing entities than most other
ORM tools do. The main difference is that it has sessionless API, which makes it a good
match for Play. Ebean borrows one, very helpfull aspect from JPA - annotations. Maping
entities looks exactly the same as in JPA.
Spring: The lowest level data access technology that Spring supports is JDBC. Other,
higher level technologies are iBATIS SQL Maps, JDO, Hibernate and other O/R mapping
tools. These technologies use JDBC for accessing a database, but all of them provide their
own abstraction API to work with. In Spring MVC the Data Access Object Pattern is very
commonly used. The framework is aimed at making it easy to work with data access
technologies. The primary purpose of the DAO is to separate persistence-related issues
from business logic. Using DAO a developer can switch between the persistence
technologies without any impact to the code and business logic. It also allows to code
without worrying about catching exceptions that are specific to each technology. Spring
provides an abstract DAO support class for each O/R mapping technology it supports. For
example, Hibernate has HibernateDaoSupport.

83
9.6. Security
In [5] the following definition is used for security:
“Security is the measure of the system’s ability to resist unauthorized usage while still
providing its service to legitimate users”.
Security has become an increasingly important topic because of a growing number
of Internet applications which support different types of users.

Play:
The Play Framework has authentication support through annotations and also adds
support for secure routing. It enables developers to secure and harden their applications
without writting if-blocks in every secure method. Secured methods are decorated with
@With and @Check annotations, which is very convenient. There is also a possibility to
integrate it with Spring-Security module.

Spring:
Security in Spring relies on the Spring Security module and can utilize all the
features Spring Security has. Writing security rules is easy and with minimum code thanks
to @PreAuthorize annotations. These annotations can be put on top of each Controller
method and it is possible to use Spring Expression Language at same time.

84
9.7. Maintainability
A definition found in [10] is “Maintainability is the capability of the software
product to be modified. Modifications may include corrections, improvements or
adaptations of
the software to change the environment, and in requirements and function specifications.”
Maintainability describes how to easily modifiy and retest the software product.

Play:
Most Play framework projects look very similar in structure because this
framework follows a convention over configuration methodology. Developers can switch
between applications without having to learn the ecosystem for every project. Thanks to
the built-in templating system the code written for the Play is readable. It enables the
creation of powerful and useful applications with lower Lines of Code counts. What is
more, Play also has reloading of components and the code both built in, which definitely
helps cut down on time during the development phase of applications. One disadvantage is
reliance on Scala - it can limit the readability to Java-specific developers.

Spring:
Unlike the convention-over-configuration frameworks such as Play, Spring is heavy
and dense. Updating and code maintenance is manageable for those who are already
familiar with the framework and project. One advantage can be found -annotations, they
enable us to access all kinds of data in a declarative manner.

85
9.8. Summary
It is impossible to decide whether the Spring or Play framework is better. The
Spring framework is created for enterprise application developers while Play for web
developers. Both of them are highly testable and provide good security support. Also, both
are modular and implement the MVC pattern for clear separation of concerns. It can be
said that the Play framework is more scalable and its application maintenance as well as
code updates are simpler than in Spring, but these both advantages are caused it's
sessionless API. That entails a need to read the data from the database for each separate
operation. In Spring all object trees can be stored in the server-side session and the
developer has easy access to them by using the annotations. The decision whether to
choose Spring or Play framework remains to be resolved by application architects. The
most important aspects is the awareness of advantages and disadvantages of both
frameworks as well as of differences between them.

86
10. Comparison of Spring and Play Frameworks based
on performance tests of school management system.
Assumptions and description of the tests:

The tests were designed to check the performance of implemented applications. For
this purpose, the applications were loaded with the corresponding parameters such as the
number of threads, number of repetitions and time of the specified HTTP request. Tests
were performed using scripts in the Apache JMeter in Version 2.11. This tool allows to
create a plan of the tests and enables the presentation of the results in a selected form.
To maintain similar comparison conditions, both applications were exported as a WAR file
and placed on the application server Apache Tomcat 7.

10.1. Test number 1 – Displaying the list of student subjects.


In the first test a request to display a list of the student subjects was simulated. The
test case assumes the correct login to the student’s account and displays a list of student’s
subjects. Table 1 shows the test case parameters. Element "time to reach the full number of
threads" specifies the time needed to create the last user(measured in seconds). Thus, in
this case the two hundredth thread will be created after 30 seconds.

Number of threads (users) 200


Time to reach the total count of threads in 30
seconds
Number of repetitions 5

87
Play framework results:

Figure 10.1 Response Time - Play framework

Figure 10.2. Response time statistics - Play framework

88
Spring framework results:

Figure 10.3. Response Time - Spring framework

Figure 10.4. Response time statistics – Spring framework

The correct execution of the request for each trial and each user means that the
server returned the list of subjects for the logged student. The simulation of 200 users after
5 attempts gave a total number of 1000 samples. The aggregated data graphs suggest that
the Spring framework is slightly faster in this attempt.

89
10.2. Test number 2– Handling the form data

In test no. 2 the typical load caused by sending the form data was simulated. The
test was executed during filling the student’s marks form by the teacher. Sending the form
data is a key aspect for the performance comparison.

Number of threads (users) 100


Time to reach the total count of threads in 1
seconds
Number of repetitions 10

In this test case, the activity of 100 users was simulated. Each of them login to the
application, send the form and logout 10 times.
Play framework results:

The name Login Filling and sending Logout


the form
Number of samples 1000 1000 1000
Average 2734 5464 2263
Median 1390 4082 858
Minimum 17 222 4
Maksimum 15539 28645 14872
Error percentage 0 0 0
throughput 8,5 8,7 8,8

flow KB/sec 14,8 105,5 10

90
Figure 10.5. Response Time - Play framework

Figure 10.6. Response time statistics – Play framework

91
Spring framework results:
The name Login Filling and sending Logout
the form
Number of samples 1000 1000 1000
Average 3169 7175 7
Median 3193 7162 7
Minimum 264 37 6
Maksimum 5780 10809 40
Error percentage 0 0 0
throughput 9,6 9,5 10

flow KB/sec 70,3 74,5 10,2

Figure 10.7. Response time statistics – Spring framework

92
Figure 10.8. Response Time - Spring framework

Based on the test results it can be concluded that the play framework is faster
during login and grading by the teacher’s account. Spring is faster during logging off.
However, the minimum and maximum time of sending the form in Spring app is lower. So
when comparing the average values of individual operations Play framework wins.

10.3. Test number 3 – maximum load

In the last test, both frameworks are tested for maximum load that can withstand
further requests by the server without error and denial of service.
The test was carried out also by using JMeter, with the parameter "time to reach the
full number of members" equal to 10 seconds. Then, the number of users who try to log in,
display the list of teams and after that logout. After a successful trial the number of threads
in the next iteration was increased by 10 (up to the point at which the tool began to report
bugs). Maximum value of users in Spring application is 800 and in Play application is
2000.

93
11. Conclusions

Under this thesis a review of technologies and methods designed to build Java
Enterprise web application was conducted. First the build-up and behavior of web
applications was presented. After that Java web technologies specifications and
implementations were introduced. The next step was an overview of Java View
technologies and frameworks.

One of the main goals of the thesis was examining the possibility of combining
various solutions by trying to implement a test application created by using the Spring
framework with Java Server Faces. It turned out that an implementation by using the
Spring framework with JSF as a view technology is possible. For this purpose following
conditions have to be fulfilled:

• declaration of FacesServlet, which manages the request processing lifecycle, has to


be declared in web.xml file;
• to enable the recognition of a Spring Beans in the view layer, the faces-config file
should be created in the WEB-INF folder and it should contains the declaration of
SpringBeanFacesELResolver;
• to fully use JavaServer Faces features Faces Scopes should also be declared.

The thesis also compares Spring and Play frameworks based on:

• a prototype of school management system projected and implemented specifically


for the purposes of this thesis;

• a technical domain.

The main goal of both comparisons was to expand the knowledge on the
frameworks and present the differences between them. What should be noticed is the fact
that the Play Framework provide sessionless API, which has a significant impact on
cooperation with the stateless HTTP protocol. What is more, this framework enables hot

94
deployment of the application, which saves a lot of developers’ time. On the other hand the
Spring framework focuses on providing a way to manage business objects. The technology
that Spring is most identified with is Inversion of Control, and specifically the Dependency
Injection flavor of IoC. Dependency Injection and Annotations enable easy access to all
Spring Beans declared in the application, which simplifies the development process.
Also, performance tests were conducted during the preparation stage of this thesis.
The Spring framework was slightly faster in the first attempt, Play framework won other
tests, what confirmed that Play is incredibly scalable and allows for high throughput.

95
12. Bibliography

12.1. Basic bibliography


1. Wheeler W., Joshua W.: Spring in Practice, Manning, 2013 Shelter Island
2. Leroux N., Kaper S.: Play for Java, Manning, 2012 Shelter Island
3. Reelsen A., Play Framework Cookbook, Packt, 2011 Birmingham -Mumbai
4. Peterella Andy, Learning Play! Framework 2, Packt,2013 BIRMINGHAM –
MUMBAI
5. L Bass, P Clements, R Kazman - Software Architecture in Practice, second edition,
2003
6. CU Smith, LG Williams - Software performance engineering - UML for real:
design of embedded real-time, 2003
7. H Ossher, P Tarr - Multi-Dimensional Separation of Concerns and The
Hyperspace Approach 2000
8. JM Voas, KW Miller - Software testability: the new verification - Software, IEEE,
1995
9. V.J. Cahill, P.A. Nixon, F.A. Rabhi - Object Models for Distributed or Persistent
Programming - 1998 ,Trinity College, University of Dubli

12.2. Additional bibliography


I. http://helpx.adobe.com/dreamweaver/using/web-applications.html, access 2014-07-
01
II. http://stackoverflow.com/questions/4195858/question-about-java-ee-6-architecture,
access 2014-07-01
III. http://en.wikipedia.org/wiki/Comparison_of_application_servers#Java, access
2014-07-01
IV. http://howtodoinjava.com/2013/10/03/a-birds-eye-view-on-how-web-servers-
work/, access 2014-07-02
V. http://zeroturnaround.com/rebellabs/java-tools-and-technologies-landscape-for-
2014/, access 2014-07-02
VI. http://www.javacodegeeks.com/2012/05/why-i-will-continue-to-use-spring-
and.html, access 2014-07-04

96
VII. http://www.ntu.edu.sg/home/ehchua/programming/java/JavaServlets.html,
access 2014-07-04
VIII. http://www.javatpoint.com/jsp-tutorial, access 2014-07-02
IX. http://www.slideshare.net/Uniface/enterprise-applications-and-facebook-16779910,
access 2014-07-01

X. http://www.ijetae.com/files/Volume2Issue2/IJETAE_0212_20.pdf, access 2014-


08-10

97

You might also like