Sapan Diwakar

Software developer

Follow me on Twitter Check out my code on GitHub View some of my designs on Dribbble Take a look at my Linked In profile

Building Java Web Application using MyBatis, Spring MVC, Ext JS, Tomcat, MySQL, Eclipse [Tutorial]

This tutorial will describe you how to build a Java Web App from scratch using MyBatis, Spring MVC, Ext JS, Tomcat, MySQL on Windows platform. I am not an expert in these technologies so feel free to give suggestion if anything goes wrong in this tutorial. This article might not meet your expectation. If that’s the case then I apologize in advance for ruining your day.
To start with, I will try to give a brief idea about all the terms that we will be using to develop this app: (skip this, go to installation steps)
MyBatis [Newer version of iBatis Framework]: MyBatis is a persistence framework available for Java and .NET that couples objects with stored procedures or SQL statements using a descriptor or annotations. MyBatis is free software that is distributed under the Apache License 2.0.
Spring MVC: Spring MVC helps in building flexible and loosely coupled web applications. MVC stands for Model, View, Controller. Models are responsible for encapsulating the application data. The Views render response to the user with the help of the model object. Controllers are responsible for receiving the request from the user and calling the back-end servi
Spring MVC works in the following manner:
1. The client sends a request to web container in the form of HTTP request.
2. This incoming request is intercepted by Front controller (DispatcherServl
3. The DispatcherServlet consults the HandlerMapping and invokes the Controller associated with the request.
4. The Controller tries to process the request by calling service method and returns the Model and View object in form of ModelAndView instance to the (DispatcherServlet). This object contains model data and name of the view.
5. The Front Controller then tries to resolve the View (which can be Velocity, JSP etc in my case it is JSP) by consulting the ViewResolver object.
6. The View with the help of the model data will render the result back to the user.
Ext JS: Ext JS is a JavaScript library for building interactive web applications. This application uses Ext JS for User Interface Widgets.
Tomcat: Tomcat is an application server from the Apache Software Foundation that executes Java servlets and renders Web pages that include Java Server Page coding.
MySQL: MySQL is a relational database management system (RDBMS) based on SQL (Structured Query Language).
Eclipse: Eclipse is a multi-language software development environment comprising an integrated development environment (IDE) and an extensible plug-in system. It is written mostly in Java and can be uto develop applications in Java and, by means of various plug-ins, other programming languages including C, C++, Perl, PHP, Python.
Installation Steps -
To see how all these things work we are going to build a small java web application name RGITTB2k7 in Eclipse.(skip this, go to development steps)
First thing you will need is downloading and installing all the stuffs-
Installing Eclipse: This web app uses JAVA EE Eclipse (Helios)
You can download this version of eclipse from here.
Installing Tomcat: This web app uses apache-tomcat-7.0.6.
You can use newer version apache-tomcat-7.0.14.
Installing Spring MVC:
To use Spring Framework download these JARs from Spring distribution (with dependencies):
You can try
this alternate link.
I will tell you where to put these JARs later.
Installing MySQL:
This web app uses mysql-connector-java-5.1.15 to use MySQL from Java Web App. To use t
a) Go to: and download JDBC Driver for MySQL (Connector/J) zip archive.
b) Extract the driver .jar file into your Tomcat installation:
CATALINAHOME/common/lib folder (Tomcat 5) or
HOME/lib (Tomcat 6)
Using MyBatis:
Use this link to download Jar libraries for MyBa
Again I will tell you where to put these JARs later.
Using Ext JS:
Use this to download Ext JS related libraries.
Now once all the necessary things are downloaded/installed. We can start developing app named RGIITB2k7.

Creating Database for the app:
Here is SQL Script to create DB named StudentInfo

drop database if exists StudentInfo;  
create database StudentInfo;  
use StudentInfo;

