Home Page

1. Introduction

This page should provide reader basic knowledge about technologies which are needed for making a dynamic web project based on model-view-controller (MVC) architecture.

1.1. MVC-Architecture

In short MVC is architexture, which separates representation from the user's interactions. The model consists of application data, bussines rules and functions. The view outputs representation of data The controller mediates input and converts its to commnads for model of view.

To learn everything about MVC visit http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller

To create an application using MVC architecture, we need to have some tools and technologies, which can help us. We will be using Maven, Spring, Hibernate and and developing environment Spring Source Tools.

2. Technologies

Technologies are divided into sub-chapters for better orientation. If someone is familiar with any of them, it is not necessary to read the paragraph, but it’s strongly recommended.

2.1. Maven

Maven's allows developer to comprehend the complete state of a development effort in the shortest period of time. In order to attain this goal there are several areas of concern that Maven attempts to deal with. Maven itself is huge project, which could be modified in many different ways. After getting over first confusing, and trying build some basic maven project, this source will be very useful:


It is not actually for the latest version of the Maven, but that doesn’t really matter.

2.1.1. What is Maven ?

Maven is modern build/project management tool.The main usage is:

  • Make the build process easy
  • Provide a uniform build system
  • Provide quality project information
  • Provide guidelines for "best practices" in development
  • Allows transparent migration to new features

From point of view, we can say that Maven is a builder like make or ant, written in java. It's a command line tool. Eclipse and others IDE have plugins to handle and integrate project powered by maven. It could be used to create lib (jar), webapps (ear) and any other type of "artifact”.


2.1.2. POM

Every project has to contain POM file. It means "Project Object Model". It is an XML representation of a Maven project held in a file named pom.xml. In this file can be defined various configurations and dependencies. Content could be very different, and it affect behaviour of application.

Basic project structure is defined in chapter 2.1.4. Dir Layout. If your project contains multiple subproject, every single module has to contain the POM file. To avoid duplicity you can use one POM file as parent POM, where can be define common shared attributes and settings of your project. In most cases it’s the one, which is in directory structure on the highest position – the top POM file.

Reactor file is POM, where all modules are defined. During build, maven goes thru all modules separately and doing all phases on each module.

Reactor example:

	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"



2.1.3. Repository

Dependencies configured in POM file(s), will maven automatically download during build, into local repository. It is also possible to define own repository sites, which should maven search adding configuration into parrent POM:


Repository structure is very simple. Single subdirectories are created by the <groupID> , <artifactId> and <version> of the downloaded, or locally build library, plugin, project etc. Default location of maven repository is:

2.1.4. Dir Layout

Maven directory layout depends on type of maven project. Simple maven project has following directory layout :


2.1.5. Default Lifecycles

1. validate
2. generate-sources
3. process-sources
4. generate-resources
5. process-resources
6. compile
7. process-classes
8. generate-test-sources
9. process-test-sources
10. generate-test-resources
11. process-test-resources
12. test-compile
13. test
14. prepare-package
15. package
16. pre-integration-test
17. integration-test
18. post-integration-test
19. verify
20. install
21. deploy

2.1.6. Tycho

For building existing eclipse project (OSGi?, PDE) with maven, it can be used Tycho. Tycho will find manifest, feature.xml, build.properties, etc. and build the project with maven without any difficult directory modification.


2.2. Spring

Contains a framework (among others) which is used for designing MVC aplications. The first version was written by Rod Johnson, who released the framework with the publication of his book Expert One-on-One J2EE? Design and Development in October 2002. Since then, Spring has grown into much bigger project.

2.2.1. What is Spring ?

