Spring tutorial

Spring tutorial

Here I will describe on Spring tutorial. let me describe the working environment. my another blog shows how to set up your environment. To know more on springframework please visit here.

Spring tutorial – step by step

In this example we are using following tools

Eclipse 3.4: Ganymede;

Plugs in: svn, Maven, spring-ide, tomcat lunher, ant.

Tomcat: 5.5

FireFox: 3

Create a new project in Eclipse;

Spring tutorial - Eclipse create new project

Spring tutorial – Eclipse create new project

Spring tutorial - set project name

Spring tutorial – set project name

create one package name:  click the right button on the src folder and select new -> Package and put  com.rajib.spring.samplespring.model value.

create a class Information under the model folder. In this Spring tutorial have used couple of java classes, here are they


package com.rajib.spring.samplespring.model;

public class Information {
	private String projectName = "Spring demo1";
	private String version = " 1.1";

	public String getProjectName() {
		return projectName;

	public void setProjectName(String projectName) {
		this.projectName = projectName;

	public String getVersion() {
		return version;

	public void setVersion(String version) {
		this.version = version;

create an xml file  applicationContext.xml under the src file. by default spring is looking this under web-inf folder but we put his under class path intentionally thats why we will mention the conetx file location at the web.xml. In this spring tutorial, I am trying to show you can create a spring application. We can mention all beans under <beans> tag.

————- applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
  <bean id="information"      

we will show information.project name and information.version at index.jsp page. we used the information class as bean.

Create WebContent folder under the project. create WEB-INF folder under the WebContent folder. Create lib folder under WEB-INF folder. I used lot of jar files as library file. My lib contains jarlist jar files.

Create log4j.properties and web.xml file under WEB-INF folder.


log4j.logger.java.sql=DEBUG, STDOUT
log4j.logger.com.ibatis=DEBUG, STDOUT

log4j.appender.STDOUT.layout.conversionPattern=%-5p - %-26.26c{1} - %mn

————————- web.xml

 <?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	<description>Spring simple example</description>





Create index.jsp file under WebContent folder.

———– index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<%@ page
<title>Simple Spring example</title>
<body bgcolor="white">
	<h2>(Spring example by rajib_info@yahoo.com)</h2>

		BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(
		Information info = (Information) beanFactory.getBean("information");

	Hello, this is sample spring project!
	<br /> Project Name is :
	<b> <%=info.getProjectName()%>
	</b> Project Version is :
	<b> <%=info.getVersion()%>

to make the build path to do the following

Spring tutorial - eclipse build path

Spring tutorial – eclipse build path

-click right button on the project and select properties select the Java Build Path from the left side. click – Library tab from right side , click Add jar select all jars of  (SimpleSpring->WebContent->lib all jars). click the Ordre and Ecports tab and click on  Select All button.

How to run this project:

for building this project we need buld.xml


—————————- build.xml

<project name="simplespring" basedir="." default="deploy">
	<!-- Project settings -->
	<property name="project.distname" value="simplespring" />
	<!-- Local system paths -->
	<property file="${basedir}/build.properties" />
	<property name="webroot.dir" value="${basedir}/WebContent" />
	<property name="webinf.dir" value="${webroot.dir}/WEB-INF" />
	<property name="build.dir" value="target" />

	<!-- classpath for WEB-INF/lib -->
	<path id="compile.classpath">
		<pathelement path="${webinf.dir}/lib/acegi-security-1.0.3.jar" />
		<pathelement path="${webinf.dir}/lib/activation.jar" />
		<pathelement path="${webinf.dir}/lib/antlr-2.7.6.jar" />
		<pathelement path="${webinf.dir}/lib/aopalliance.jar" />
		<pathelement path="${webinf.dir}/lib/avalon-framework-4.2.0.jar" />
		<pathelement path="${webinf.dir}/lib/barbecue-1.1.jar" />
		<pathelement path="${webinf.dir}/lib/bsf-2.3.jar" />
		<pathelement path="${webinf.dir}/lib/bsh-2.0b4.jar" />
		<pathelement path="${webinf.dir}/lib/cglib-nodep-2.1_3.jar" />
		<pathelement path="${webinf.dir}/lib/commons-annotations.jar" />
		<pathelement path="${webinf.dir}/lib/commons-beanutils.jar" />
		<pathelement path="${webinf.dir}/lib/commons-codec.jar" />
		<pathelement path="${webinf.dir}/lib/commons-collections.jar" />
		<pathelement path="${webinf.dir}/lib/commons-dbcp.jar" />
		<pathelement path="${webinf.dir}/lib/commons-digester-1.8.jar" />
		<pathelement path="${webinf.dir}/lib/commons-discovery-0.4.jar" />
		<pathelement path="${webinf.dir}/lib/commons-fileupload.jar" />
		<pathelement path="${webinf.dir}/lib/commons-io.jar" />
		<pathelement path="${webinf.dir}/lib/commons-javaflow-20060411.jar" />
		<pathelement path="${webinf.dir}/lib/commons-lang.jar" />
		<pathelement path="${webinf.dir}/lib/commons-logging-1.1.1.jar" />
		<pathelement path="${webinf.dir}/lib/commons-pool.jar" />
		<pathelement path="${webinf.dir}/lib/commons-validator-1.3.1.jar" />
		<pathelement path="${webinf.dir}/lib/dom4j-1.6.1.jar" />
		<pathelement path="${webinf.dir}/lib/dwr.jar" />
		<pathelement path="${webinf.dir}/lib/EasySI-0.9.0.jar" />
		<pathelement path="${webinf.dir}/lib/ehcache-1.2.3.jar" />
		<pathelement path="${webinf.dir}/lib/fop.jar" />
		<pathelement path="${webinf.dir}/lib/ibatis-common-2.jar" />
		<pathelement path="${webinf.dir}/lib/ibatis-sqlmap-2.jar" />
		<pathelement path="${webinf.dir}/lib/iReport.jar" />
		<pathelement path="${webinf.dir}/lib/itext-1.3.1.jar" />
		<pathelement path="${webinf.dir}/lib/jakarta-oro-2.0.8.jar" />
		<pathelement path="${webinf.dir}/lib/jaxen-1.1-beta-7.jar" />
		<pathelement path="${webinf.dir}/lib/jazzy-core.jar" />
		<pathelement path="${webinf.dir}/lib/jsf-facelets.jar" />
		<pathelement path="${webinf.dir}/lib/jsf-impl.jar" />
		<pathelement path="${webinf.dir}/lib/jstl.jar" />
		<pathelement path="${webinf.dir}/lib/jta.jar" />
		<pathelement path="${webinf.dir}/lib/log4j-1.2.14.jar" />
		<pathelement path="${webinf.dir}/lib/mail.jar" />
		<pathelement path="${webinf.dir}/lib/myfaces-api-1.2.5.jar" />
		<pathelement path="${webinf.dir}/lib/myfaces-impl-1.2.5.jar" />
		<pathelement path="${webinf.dir}/lib/myfaces-shared-impl-3.0.5.jar" />
		<pathelement path="${webinf.dir}/lib/ojdbc14.jar" />
		<pathelement path="${webinf.dir}/lib/poi-3.0.1-FINAL-20070705.jar" />
		<pathelement path="${webinf.dir}/lib/quartz-all-1.6.1-RC1.jar" />
		<pathelement path="${webinf.dir}/lib/serializer-2.7.0.jar" />
		<pathelement path="${webinf.dir}/lib/spring-aop.jar" />
		<pathelement path="${webinf.dir}/lib/spring-beans.jar" />
		<pathelement path="${webinf.dir}/lib/spring-core.jar" />
		<pathelement path="${webinf.dir}/lib/spring-context.jar" />
		<pathelement path="${webinf.dir}/lib/spring-dao.jar" />
		<pathelement path="${webinf.dir}/lib/spring-ibatis.jar" />
		<pathelement path="${webinf.dir}/lib/spring-jdbc.jar" />
		<pathelement path="${webinf.dir}/lib/spring-support.jar" />
		<pathelement path="${webinf.dir}/lib/spring-web.jar" />
		<pathelement path="${webinf.dir}/lib/spring-webmvc.jar" />
		<pathelement path="${webinf.dir}/lib/standard.jar" />
		<pathelement path="${webinf.dir}/lib/tomahawk12-1.1.8.jar" />
		<pathelement path="${webinf.dir}/lib/xalan-2.7.0.jar" />
		<pathelement path="${webinf.dir}/lib/xercesImpl-2.7.1.jar" />
		<pathelement path="${webinf.dir}/lib/xml-apis-1.3.02.jar" />
		<pathelement path="${webinf.dir}/lib/xmlgraphics-commons-1.1.jar" />
		<pathelement path="${webinf.dir}/classes" />
		<pathelement path="${classpath.external}" />
		<pathelement path="${classpath}" />

	<!-- define your folder for deployment -->
	<property name="deploy.dir" value="deploy" />

	<!-- Check timestamp on files -->
	<target name="prepare">
		<tstamp />

	<!-- Copy any resource or configuration files -->
	<target name="resources">
		<copy todir="${webinf.dir}/classes" includeEmptyDirs="no">
			<fileset dir="src">
					<include name="**/*.conf" />
					<include name="**/*.properties" />
					<include name="**/*.xml" />

	<!-- Normal build of application -->
	<target name="compile" depends="prepare,resources">
		<javac srcdir="src" destdir="${webinf.dir}/classes" encoding="UTF-8">
			<classpath refid="compile.classpath" />

	<!-- Remove classes directory for clean build -->
	<target name="clean" description="Prepare for clean build">
		<delete dir="${webinf.dir}/classes" />
		<mkdir dir="${webinf.dir}/classes" />

	<!-- Build entire project -->
	<target name="build" depends="prepare,compile" />
	<target name="rebuild" depends="clean,prepare,compile" />

	<!-- Create binary distribution -->
	<target name="war" depends="build">
		<mkdir dir="${build.dir}" />
		<war basedir="${webroot.dir}" warfile="${build.dir}/${project.distname}.war"
			<exclude name="WEB-INF/${build.dir}/**" />
			<exclude name="WEB-INF/src/**" />
			<exclude name="WEB-INF/web.xml" />

	<target name="deploy" depends="war">
		<delete file="${deploy.dir}/${project.distname}.war" />
		<delete dir="${deploy.dir}/${project.distname}" />
		<copy file="${build.dir}/${project.distname}.war" todir="${deploy.dir}" />


there are some supporting file exist for this build.xml these are –

————————- build.properties


so we need to create another folder external-lib and put these 2 jar files.

Spring tutorial - build

Spring tutorial

to build this project use these stepts – open build.xml. click – window->show view -> outline . click the right button on rebuild select – Run As -> 1 Ant Build.

set a context configaration file at {Tomcat folder}/conf/Catalina/localhost. lest assume this file name is – simplespring.xml and its looks –




<?xml version="1.0" encoding="UTF-8"?>

<Context docBase="D:/workspace/simplespring/WebContent"
privileged="true" antiResourceLocking="false" antiJARLocking="false">

if your eclipse has tomcat lunch plugs in so you can deploy from eclipse. click on as picture

Spring tutorial - run-tomcat

Spring tutorial


The output looks —

Spring tutorial - output

Spring tutorial

Download Spring tutorial

Click here to download this project.

Eclipse is running in a JRE, but a JDK is required

I got this problem –

“Eclipse is running in a JRE, but a JDK is required
Some Maven plugins may not work when importing projects or updating source folders.”

I put the java home as C:Program FilesJavajdk1.5.0_05

and path – C:Program FilesJavajdk1.5.0_05bin

but i got this problem. let me say how i solve it –

open eclipse.ini from eclipse folder. put this line

C:Program FilesJavajdk1.5.0_05binjavaw.exe

so the total file looks-

C:Program FilesJavajdk1.5.0_05binjavaw.exe

2nd way solution –

create a bat file under the eclipse folder and put this line

eclipse.exe  -vm “C:Program FilesJavajdk1.5.0_05binjavaw.exe”

save this file.  use this file for opening eclipse.

Jasper reports

Jasper reports

This time i am describing how make Jasper reports. Lets download iReport which is a tools of Jasper reports. To get more details on Jasper reports and documents please click here. Yet I described on Jasper reports at my another post. Here I am using iReport-3.0.0 zip file. This version i found mysql driver jar found in the lib folder but i did not see the oracle(ojdbc14.jar) driver jar file. If you would like to use oracle please put this jar file into the lib folder.

Jasper Reports step by step

# Create Connection:  Click Data-> Connections/Datasources. Click New button. select Database JDBC Connection -> Next Button ->now put your database information. i gave here one screen shot Jasper reports - dbconnection window

Pressing test button iReport shows the connection status. If you get any error like oracle/mysql class not found, make sure the lib folder contain your database driver jar file. If you get same excepton so go Options -> ClassPath -> Click add jar. now select the related database jar file. iReport supports multiple database so we can produce Jasper reports using different datasource.

# create a report using iReport:  File -> Report Wizard ->

template : none, connection: mysql, SQL Query : Select *from Person.

Next-> select all columns.  Next -> (do not select any group 1 value, if you want to show the report by any group you can select any column.)  Next -> Tabular Layout (ClassicT) Finish.

now you get one report. now you can change the report title. it looks

Jasper reports - mainscreen1Now you can test this Jasper reports by clicking  Build->Complie or Build->Execute(emptyconnection) or Build-> Execute (active connection). after compile the jaspar file will generatewhere the iReport.exe file is located. empty connection will show only report withoutdata butactive connection will show the data.

Since we want to show only first 30 id records, so we have create a parameter variable. this parameter determine how many record we want to show. to create a parameter click View -> Parameter then a window will come, here we can create variable which will only used as variable that scope is the whole report, field that is used for showing a field in the report and finally parameter that takes data from java class.  Click New button ->parameter name: p_id, class type: java.lang.Integer, use as Prompt uncheckd, default Value expression : new Integer(0) that means we assing a default value for this parameter. iReport always consider all the value as Object not primitive thats why i set write as new Integer(0) Paramete Description: paraeter ID . now click OK.

Now lets set the condition in the query. Click Data-> Report Query now put the following line – select *from person where id < $P{p_id}  here $P{p_id} is the parameter. Jasper reports - reportquery in iReport $F { name } is means field and $V{ name } is indicate variable. now click OK.

Now save the report as person.jrxml. if you complie this report you will get person.jasper file. let see the description of person table.

create table person ( id number(6), name varchar(20));

# Execute iReport From Java: I used eclipse to create one java program that execute Jasper reports.  Open eclipse, click New -> New Java Project  Project Name: SimpleiReprot , select Create new project in workspace, select default JRE, select Create separate folders now click Next -> FInish. now create 3 folders ( lib, report-out, report-src) under this project. The project folder structure looks this Jasper reports - folder_arch3

now put the person.jrxml and person.jaspar file into report-src folder. report-out folder will use for the pdf report file. Here I should mention jrxml file is xml formatted file and .jasper file is generated after compiling .jrxml file. Jasper engine using .jasper file to produce Jasper report at runtime. Now copy all the jar files from ireport’s lib folder into your project lib folder.  now refresh the eclipse project.now set the build path for this project. click the right button on the project and select properties and select the Java Build Path from the left side menu and click the Libraries Tab. it looks as

Jasper reports - eclipse project buildpath

Jasper reports – eclipse project buildpath

Now Add Jar button from the right side. Now select SimpleiReprot project and explore the lib folder and select all the jar files of lib folder. now click OK. Select Order and Exprot tab and Select All button from right side. Click OK.

I used 2 java files. DBConnector.java used for creating the database connection and SimpleiReport.java used for execute the Jasper reports.

Jasper reports  are generated by java class

DBConnector class

import java.sql.Connection;
import java.sql.DriverManager;
 * Database connection class.
 * it return single instance of connection
 * author: rajib_info@yahoo.com
public class DBConnector {
	public static Connection getConnection() {
		Connection connection = null;
		if (connection != null) {
			return connection;
		try {
			connection = DriverManager.getConnection(
					"jdbc:mysql://localhost/development", "root", "");
		} catch (Exception e) {
		return connection;

SimpleiReport Class

import java.sql.Connection;
import java.util.HashMap;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;

 * this class generates one pdf file from jaspar file. here i used one condition that filter
 * only first 30 records.
 * author: rajib_info@yahoo.com
public class SimpleiReport {
	public static void main(String[] args) {
		// database connection
		Connection connection = null;
		String jasperFile = "./report-src/person.jasper";
		String pdfFile = "./report-out/personList.pdf";
		// params used for passing the parameter.
		HashMap&lt;String,Integer&gt; params = new HashMap&lt;String,Integer&gt;();
		params.put("p_id", 30);
		try {
			// get database connection.
			connection = DBConnector.getConnection();

			JasperPrint print = JasperFillManager.fillReport(jasperFile, params,
			JRExporter exporter = new net.sf.jasperreports.engine.export.JRPdfExporter();
			exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
			System.out.println("Created file: " + pdfFile);
		} catch (JRException e) {
		} catch (Exception e) {

If you want to use other database change the DBConnector class.Jasper reports - eclipse-mainClick the right button on the SimpleiReport file and select Run As ->  Java Application. Or you can set Run configaration from the Run->Run Configuration. this run configuration window you have to select the main class. the output console looks

——- output console

Created file: ./report-out/personList.pdf

and personList.pdf file will generate under the report-out folder. the pdf looks as

Jasper reports - output as pdf

Jasper reports – output as pdf

Please ask me if you have any problem or can give me any suggestion.


Making workspace (Set up Eclipse, Tomcat, Ant, Maven, Spring Ide, SVN)

I used eclipse IDE for creating my working environment.

  • Download eclipse.  if you want old version visit this site http://archive.eclipse.org/eclipse/downloads/. unzipped that zip file into your desired location. i used here eclipse v3.4.1.
  • Download tomcat. i used tomcat 5.27 (Windows Service Installer). during installation set the jre path. I guess you have already installed jdk 1.4 or later. install tomcat plugins: download plugins from http://www.easyeclipse.org/site/plugins/tomcat-launcher.html. here you can get some installment information too.

Now run the tomcat server and check this address – http://localhost:8080. you can change the port number by editing tomcat-home/conf/server.xml file.

  • After install tomcat plugins restart your the eclipse by execute the following commands.
    command prompt > eclipse -clean
    Now you can see tomcat in eclipse. Before using the plugin, you must set Tomcat home : Window > Preferences, select Tomcat and set the Tomcat version and Tomcat home fields.
  • Ant : download ant. unzipped your desired location. update your computer env path.click win-key + pause/break key and click Advance tab and select environment variables. create new system variable –
    ANT_HOME=D:/ Development Tools/Java/apache-ant-1.7.0-bin
    update path variable
    PATH= …..;D:/Development Tools/Java/apache-ant-1.7.0-bin/bin

Ensure these two environment variable are set by typing following on command prompt
echo %ANT_HOME%
echo %PATH%

lets check is it installed. open command prompt -> ant press enter. it shows-Buildfile: build.xml does not exist!.  that means it is works.

lets configure eclipse ant. Click Windose -> Prefreneces -> Ant (Runtime) select Classpath tab. now click Ant Home button and set the ant home location.

  • Download Maven.Unzip the maven download to your computer:  D:/Development Tools/Java/maven-2.0.9. update your computer env path.click win-key + pause/break key and click Advance tab and select environment variables. create new system variable –
    M2_HOME=D:/Development Tools/Java/maven-2.0.9
    update path variable
    PATH= …..;D:/Development Tools/Java/maven-2.0.9/bin  Ensure these two environment variable are set by typing following on command prompt

    echo %JAVA_HOME%
    echo %M2_HOME%
    echo %PATH%

type in command prompt ->mvn –version . if this command shows its version that means it works.

You can install maven plugins. use http://m2eclipse.codehaus.org/update/ this link for install this plugin (read the following paragraph for how to install plugins).

please use this link -http://m2eclipse.sonatype.org/update/  this is more update than http://m2eclipse.codehaus.org/update/

  • Click help menu of eclipse and select software update. select available software tab and click add site button. put http://springide.org/updatesite value into location and press OK. after restart you eclipse you will get spring features. lets check is it installed. Press ctrl+N , type spring into new wizard text field then you can see spring tree.
  • SVN: you can download svn client version.

for plugings -Click help menu of eclipse and select software update. select available software tab and click add site button. put http://subclipse.tigris.org/update_1.0.x    value into location and press OK.

or visit this page – http://subclipse.tigris.org/

after restart you eclipse click window->open perspective->other you will see SVN Repository Exploring.

Note – for unzipped i used 7-Zip software this is free.