All the software applications that appear below represent trademarks and they are the property of their respective owners.
Use and implement my notes in this article at your own risk.
The following topics are discussed:
1. General Considerations - overview of the subject;
2. Prerequisites - what you need to setup a Spring 3.0 MVC app;
3. Installation - installation of the tools needed (platforms, IDEs, aso);
4. Assembly librairies - setting up the used JEE librairies;
5. Configuration
6. MySQL database - database description;
7. Considerations;
1. General Considerations:
This section gives you some hints in how to setup a Spring 3.0 MVC application that uses Hibernate as persistence layer for MySQL database objects.
It is also used as a basis configuration for the next samples posted on this blog, namely:
"Spring 3.0 Framework - XML Configuration of a Spring MVC Application",
"Spring 3.0 Framework - Annotation Configuration of a Spring MVC Application",
"Spring 3.0 Framework - JavaConfig Configuration of a Spring MVC Application",
"Spring 3.1 Framework - JavaConfig Configuration of a Spring 3.1 MVC Application",
Note: My recommendation is to read in this order all the posts and to decide which one you will use in a Spring MVC project.
Note: While XML and Annotation Configurations are backward compatible with Spring Framework 2.5, a set of JavaConfig capabilities appeaqred firstly at Spring Framework 3.0 and the evolved at Spring Framework 3.1. All the configurations presented are forward compatible with just released Spring Framework 3.1 and future versions.
2. Prerequisites:
2.1 Operating System;
2.2. Java;
2.3. Development IDE;
2.4. Tomcat 7;
2.5. Spring 3.0.5 Framework;
2.6. Hibernate 3.6.0;
2.7. MySQL Connector;
2.8. Logging errors;
2.1. Operating System
I used WinXP SP3 for this sample, but you may use any OS on which you may install Java Virtual Machine.
2.2. Java
You will need to have installed Java JDK 1.6.0_x. Go download'em from Oracle website.
2.3. Development IDE
You may use:
- Netbeans;
- Eclipse with WTP;
- MyEclipse;
- SpringSource Tool Suite (STS).
In my case, I used SpringSource Tool Suite (STS) v. 2.8.1 which you may download and install for free, so google'it.
Generally speaking, you will need an IDE that supports JEE, not only JSE.
2.4. Tomcat 7
I used Apache Tomcat 7 as web container, but you may use any web servers that supports JEE deployments.
2.5. Spring 3.0.5 Framework
I used Spring v. 3.0.5
You need to download latest Spring Framework librairies, so google for'em;
2.6. Hibernate 3.6.0
Hibernate v. 3.6.0 was used, so, google it.
2.7. MySQL Connector
I used mysql-connector-java-5.1.14-bin.jar
Also, for Tomcat you may need: tomcat-jdbc.jar
I used MySQL 5, as I have it configured on the machine, but you may use any database support with the condition to configure the database connection driver.
Download MySQL 5 from Oracle, together with a visual database manager for MySQL; I used MySQL Administrator, but you may find others: Workbench, Heidi, Navicat, aso.
2.8. Logging errors
You will need to set a Java properties named log4j.properties, together with the following Java installed libraries:
log4j-1.2.16.jar
log4j-over-slf4j-1.6.1.jar
slf4j-api-1.5.8.jar
slf4j-jcl-1.5.8.jar
3. Installation
Once you downloaded all the above, you'll have to install:
- Java JDK; install to default specified location;
- Apache Tomcat 7 - install to default location; use the default specified port (8080) for tomcat HTTP web connector;
- Development IDE - install to specified location;
- MySQL - download to specified default location; use the default specified port (3306) for MySQL service database connectivity; also install the MySQL database manager (Administrator, Workbench, Heidi, aso) to default specified location;
Note: if installed, do not install again.
4. Assembly librairies
After you downloaded all the above, be sure you gathered on your disk and placed in a folder (let's say "lib") the following librairies.
Later, you should have these on the application library path:
- antlr-2.7.6.jar
- aopalliance-1.0.jar
- asm-3.1.jar
- cglib-2.2.jar // used only for JavaConfig
- commons-collections-3.1.jar
- commons-dbcp-1.3.jar
- commons-logging-1.1.1.jar
- commons-pool-1.5.4.jar
- dom4j-1.6.1.jar
- hibernate-annotations-3.5.3-Final.jar
- hibernate-commons-annotations-3.2.0.Final.jar
- hibernate-core-3.5.3-Final.jar
- hibernate-jpa-2.0-api-1.0.0.Final.jar
- javassist-3.9.0.GA.jar
- jstl-1.2.jar
- jta-1.1.jar
- log4j-1.2.16.jar
- log4j-over-slf4j-1.6.1.jar
- mysql-connector-java-5.1.14-bin.jar
- servlet-api-2.5.jar
- slf4j-api-1.5.8.jar
- slf4j-jcl-1.5.8.jar
- spring-aop-3.0.5.RELEASE.jar
- spring-asm-3.0.5.RELEASE.jar
- spring-beans-3.0.5.RELEASE.jar
- spring-context-3.0.5.RELEASE.jar
- spring-core-3.0.5.RELEASE.jar
- spring-expression-3.0.5.RELEASE.jar
- spring-javaconfig-1.0.0.m3.jar
- spring-jdbc-3.0.5.RELEASE.jar
- spring-orm-3.0.5.RELEASE.jar
- spring-tx-3.0.5.RELEASE.jar
- spring-web-3.0.5.RELEASE.jar
- spring-webmvc-3.0.5.RELEASE.jar
5. Configuration
Following Spring 3.0 MVC web app architecture, you will configure:
5.1. Spring 3.0 MVC app;
5.2. web.xml;
5.3. app-config.xml;
5.4. mvc-config.xml;
5.5. log4j.properties;
5.1. Spring 3.0 MVC physical structure
With your IDE development, create a new JEE project; name it "sprBlog".
Under "sprBlog" you should have:
- the "src" directory, in which will reside all your Java code;
- the "WEB-INF" directory that will store the web dependecy files: librairies (lib subfolder), web.xml, app-config.xml, aso;
- other web used subfolders: css, images, aso;
Note: in case of SpringSource Tool Suite (STS), all the functional web modules (WEB-INF plus css, images, aso are placed in an internal chosen folder named WebContent which constitutes the webroot of the web application; this folder ("WebContent") differs when using other IDEs.
Basically, the structure should look like in the image below taken from STS IDE:
Spring project app structure:
5.2. web.xml
This is the web app descriptor, located under "WEB-INF" application directory:
<<
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>sprBlog</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/app-config.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/web/*</url-pattern>
</servlet-mapping>
</web-app>
>>
In this file there is configured the listener and dispatcher for Spring Framework; the listener and the dispatcher are the main components that allows the definition of the Spring Framework in order to use it in a web application.
5.3. app-config.xml
This is the Spring configuration file, located unde "WEB-INF" directory. It is loaded by Spring ContextLoaderListener defined earlier in web.xml and defines the business components used later by Spring; more exactly, the business components represent the Model layer and the operations used on this Model to get and set data in the database; the Model is represented by Hibernate entities, while the database operations use Hibernate sessions that are manipulated by Spring services.
Here you should define at least:
a. a data source for the database you use (in our case is MySQL);
b. a session factory bean that uses a connection to your database in order to create a Hibernate working session; the session factory should know which are the Hibernate entities used to map the database tables and which is the database specific Hibernate behaviour;
c. a transaction manager that will be used in case of transactional Hibernate operations over the database;
d. the Spring business components (services) used to manipulate the Hibernate objects over the databae;
Note: This will be detailed in the next posts, as they refer to way of configuration of Spring 3.0 MVC application.
5.4. mvc-config.xml
This file is establish the MVC components used by Spring DispatcherServlet in order to manipulate the business components and to make them available to the web pages; more exactly, the dispatcher choses a Spring Controller that will render later a View with the help of a handler.
Here you should define at least:
a. the Spring Controllers used to render the Views;
b. one or more View resolvers that will define the type of the View that will be rendered; in Spring 3.0, the default rendered type is JSTL - this means that you may design Views as JSP files and control the data provided by Controllers with the help of JSTL;
Note: This will be detailed in the next posts, as they refer to way of configuration of Spring 3.0 MVC application.
5.5. log4j.properties
This is located under the classpath of application ("WEB-INF/classes" folder) and will configure log4j to log the app errors:
<<
log4j.rootLogger=ERROR, dest1
log4j.appender.dest1=org.apache.log4j.DailyRollingFileAppender
log4j.appender.dest1.File=${catalina.home}/logs/sprBlog.log
log4j.appender.dest1.DatePattern='.'yyyy-MM-dd
log4j.appender.dest1.layout=org.apache.log4j.PatternLayout
log4j.appender.dest1.layout.ConversionPattern=[%5p] [%t] %d{dd.MM.yyyy HH:mm:ss} %c (%F:%M:%L)%n%m%n%n
log4j.logger.blog=ERROR
log4j.logger.org.springframework=ERROR
log4j.logger.org.springframework.security=ERROR
log4j.logger.org.hibernate=ERROR
log4j.logger.org.apache=ERROR
>>
So, only ERROR type events will be logged to "${catalina.home}/logs/sprBlog.log".
Note. You may configure log4j to log the errors to your console by using org.apache.log4j.ConsoleAppender as log appender.
6. MySQL database
The database used in the following samples, namely "blog", contains 3 tables: zone, country, city. These tables are linked by foreign keys that will create a correspondence of the kind - zones include countries and countries include cities.
Use the following script to create the MySQL "blog" database from MySQL command line prompt:
<<
CREATE DATABASE IF NOT EXISTS blog;
USE blog;
DROP TABLE IF EXISTS `zone`;
CREATE TABLE `zone` (
`cod` varchar(4) NOT NULL,
`name` varchar(45) NOT NULL,
PRIMARY KEY (`cod`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `zone` (`cod`,`name`) VALUES
('AS','Asia'),
('EU','Europe'),
('NA','North America'),
('SA','South America');
DROP TABLE IF EXISTS `country`;
CREATE TABLE `country` (
`cod` varchar(4) NOT NULL,
`name` varchar(45) NOT NULL,
`cod_zone` varchar(4) NOT NULL,
PRIMARY KEY (`cod`),
KEY `FK_country_zone` (`cod_zone`),
CONSTRAINT `FK_country_zone` FOREIGN KEY (`cod_zone`) REFERENCES `zone` (`cod`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `country` (`cod`,`name`,`cod_zone`) VALUES
('AG','Argentina','SA'),
('BR','Brasil','SA'),
('CA','Canada','NA'),
('CN','China','AS'),
('DE','Germany','EU'),
('FR','France','EU'),
('GR','Greece','EU'),
('RU','Russia','AS'),
('US','United States','NA');
DROP TABLE IF EXISTS `city`;
CREATE TABLE `city` (
`id` int(10) unsigned NOT NULL auto_increment,
`cod_country` varchar(4) NOT NULL,
`name` varchar(45) NOT NULL,
PRIMARY KEY (`id`),
KEY `FK_city_country` (`cod_country`),
CONSTRAINT `FK_city_country` FOREIGN KEY (`cod_country`) REFERENCES `country` (`cod`)
) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=latin1;
INSERT INTO `city` (`id`,`cod_country`,`name`) VALUES
(1,'DE','Berlin'),
(2,'DE','Dortmund'),
(3,'DE','Munchen'),
(4,'FR','Paris'),
(5,'FR','Marseille'),
(6,'FR','Bordeaux'),
(7,'GR','Athens'),
(8,'GR','Thesaloniki'),
(9,'GR','Larissa'),
(10,'US','Seattle'),
(11,'US','New York'),
(12,'US','Detroit'),
(13,'US','Los Angeles'),
(14,'CA','Toronto'),
(15,'CA','Montreal'),
(16,'CA','Vancouver'),
(17,'BR','Janeiro'),
(18,'BR','Brasil'),
(19,'AG','Aires'),
(20,'RU','Moscow'),
(21,'RU','Stalingrad'),
(22,'RU','Petersburg'),
(23,'CN','Beijing'),
(24,'CN','Nanjang');
>>
7. Considerations
Having all the above installed and configured, we may follow the next sections that describe the Spring 3.0 MVC application possible configurations.
salut,
ReplyDeleteai putea te rog uploada undeva, orientativ, codul sursa pentru proiectul exemplu de mai sus?
sal, momentan n-am pus undeva codul; as putea sa pun pe docs.google.com, dar mai bine lasa o adresa de email sau da-mi un email la vsorin@gmail.com; nu am cine stie ce timp de alocat pt blog din cauza servici; oricum, vezi ca mai bine folosesti spring 3.1 pt JavaConfig; este un topic tot aici pe blog exact langa asta de spring 3.0.
ReplyDelete