The Spring Framework (http://www.springframework.org) is a development stack for JEE-based application. What started as a dependency injection container has evolved into a POJO-based programming model for enterprise applications, providing commonly used services and abstractions (transaction management, caching, batch processing, etc.) out of the box.

There's no direct relationship to Hibernate (which is a object-relational mapping), but within its ORM module, Spring provides an integration layer for it. With connection of Spring, Hibernate and Maven you’ll get very powerful tools.

The Spring Framework consists of features organized into about 20 modules and some of the will be shortly described. These modules are grouped into Core Container, Data Access/Integration, Web, AOP (Aspect Oriented Programming), Instrumentation, and Test, as shown in the following diagram.


2.2.2. Dependency Injection / Inversion of Control

Inversion of Control is best understood through the term the "Hollywood Principle," which basically means "Don't call me, I'll call you." Consider a traditional class library: Application code is responsible for the overall flow of control, calling out to the class library as necessary.

IoC? is a broad concept, and can encompass many things, including the EJB and Servlet model, and the way in which Spring uses callback interfaces to allow clean acquisition and release of resources such as JDBC Connections.

To clarify, dependency injection is a mechanism by which Spring handles creation and initialization of the proper type of child object for a parent object at the moment the parent object needs the reference to the child.

An example of where this is useful in the context of enterprise Java programming would be for your web application to instantly have access to your data-access layer in order to read or write an object from the database. This is a classic example of allowing Spring to inject the reference to the data-access layer into a POJO in the web application in order to load or save an object.

2.2.3. Aspected-oriented programming

AOP provides a different way of thinking about code structure, compared to OOP or procedural programming. Whereas in OOP you model real-world objects or concepts, such as bank accounts, as objects, and organize those objects in hierarchies, AOP enables you to think about concerns or aspects in your system. Typical concerns are transaction management, logging, or failure monitoring. For example, transaction management applies to operations on bank accounts, but also to many other things besides. Transaction management applies to sets of methods without much relationship to the object hierarchy. This can be hard to capture in traditional OOP.

Spring AOP is used in the framework itself for a variety of purposes, many of which are behind the scenes and which many users may not realize are the result of AOP:

• Declarative transaction management
This is the most important out-of-the-box service supplied with Spring. It's analogous to the value proposition of EJB container-managed transactions (CMT).

• Hot swapping
An AOP proxy can be used to provide a layer of indirection. For example, if an OrderProcessor? depends on an InventoryManager?, and the InventoryManager? is set as a property of the OrderProcessor?, it's possible to introduce a proxy to ensure that the InventoryManager? instance can be changed without invalidating the OrderProcessor? reference. This mechanism is threadsafe, providing powerful "hot swap" capabilities.

• "Dynamic object" support
As with hot swapping, the use of an AOP proxy can enable "dynamic" objects such as objects sourced from scripts in a language such as Groovy or Beanshell to support reload (changing the underlying instance) and (using introduction) implement additional interfaces allowing state to be queried and manipulated (last refresh, forcible refresh, and so on).

• Security: Acegi Security for Spring
Is an associated framework that uses Spring AOP to deliver a sophisticated declarative security model.

2.2.4. Data access framework

Spring's data access framework addresses common difficulties developers face when working with databases in applications. Support is provided for all popular data access frameworks in Java: JDBC, iBatis / MyBatis?, Hibernate, JDO, JPA, Oracle TopLink?, Apache OJB, and Apache Cayenne, among others. For all of these supported frameworks, Spring provides these features:

Resource management - automatically acquiring and releasing database resources
Exception handling - translating data access related exception to a Spring data access hierarchy
Transaction participation - transparent participation in ongoing transactions
Resource unwrapping - retrieving database objects from connection pool wrappers
Abstraction for BLOB and CLOB handling

Together with Spring's transaction management, its data access framework offers a flexible abstraction for working with data access frameworks. The Spring Framework doesn't offer a common data access API; instead, the full power of the supported APIs? is kept intact. The Spring Framework is the only framework available in Java which offers managed data access environments outside of an application server or container.

2.2.5. Model View Controller

The Spring Framework features its own MVC web application framework, which wasn't originally planned. The Spring developers decided to write their own web framework as a reaction to what they perceived as the poor design of the popular Jakarta Struts web framework, as well as deficiencies in other available frameworks. In particular, they felt there was insufficient separation between the presentation and request handling layers, and between the request handling layer and the model.

Like Struts, Spring MVC is a request-based framework. The framework defines strategy interfaces for all of the responsibilities which must be handled by a modern request-based framework. The goal of each interface is to be simple and clear so that it's easy for Spring MVC users to write their own implementations if they so choose. MVC paves the way for cleaner front end code. All interfaces are tightly coupled to the Servlet API. This tight coupling to the Servlet API is seen by some as a failure on the part of the Spring developers to offer a high-level abstraction for web-based applications[citation needed]. However, this coupling makes sure that the features of the Servlet API remain available to developers while offering a high abstraction framework to ease working with said API.

2.3. Hibernate

Is an object-relational mapping (ORM) library for the Java language, providing a framework for mapping an object-oriented domain model to a traditional relational database so you can map youra database tables to objects in your java code.Hibernate is free as open source software that is distributed under the GNU Lesser General Public License.

2.3.1. What is Hibernate ?

Hibernate is an object-relational mapping (ORM) library for the Java language, providing a framework for mapping an object-oriented domain model to a traditional relational database. Hibernate solves object-relational impedance mismatch problems by replacing direct persistence-related database accesses with high-level object handling functions.


2.3.2. Features of Hibernate

  • Hibernate provides three full-featured query facilities: Hibernate Query Language (HQL), Hibernate Criteria Query API, and enhanced support for queries expressed in the native SQL dialect of the database.
  • Filters for working with temporal (historical), regional or permissioned data.
  • Enhanced Criteria query API: with full support for projection/aggregation and subselects.
  • Runtime performance monitoring: via JMX or local Java API, including a second-level cache browser.
  • Eclipse support, including a suite of Eclipse plug-ins for working with Hibernate 3.0, including mapping editor, interactive query prototyping, schema reverse engineering tool.
  • Hibernate is Free under LGPL: Hibernate can be used to develop/package and distribute the applications for free.
  • Hibernate is Scalable: Hibernate is very performant and due to its dual-layer architecture can be used in the clustered environments.
  • Less Development Time: Hibernate reduces the development timings as it supports inheritance, polymorphism, composition and the Java Collection framework.
  • Automatic Key Generation: Hibernate supports the automatic generation of primary key for our.
  • Hibernate XML binding enables data to be represented as XML and POJOs? interchangeably.

2.3.3. Mapping

Mapping Java classes to database tables is accomplished through the configuration of an XML file or by using Java Annotations. When using an XML file, Hibernate can generate skeletal source code for the persistence classes. This is unnecessary when annotations are used, which is the most convenient way today.


Facilities to arrange one-to-many and many-to-many relationships between classes are provided. In addition to managing associations between objects, Hibernate can also manage reflexive associations where an object has a one-to-many relationship with other instances of its own type. Hibernate supports the mapping of custom value types. This makes the following scenarios possible:

  • Overriding the default SQL type that Hibernate chooses when mapping a column to a property.
  • Mapping Java Enum to columns as if they were regular properties.
  • Mapping a single property to multiple columns.


Hibernate provides transparent persistence for Plain Old Java Objects (POJOs?). The only strict requirement for a persistent class is a no-argument constructor, not necessarily public. Proper behavior in some applications also requires special attention to the equals() and hashCode() methods.

Collections of data objects are typically stored in Java collection objects such as Set and List. Java generics, introduced in Java 5, are supported. Hibernate can be configured to lazy load associated collections. Lazy loading is the default as of Hibernate 3

Related objects can be configured to cascade operations from one to the other. For example, a parent such as an Album object can be configured to cascade its save and/or delete operation to its child Track objects. This can reduce development time and ensure referential integrity. A dirty checking feature avoids unnecessary database write actions by performing SQL updates only on the modified fields of persistent objects.

3. Step-by-step MVC project example (Maven, Spring, Hibernate)

3.1. Installation

See separate page for the manual on how to install all tools and technologies

3.2. New Project

There are more ways how to create new MVC project. The easiest one is create MVC spring template and modify the project.

a) In STS click on File >> New >> Other >> Spring >> Spring Template Project >> Spring MVC Project