drop table if exists STUDENTS;  
create table STUDENTS (  
NAME varchar(255) not null,  
ENROLLMENT_NUMBER varchar(255) not null  

insert into STUDENTS (NAME, ENROLLMENT_NUMBER) VALUES ("Ashutosh", "RIT2007001");  
insert into STUDENTS (NAME, ENROLLMENT_NUMBER) VALUES ("Sandeep", "RIT2007002");  
insert into STUDENTS (NAME, ENROLLMENT_NUMBER) VALUES ("Ankesh", "RIT2007003");  
insert into STUDENTS (NAME, ENROLLMENT_NUMBER) VALUES ("Ashish ", "RIT2007004");  
insert into STUDENTS (NAME, ENROLLMENT_NUMBER) VALUES ("Naresh", "RIT2007005");  
insert into STUDENTS (NAME, ENROLLMENT_NUMBER) VALUES ("Anudeep", "RIT2007006");  
insert into STUDENTS (NAME, ENROLLMENT_NUMBER) VALUES ("Vishal", "RIT2007007");  
insert into STUDENTS (NAME, ENROLLMENT_NUMBER) VALUES ("Santosh", "RIT2007008");  
insert into STUDENTS (NAME, ENROLLMENT_NUMBER) VALUES ("Ankit", "RIT2007009");  

Now we are ready to open Eclipse IDE:
To create new Dynamic Project Go to: File -> New -> Dynamic Web Project

Right click the project folder, and select Spring Tools -> Add Spring Project Nature, to add Spring capabilities to the web project. This feature will be available once you install the Spring IDE.

Now add packages into the src directory for controller etc. I have named it com.student.controller (you can give as you like). The Spring controller class extends org.springframework.web.servlet.mvc.AbstractController class. To create a new controller class right click the src directory and create a new java class, enter the controller class name and super class name and the Finish button. Make a class named studentInfo in the package
Now its time to add downloaded JARs to your project. to do this add the downloaded JARs(except the extJS) to /WEB-INF/lib folder
The HelloWorldController class has a message property that is set thru the setter injection. The HelloWorldController class should override the handleRequestInternal() method to process the request. After processthe request the handleRequestInternal() method returns a ModelAndView object back to the DispatcherServlet.

package com.batch2k7;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSessionFactory;  
import org.springframework.web.servlet.ModelAndView;  
import org.springframework.web.servlet.mvc.AbstractController;

import com.batch2k7.db.StudentInfoDAO;  
import com.batch2k7.model.StudentInfo;

public class StudentInfoController extends AbstractController {  
    private String message;

    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {

        ModelAndView mav = new ModelAndView("showStudentInfo","welcomeMessage", message);
handleFormSubmission(request, mav);  
        return mav;

    public void setMessage(String message) {
        this.message = message;

Note that showStudentInfo is the name of View (jsp file in this case)

The entry point of Spring 3.0 MVC is the DispatcherServlet. DispatcherServlet is a normal servlet class which implements HttpServlet base class. Thus we need to configure it in web.xml. Add web.xml in /WEB-INF folder.
Now add following lines of code in it.






In above code snippet, we have configure DispatcherServlet in web.xml. Note that we have mapped *.html url pattern with example DispatcherServlet. Thus any url with *.html pattern will call Spring MVC Front controller.

the following code in the DispatcherServlet you just created.

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

    <bean id="viewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
        <property name="prefix">
        <property name="suffix">

    <bean name="/students.html" class="com.batch2k7.StudentInfoController" ></bean>

Here I have mapped students.html to class name com.batch2k7.StudentInfoController. So any url with students.html will be redirected to the class Since any url with .html will be redirected to DispatchedServlet.xml as we defined in web.xml. Also we have defined a bean viewResolver. This bean will resolve the view and add prefix string /WEB-INF/jsp/ and suffix .jspthe view in ModelAndView. Note that in our StudentInfoController class, we have return a ModelAndView object with view name “showStudentInfo”. This will be resolved to path /WEB-INF/jsp/showStudentInfo.jsp.
After setting all these things we are now ready to define a model class which will interact with our database(we have written a sql script to create database earlier in this tutorial, remember?). These Plain Old Java Objects (POJOs) (the model classes, in our case its is only one class) will serve as the model, or in other words, a way to transfer data between the database and the our webapp.
At this point we're not concerned about how we'll actually retrieve the data from the database into our model classes, that is where MyBatis will come in later on and take care of that for us.
Create a new package com.batch2k7.model in the same way we created com.batch2k7 earlier. Add a class in the newly created package com.batch2k7.model named StudentInfo. Add following lines of code in this class-

package com.batch2k7.model;

public class StudentInfo {

    private int id;
    private String name;
    private String enrollmentNumber;

    public int getId() {
        return id;

    public void setId(int id) { = id;

    public String getName() {
        return name;

    public void setName(String name) { = name;

    public String getEnrollmentNumber() {
        return enrollmentNumber;

    public void setEnrollmentNumber(String enrollmentNumber) {
        this.enrollmentNumber = enrollmentNumber;

Now its time for MyBatis to come and play its role. For that we need to configure its configuration file. To create this right click on the src directory and create a new xml file. name it Configuration.xml and add dollowing lines of code-

<?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE configuration PUBLIC "-// Config 3.0//EN"  

 <properties resource=""/>

  <setting name="useGeneratedKeys" value="true"/>

  <typeAlias alias="Students" type="com.batch2k7.StudentInfoController"/>

 <environments default="development">

  <environment id="development">
   <transactionManager type="JDBC"/>
   <dataSource type="JNDI">
    <property name="initial_context" value="java:comp/env"/>
    <property name="data_source" value="/jdbc/mydb"/>

  <environment id="testing">
   <transactionManager type="JDBC"/>
   <dataSource type="POOLED">
    <property name="driver" value="${db.driver}"/>
    <property name="url" value="${db.url}"/>
    <property name="username" value="${db.user}"/>
    <property name="password" value="${db.pass}"/>


  <mapper resource="com/batch2k7/model/SimpleMappers.xml"/>


We have added to include (located in src directory) file. Add in the properties file -


Typealias will allow us to name com.batch2k7.StudentInfoController to Students. In the end there is a mapper file which will map our POJO to our DB. The mapper file contains all the SQL Query that we will need to communicate with DB.
The mapper file also stores definitions of objects that will be used to retrieve data from the database. By doing this MyBatis abstracts most of the hard work of writing tons of sql statements, and most importantly jdbc code.
Since we've configured this file's location (com/batch2k7/model/SimpleMappers.xml) in the Configuration file above, MyBatis now knows to load this resource whenever it is initialized.
Now add following lines of code in SimpleMappers

<?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE mapper PUBLIC "-// Mapper 3.0//EN" "">

 <mapper namespace="com.batch2k7.model.SimpleMappers">

 <resultMap id="StudentInfoResultMap" type="Students">
     <id property="id" column="STUDENTS_PK" />
     <result property="name" column="NAME" />
     <result property="enrollmentNumber" column="ENROLLMENT_NUMBER" />

 <select id="getName" parameterType="StudentInfo" resultMap="StudentInfoResultMap">
       select * from STUDENTS where ENROLLMENT_NUMBER = (#{enrollmentNumber})

The name of each query indicates the name one should call the query. parameterType indicates what type of parameter you will pass into the sql statement (for simple queries there is only one parameter or none), for queries which require multiple parameters you can use the 'hashmap' parameterType to pass in name value pairs. By defining result maps for each of our objects, MyBatis knows how to automatically map a column from the database tadirectly to the javabean property name (StudentInfo class in our case)
Now we are ready to create DAO class under package com.batch2k7.db Before we go ahead we need to make sure the MyBatis has been initalized and available to the our app. For this we need to add ServletContextListener which will be responsible for allowing us to use SqlSessionan variable. Let us create a new package name com.batch2k7.listener. Also we have to register it into web.xml
Add following in web.xml


Now create a new package name com.batch2k7.listener and add a new class name CustomServletContextListener
Write down folowing lines of code in the newly created class-

package com.batch2k7.listener;

import javax.servlet.ServletContext;  
import javax.servlet.ServletContextEvent;  
import javax.servlet.ServletContextListener;

import org.apache.ibatis.session.SqlSessionFactory;  
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class CustomServletContextListener implements ServletContextListener {

 public void contextInitialized(ServletContextEvent event) {

     ServletContext serContext = event.getServletContext();
     String resource = "Configuration.xml";

     try {
         Reader reader = Resources.getResourceAsReader(resource);
         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); 
         serContext.setAttribute("sqlSessionFactory", sqlSessionFactory);
     } catch(Exception e){
         System.out.println("FATAL ERROR: myBatis could not be initialized");

 public void contextDestroyed(ServletContextEvent event){


You will find some errors this is because MyBatis JARs are not available. Add the downloaded JARs to /WEB-INF/lib directory. Now basic set up is done. Now you just need to add classes to make your project work.
We haven't added any code to DAO class this is due to reason that we want to execute the query to extract the name corresponding to a given Enrollment number, but we don't have any Enrollment number yet. So therefore we will first create interface to get Enrollment Number. This is where Ext JS comes into the play.
Building Interface using Ext JS:
To set up Ext JS Frame work we need to copy following files from the Ext JS directory downloaded earlier.
• ext-3.3.1/resources/css/ext-all • ext-3.3.1/adapter/ext/ext-base.js • ext-3.3.1/ext-all.js and images folder.
So your structure at this stage should look like:

Right click on /WEB-INF directory and create a new folder jsp in it. Add showStudentInfo.jsp in it. (This name should be same as return be controller)
In the interface we are going to make a ComboBox to display all the Enrollment Number which exists in our database. To fetch all the enrollment numbers use the following code in Controller class.

private void handleFormSubmission(HttpServletRequest request, ModelAndView mav) {  
        SqlSessionFactory sf = (SqlSessionFactory)getServletContext().getAttribute("sqlSessionFactory");

        StudentInfoDAO studDao = new StudentInfoDAO(sf);
        ArrayList<StudentInfo> enrollment = studDao.getEnrollmentNumber();
        String[] rollTemp = new String [enrollment.size()];
        for (int i = 0; i < enrollment.size(); ++i) {
            rollTemp[i] = enrollment.get(i).getEnrollmentNumber();
        mav.addObject("rollNumbers", rollTemp);

In the above code getEnrollmentNumber() is the function defined in DAO class and definition is as follows-

package com.batch2k7.db;

import java.util.ArrayList;

import org.apache.ibatis.exceptions.PersistenceException;  
import org.apache.ibatis.session.SqlSession;  
import org.apache.ibatis.session.SqlSessionFactory;

import com.batch2k7.model.StudentInfo;

public class StudentInfoDAO {  
    private SqlSessionFactory sf;

    //constructor will receive a myBatis sessionFactory object
    public StudentInfoDAO (SqlSessionFactory containerSessionFactory) {
        if(containerSessionFactory==null) {
            System.err.println("Error: could not load myBatis sessionFactory");

        sf = containerSessionFactory;

    public ArrayList<StudentInfo> getEnrollmentNumber() throws PersistenceException {
        SqlSession session = sf.openSession();
        try {
            ArrayList<StudentInfo> getRoll = (ArrayList<StudentInfo>)session.selectList("com.batch2k7.model.SimpleMappers.getAllRollNumber");
            if (getRoll == null) {
                throw new PersistenceException();       //TODO: Do Better Error handling
            return getRoll;

        } finally {


DAO class calls getAllRollNumber which is defined in SimpleMappers.xml as follows

<select id="getAllRollNumber" parameterType="StudentInfo" resultMap="StudentInfoResultMap">  
       select * from STUDENTS

Once we have all the Enrollment Numbers we just have to send it to our View(showStudentInfo.jsp) using ModelAndView. We can send it by adding rollTemp to our ModelAndView object.
To retrieve rollTemp in View we use the following code.

  <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  <%@ include file="../../libraries.html" %>
<script type="text/javascript">  
    var dropDownEnrollmentNumber = new Array();
    var i = 0;

    <c:forEach items="${rollNumbers}" var="rollNumbers">
        dropDownEnrollmentNumber[i] = new Array();
        dropDownEnrollmentNumber[i][0] = i.toString();
        dropDownEnrollmentNumber[i][1] = "<c:out value="${rollNumbers}"/>";
      i ++;
    var rollNumbers = new{
          fields    : ['id', 'roll'],
          data            : dropDownEnrollmentNumber      // multi-dimensional array

In jsp file we have added an html file which includes required files for Ext JS framework.
Use this line to add HTML file in jsp sile
<%@ include file="../../libraries.html" %>

In libraries.html (located in /WEB-INF)add following lines of code to include required file

    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <script type="text/javascript" src="js/ext-base.js"></script>
    <link rel="stylesheet" type="text/css" href="css/ext-all.css"/>
    <script type="text/javascript" src="js/ext-all.js"></script>

So now only task is to remain is to send the value selected by user from ComboBox to send it back to server side and send the result back to client side.

For creating comboBox in Ext JS we use the following code:

 var enrollmentCombo = function()
        var rollNumbers = new Ext.form.ComboBox({
          store         : param,
          mode          : 'local',
          forceSelection        : true,
          allowBlank            : false,
          fieldLabel            : 'Enrollment Number',
          name          : 'slope',
          anchor        : '70%',
          displayField          : 'roll',
          valueField            : 'id'

      return rollNumbers;

All these Ext JS widgets are placed inside a Ext JS window using the code:

 var win = new Ext.Window({
      title        : 'RGIIT',
      width        : 500,
      border       : 'false',
      height       : 100,
      id        : 'win',
      name        : 'win',
      bodyStyle    : 'background-color:#fff;padding: 10px',
      autoScroll  : true,
      items: [{
          items: [

      buttonAlign    : 'right', // buttons aligned to the right
      buttons        :[{
              text        : 'save',
              handler             : getName
              text        : 'Cancel'

To do this as soon as user request to retrieve the name we call the handler associated with the save button. The selected Enrollment Number is sent back to server side using AJAX request with the help of following code written in handler.

function getName (btn)  
           url                 : 'showStudentInfo.htm',
           method                  : 'POST',
           params: {
               rollNumber      :    rollNumbers.getValue()
        scope                   : this

To retrieve the selected Enrollment Number at the server side we will do something like this

String enrollmentNumber = request.getParameter("rollNumber");  

Note that parameter in function getParameter is the value sent by AJAX request. Now only task remaining is to fetch value again from DB using MyBatis and send it back to client side. To do this we again call a function in defined in StudentInfoDAO name getName() which will look like

public String getName(String rollNumber) throws PersistenceException {  
        SqlSession session = sf.openSession();
        try {
            ArrayList<StudentInfo> getName = (ArrayList<StudentInfo>)session.selectList("com.batch2k7.model.SimpleMappers.getName");
            if (getName == null) {
                throw new PersistenceException();       //TODO: Do Better Error handling
            return getName.get(0).getName();

        } finally {

We invoke this function like this:

if (rollNumber != null) {  
        SqlSessionFactory sf = (SqlSessionFactory)getServletContext().getAttribute("sqlSessionFactory");

            StudentInfoDAO studDao = new StudentInfoDAO(sf);
            String name = studDao.getName(rollNumber);

Now we can again send name back to client side using the method I describe earlier in this tutorial and display it to user using a MessageBox

When user click on save button, an AJAX request is sent back to server as I described earlier, value is fetched from DB ans sent back to client side. To display it use the code in handler of save button

Go to top.