b) If your project has following error indication:

c) Pres RMB on project >> Maven >> Update Project
Maven will refresh project, look at pom.xml and download all dependencies

d) Run project: RMB on Project name >> Run as >> Run On server >> Tomcat

3.3. Customize MVC Project

3.3.1. web.xml

A deployment descriptor (DD) refers to a configuration file for an artifact that is deployed to some container/engine.

For web applications, the deployment descriptor must be called web.xml and must reside in the WEB-INF directory in the web application root.


a) Modify web.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	<!-- Creates the Spring Container shared by all Servlets and Filters -->

	<!-- Processes application requests -->

	<!-- Every url request goes thru default spring dispatch servlet -->

	<!-- first page loaded when application starts -->

note: Follow the comments, they are pretty straightforward.

3.3.2. dispatch-servlet.xml

The job of the DispatcherServlet? is to take an incoming URI and find the right combination of handlers (generally methods on Controller classes) and views (generally JSPs?) that combine to form the page or resource that's supposed to be found at that location.

In origin web.xml file there was an appServlet definition:


but has been replaced by:


b) In WEB-INF folder delete "spring" folder
c) In WEB-INF folder create new file dispatch-servlet.xml and save content:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"

	<context:component-scan base-package="springmvc.web" />

	<mvc:resources mapping="/resources/**" location="/resources/" />

	<mvc:default-servlet-handler />

	<!-- Declare a view resolver -->
	<bean id="viewResolver"
		p:prefix="/WEB-INF/views/" p:suffix=".jsp" />


View Resolver is tool, which makes web page handling easier. Will be demonstrated in chapter New Controller.

3.3.3. applicationContext.xml

Spring lets you define multiple contexts in a parent-child hierarchy.

The applicationContext.xml defines the beans for the "root webapp context", i.e. the context associated with the webapp.

The dispatch-servlet.xml (or whatever else you call it) defines the beans for one servlet's app context. There can be many of these in a webapp, one per Spring servlet (e.g. spring1-servlet.xml for servlet spring1, spring2-servlet.xml for servlet spring2).

Beans in dispatch-servlet.xml can reference beans in applicationContext.xml, but not vice versa.

In most simple cases, the applicationContext.xml context is unnecessary. It is generally used to contain beans that are shared between all servlets in a webapp. If you only have one servlet, then there's not really much point, unless you have a specific use for it.

d) Create new file applicationContext.xml in WEB-INF folder, and save content:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"

	<!-- Activates various annotations to be detected in bean classes -->
	<context:annotation-config />

	<!-- Scans the classpath for annotated components that will be auto-registered 
		as Spring beans. For example @Controller and @Service. Make sure to set the 
		correct base-package -->
	<context:component-scan base-package="com.zcu.example" />

	<!-- Configures the annotation-driven Spring MVC Controller programming 
		model. Note that, with Spring 3.0, this tag works in Servlet MVC only! -->
	<mvc:annotation-driven />


3.4. Connection to DB

For access to database will be used Hibernate framework and Oracle DB. Connection to MySQL? or other DB is similar.

3.4.1. Install Oracle driver mvn repository

a) Download the ojdbc6.jar from:

b) Go to folder, where ojdbc6.jar is located run command from command line:
mvn install:install-file -Dfile={ojdbc6.jar} -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0 -Dpackaging=jar

c) Rename ojdbc6.jar to ojdbc6-11.2.0.jar
d) Copy ojdbc6-11.2.0.jar to:

3.4.2. pom.xml

e) Modify root pom.xml. Add following dependencies:

<!-- Database dependencies -->

note: Defined versions musn't be the most actual when you read this document. Please check the lastest version.

If any errors will appear on your project, try: RMB on project >> Maven >> Update project

3.4.3. jdbc.properties

f) Create new file in WEB-IN folder: jdbc.properties , and save db properties:

# database properties

note: Replace "username", "password" and "url" with your db paramaters.

3.4.4. hibernate.cfg.xml

In this file is stored connection to DB for Hibernate.

g) Create new xml file in src/main/resources and save content to hibernate.cfg.xml:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
  <property name="hibernate.connection.url">jdbc:oracle:thin:@students.kiv.zcu.cz:1521:STUDENTS</property>
  <property name="hibernate.connection.username">username</property>
  <property name="hibernate.connection.password">userPassword</property>
  <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
  <property name="hibernate.default_schema">BROZEK</property>
  <property name="show_sql">false</property>
  <property name="hibernate.connection.characterEncoding">UTF-8</property>   

note: Dont forget to change your db parameters.

3.4.5. hibernate-context.xml

This xml file holds context for Hibernate, that needs to be included to Spring.

h) Create new file in WEB-INF folder: hibernate-context.xml and save content:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"

	<context:property-placeholder location="/WEB-INF/jdbc.properties" />

	<!-- Enable annotation style of managing transactions -->
	<tx:annotation-driven transaction-manager="transactionManager" />

	<!-- Declare the Hibernate SessionFactory for retrieving Hibernate sessions -->
	<!-- See http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/orm/hibernate3/annotation/AnnotationSessionFactoryBean.html -->
	<!-- See http://docs.jboss.org/hibernate/stable/core/api/index.html?org/hibernate/SessionFactory.html -->
	<!-- See http://docs.jboss.org/hibernate/stable/core/api/index.html?org/hibernate/Session.html -->
	<bean id="sessionFactory"
		p:dataSource-ref="dataSource" p:configLocation="classpath:hibernate.cfg.xml"
		p:packagesToScan="com.zcu.example" />

	<!-- Declare a datasource that has pooling capabilities -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
		destroy-method="close" p:driverClass="${jdbc.driverClassName}"
		p:jdbcUrl="${jdbc.url}" p:user="${jdbc.username}" p:password="${jdbc.password}"
		p:acquireIncrement="5" p:idleConnectionTestPeriod="60" p:maxPoolSize="100"
		p:maxStatements="50" p:minPoolSize="10" />

	<!-- Declare a transaction manager -->
	<bean id="transactionManager"
		p:sessionFactory-ref="sessionFactory" />


note: Parameter p:packagesToScan="com.zcu.example" is saying to Hibernate, which package should be scan for POJO files.

If this parameter will be missing, POJO classes must be defined as Hibernate mapping in hibernate.cfg.xml file like:

<property name="hibernate.connection.password">xxx</property>
<property name="hibernate.show_sql">true</property>

<mapping class="com.zcu.example.model.YourPojoFile"/>

i) Add following property to applicationContext.xml to import hibernate context, :

<!-- Context import -->
<import resource="hibernate-context.xml" />

Project structure should look like this:

3.5. Model-View-Controller

3.5.1. Model Tools Settings

a) Switch to hibernate perspective, right click and select Add Configuration…
b) In “Project” field, click on the Browse.. button to select your project
c) In “Database Connection” field, click New.. button to create your database settings

d) Choose "Oracle" and press Next
e) Fill requested fields and press Finish

f) In “Configuration File” field, click Setup button to use existing “Hibernate configuration file”, hibernate.cfg.xml, located in: POJO file

For following table ZCU_USER , POJO file will be generated using Hibernate Tools.

a) In “Hibernate Perspective”, click “Hibernate code generation” icon (see below figure) and select Hibernate Code Generation Configuration

note: If you get error when open Database tree: Error fetching children of database, check your stack trace. Mostly caused because version collision of slf4j logger.

In pom.xml change version of slf4j in properties, eg.:


b) Create a new configuration, select console configuration
c) Set Output directory
d) Check option Reverse engineer from JDBC Connection
e) Define wanted Package

f) In Exporter tab, select what you want to generate. Model , mapping file (hbm) , DAO, annotation code and etc.

g) Press Run
h) Check that POJO file has been generated

note: Hibernate Annotations has been mentioned in chapter 2.3.3. Mapping DAO file

Data Acces Object file can be generated by Hibernate tools or written manualy.

a) Crate new DAO file for ZcuUser entity

package com.zcu.example.data.dao;

import java.util.ArrayList;
import javax.annotation.Resource;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.zcu.example.data.pojo.ZcuUser;

public class ZcuUserDAO {

	private static final Logger logger = LoggerFactory

	@Resource(name = "sessionFactory")
	private SessionFactory sessionFactory;

	public ArrayList<ZcuUser> getListUsers() {

		// Retrieve session from Hibernate
		Session session = sessionFactory.getCurrentSession();

		// Create a Hibernate query (HQL)
		Query query = session.createQuery("from  ZcuUser z order by z.id asc");
		// Retrieve all
		ArrayList<ZcuUser> clients = (ArrayList<ZcuUser>) query.list();

		logger.info("User list recieved successfully");
		return clients;

3.5.2. View CSS

a) Create new folder for css files: src/main/webapp/resources/css

b) Create main.css file in that folder

@charset "utf-8";

* {
	margin: 0;
	padding: 0;
	text-indent: 0;

body {
	font: 80%/1.4 Verdana, Arial, Helvetica, sans-serif;
	margin: 0;
	padding: 0;
	color: #000;
	background-color: white;

h1,h2,h3,h4,h5,h6,p {
	margin-top: 0;
	padding-right: 15px;
	padding-left: 0px;
	padding-bottom: 20px;
	padding-top: 10px;

a img {
	border: none;

a:link,a:visited {
	color: #25B3E0;
	text-decoration: underline;

a:hover,a:active,a:focus {
	text-decoration: none;

#header {
	background: url("../img/kiv_header.png") no-repeat scroll 0 0 transparent;	
	color: #666666;
	height: 100px;
	font: 120%/1.4 Verdana, Arial, Helvetica, sans-serif;

a) Create new folder for image files: src/main/webapp/resources/img
b) Save following image into folder JSP

a) Create users.jsp into: src/main/webapp/web-inf/views

b) Save content

<%@ page language="java" contentType="text/html; charset=utf-8"	pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ZCU MVC Example</title>
<link href="resources/css/main.css" rel="stylesheet" type="text/css" />

	<div id="header"></div>


		<c:forEach var="u" items="${users}" varStatus="st">
				<td><c:out value="${u.login}" /></td>
				<td><c:out value="${u.passw}" /></td>

c) Modify home.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ZCU MVC Example</title>
<link href="resources/css/main.css" rel="stylesheet" type="text/css" />

	<div id="header"></div>
	<h1>Hello world!</h1>

	<p>This is first page</p>
		<a href="user-list">Print Users</a>

d) Modify web.xml


3.5.3. Controller New Controller

a) Create UsersController.java class in com.zcu.example package
b) Save content

package com.zcu.example;

import java.util.ArrayList;
import java.util.Locale;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.zcu.example.data.dao.ZcuUserDAO;
import com.zcu.example.data.pojo.ZcuUser;

public class UsersController {

	@Resource(name = "userService")
	private ZcuUserDAO userServis;

	@RequestMapping(value = "/user-list", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {

		ArrayList<ZcuUser> usersList = userServis.getListUsers();
		model.addAttribute("users", usersList);	
		return "users";

note: Statement return "users" means return users.jsp . Because we have already defined the prefix and postfix for dispatch-servlet in chapter 1.3.2. dispatch-servlet.xml.

note: Annotation @RequestMapping(value = "/user-list", method = RequestMethod.GET) handle uri from home.jsp.

3.6. Final project

3.6.1. Structure

In this point your project structure should be like on following figure:

3.6.2. Run application

a) Press RMB on project >> Run as >> Run on Server

b) Click on link Print Users

3.6.4. Download sample project

Sample project can be downloaded from bellow link, and imported as Existing Maven Project:

4. Tips & Tricks

This topic contains useful hints to make your life much easier.

4.1. General

Errors and problems
If you get some unknown error, which you can’t solve, be calm. Most of the beginner’s error has been already solved. Look at your stack trace and try to search a little bit in Google. Usually most answers can be find in http://stackoverflow.com .

A lot of useful tutorials can be found in following servers.

Rebel uses Rebellion Technology to instantly reload changes made to a class structure, making a full app redeploy unnecessary. You just save, refresh and see the changes right away. JRebel? tracks changes that you make in your workspace, and updates them on-the-fly, so you can keep focused on the code and stay in the zone without interruption.

4.2. Maven

The latest versions of libraries, plugins etc. can be checked and found in public maven repositories. For example try search for „log4j“ and you will get list of all version.

Command line
Since maven is added to the classpath (see chapter 1.1.2. Maven), maven commands can be invoked directly from anywhere from command line. Command mvn clean install will be your best friend for very long time at the begging.

C:\ws\ZCU_Example>mvn clean install -Dmaven.test.skip=true

Maven profiles can be very useful for example if you need build one product with various configurations. Specific configuration stored in profile is activated with parameter –p . More info about profiles can be found in maven page:

UTF-8 Encoding
To avoind warnings like:

[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!

Add following configuration to your pom.xml file:


4.3. Spring

UTF-8 Encoding
It has nothing to do with Maven settings. To get proper input from Spring forms and other items, set UTF-8 encoding to your web.xml file.


Static content handling
If your DispatchServlet? is set to handle all root urls like in chapter 3.3.1. web.xml :



Any js, img, css won't be available. Since spring 3.0.4, there is a configuration parameter that is called <mvc:resources/> (see chapter 3.3.2. dispatch-servlet.xml), which can be used to serve static resources while still using the DispatchServlet? on your site's root.

Spring security
Very convenient way to handle access to pages is done by Spring security module. For more details see:

4.4. Hibernate

Using hibernate validator annotations makes form validation very easy! For example by one simple annotation like @Email can be define on model layer that property should held an email address information. User won’t be able sent form until the field will be filled correctly.

Sequencer incrementing
To avoid generating new ID incremented by 50 (or any other non-making sence number) during inserting new record to database, use @SequenceGenerator(name="seqAddress", sequenceName="SEQ_ADDRESS" ,allocationSize=1) annotations in your POJO file.

@SequenceGenerator(name="seqAddress", sequenceName="SEQ_ADDRESS" ,allocationSize=1)
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seqAddress")
@Column(name = "ID", unique = true, nullable = false, precision = 5, scale = 0)
public long getId() {
  return this.id;

Where sequenceName="SEQ_ADDRESS" is your own sequencer in database and name="seqAddress" is just variable name.

Multiple bags fetch error
If you get similar hibernate exception like:

org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags

A newer version of hibernate (supporting JPA 2.0) should handle this. But otherwise you can work it around by annotating the collection fields with annotation: