Tuesday 26 January 2016

Passing a JSON Array Object from AJAX to Spring controller class and retrieving individual values to make dashboard even more intuitive

Now what if I want to change my dashboard according to new values selected in dropdowns in dashboard? Well, to do just just that you can pass your single value or object value to the class using AJAX and JSON and then retrieve the new dashboard values based on selected options. In this example I will show you how to pass JSON Arrays and then parse it in spring controller class to retrieve each value individually.

Project Structure:


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

<?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" version="2.5">
  <servlet>
    <servlet-name>sdnext</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/config/sdnext-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>sdnext</servlet-name>
    <url-pattern>*.html</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
</web-app>

sdnext-servlet.xml
--------------------------------------------------

<?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"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
">


 <context:component-scan base-package="com.login" />
 <mvc:annotation-driven/>
<mvc:resources mapping="/resources/**" location="/resources/img" />
<mvc:resources mapping="/js/**" location="/js" />
<mvc:resources mapping="/css/**" location="/css" />




  <mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
            <property name="prefixJson" value="true"/>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

 <bean id="jspViewResolver"
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="viewClass"
   value="org.springframework.web.servlet.view.JstlView" />
  <property name="prefix" value="/WEB-INF/views/" />
  <property name="suffix" value=".jsp" />
 </bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
  <property name="webBindingInitializer">
    <bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer"/>
  </property>
  <property name="messageConverters">
    <list>
      <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
    </list>
  </property>
</bean>
</beans>

Index.jsp
----------------------------------------------
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
  <form:form method="POST" action="ajaxPage.html">
     <table>
      <tr>
        <td colspan="2"><input type="submit" value="Submit"/></td>
       </tr>
   </table>
  </form:form>
 

</body>
</html>


ajax.js
-------------------------------------------------
var k = 0;


$(document).ready(function(){


     callAjax();
   
     $('#submit').click(function(event) {
         $("#re").empty();
         var arr =  {"ar1": [
{
"firstName": "Khushboo",
"lastName": "Singh"
},
{
"firstName": "Khushi",
"lastName": "Singh"
}
]
};
       
       
    $.ajax({
        type: 'POST',
        //    dataType: 'json',
        contentType:'application/json',
        url: "ajax.html",
        data: JSON.stringify(arr),
        success: function(response) {  
        alert("success");     
            var jsonType = JSON.parse(response);
            alert("jsonType "+ jsonType);
             $.each(jsonType, function(key,value){
         alert("key "+key);
                 for(var i = 0; i < value.length; i++)
                     {
                       $("#re").append("<tr><th>"+key.toUpperCase()+"</th><td>"+value[i]+"</td></tr>");
                     }           
             });
            },
        error: function(xhr, textStatus, errorThrown){
        alert('request failed'+errorThrown);
        }
        });

            });
   
});

function callAjax() {
    $("#re").empty();
     var arr =  {"ar1": [
{
"firstName": "Khushboo",
"lastName": "Singh"
},
{
"firstName": "Khushi",
"lastName": "Singh"
}
]
};
   
   
    $.ajax({
        type: 'POST',
        //    dataType: 'json',
        contentType:'application/json',
        url: "ajax.html",
        data: JSON.stringify(arr),
        success: function(response) {  
            alert("success");   
            var jsonType = JSON.parse(response);
            alert("jsonType "+ jsonType);
             $.each(jsonType, function(key,value){
                  alert("key "+key);
                       for(var i = 0; i < value.length; i++)
                     {
                       $("#re").append("<tr><th>"+key.toUpperCase()+"</th><td>"+value[i]+"</td></tr>");
                     }           
             });
            },
        error: function(xhr, textStatus, errorThrown){
        alert('request failed'+errorThrown);
        }
        });


     }   

LoginController.java
----------------------------------------------------

package com.login.controller;

import java.io.IOException;

import java.util.ArrayList;

import javassist.bytecode.Descriptor.Iterator;


import org.apache.catalina.User;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import antlr.collections.List;

import com.google.gson.Gson;
import com.google.gson.JsonParser;
import com.login.bean.testArrayListInAjax;


@Controller
public class LoginController {

 testArrayListInAjax obj1 = null;

 @RequestMapping(value = "/ajaxPage")
 public ModelAndView forwordLogin() {
 
  return new ModelAndView("ajax");
 }

 @RequestMapping(value = "/ajax")
 public @ResponseBody
 String ShowUserDetails(@RequestBody String arr1) {
     Gson gson = new Gson();
/*Note: Now i slice out the String arr1 to the format needed to convert String to JSONArray.*/
    int first = arr1.indexOf("[");       
    int last = arr1.lastIndexOf("]")+1;
    String l = arr1.substring(first, last);   
    ArrayList FirstNames = new ArrayList();
    ArrayList LastNames = new ArrayList();
     try {
         JSONArray jsonarray = new JSONArray(l);
         System.out.println("jsonarr "+jsonarray);
            for(int i=0; i < jsonarray.length(); i++) {
                JSONObject jsonobject = jsonarray.getJSONObject(i);
                String firstName       = jsonobject.getString("firstName");
                String lastName    = jsonobject.getString("lastName");
               FirstNames.add(firstName);
               LastNames.add(lastName);
               //Do whatever manipulation now you want to do with each individual value.     
             
                }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        System.out.println("catch");
        e.printStackTrace();
    }
    
     obj1 = new testArrayListInAjax();
      obj1.setAr1(FirstNames);
      return gson.toJson(obj1);
 }

 @RequestMapping(value = "/index", method = RequestMethod.GET)
 public ModelAndView welcome() {

  return new ModelAndView("index");
 }


}

testArrayListInAjax
-----------------------------------------

package com.login.bean;

import java.util.ArrayList;

public class testArrayListInAjax
{

    ArrayList ar1 = new ArrayList();

    public ArrayList<String> getAr1()
    {
        return ar1;
    }

    public void setAr1()
    {
        ar1.add("ArrayValue1");
        ar1.add("ArrayValue2");
       
    }   
   
    public void setAr1(ArrayList a)
    {
       
        ar1.add(a.get(0));
        ar1.add(a.get(1));
       
    }   
   
}

ajax.jsp
----------------------------------
  <?xml version="1.0" encoding="ISO-8859-1" ?>
 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<script type="text/javascript" src="./js/jquery.js"></script>
<script type="text/javascript" src="./js/ajax.js"></script>



</head>

<body>

 <table>
      <tr>
       <td colspan="2"> 
 <select id="param1">
  <option value="Khushboo">Khushboo</option>
  <option value="Singh">Khushi</option>

</select>
</td>
 <td colspan="2">
 <select id="param2">
  <option value="singh">Singh</option>
  <option value="Singh">Singh</option>
</select>
</td>
 <td colspan="2">
 <button type="button" id = "submit">submit</button>
</td>
</tr>
</table>




<table id="re" name="re" border="2" cellspacing="4" cellpadding="4">

</table>


</body>
</html>

Index screen
------------------------------


Now in my scenario I have explained how to pass a JSON array and then individually retrieve the values but i have not really changed the values based on parameters. But you can do that using this very code but instead of passing a static array you can pass the parameters individually. Using this code you can dynmaically change table values using AJAX and JSON. This is just the brief cut out on what i will be implementing in my dashboard in order to make it even more intuitive.


Thursday 21 January 2016

Making Morris graph from bootstrap dashboard theme dynamic in spring application using AJAX and JSON

In my personal home project, I am using bootstrap dashboard theme after login:

http://startbootstrap.com/template-overviews/sb-admin-2/ 

 After login I was able to pass a single data from controller class to dashboard page, however it was a huge learning for me to be able to integrate morris charts with multiple arrays passed in an object from controller class.

So, in this blog I will show you how to pass an array object containing multiple arrays to the dashboard page in above link in order for the "Morris.Area" graph to display data according to the arrays in passed objects using AJAX and JSON. Go through my previous blog to see how to pass simple array from controller class to another JSP page using AJAX.

If you download the bootstrap theme from the given link, i have modified pages/index.html to views/dashboard.jsp in my example as my project structure is different. So you will have to configure paths accordingly.

arrayBean.java
---------------------------
package com.c.bean;

import java.util.ArrayList;

public class arrayBean
{


    ArrayList<String> period = new ArrayList<String>();
    ArrayList<Integer> iphone = new ArrayList<Integer>();
    ArrayList<Integer> ipad = new ArrayList<Integer>();
    ArrayList<Integer> itouch  = new ArrayList<Integer>();
    public ArrayList<String> getPeriod() {
        return period;
    }
    public void setPeriod() {
        period.add("2010 Q1");
        period.add("2010 Q2");
        period.add("2010 Q3");
        period.add("2010 Q4");
        period.add("2011 Q1");
        period.add("2011 Q2");
        period.add("2011 Q3");
        period.add("2011 Q4");
        period.add("2012 Q1");
        period.add("2012 Q2");
    }
    public ArrayList<Integer> getIphone() {
        return iphone;
    }
    public void setIphone() {
   
        iphone.add(2666);
        iphone.add(2778);
        iphone.add(4912);
        iphone.add(3767);
        iphone.add(6810);
        iphone.add(5670);
        iphone.add(4820);
        iphone.add(15073);
        iphone.add(10687);
        iphone.add(8432);
        }
    public ArrayList<Integer> getIpad() {
        return ipad;
    }
    public void setIpad() {
        ipad.add(0);
        ipad.add(2294);
        ipad.add(1969);
        ipad.add(3597);
        ipad.add(1914);
        ipad.add(4293);
        ipad.add(3795);
        ipad.add(5967);
        ipad.add(4460);
        ipad.add(5713);
    }
    public ArrayList<Integer> getItouch() {
        return itouch;
    }
    public void setItouch() {
        itouch.add(2647);
        itouch.add(2441);
        itouch.add(2501);
        itouch.add(5689);
        itouch.add(2293);
        itouch.add(1881);
        itouch.add(1588);
        itouch.add(5175);
        itouch.add(2028);
        itouch.add(1791);
    }

}

controller class - ControllerClass.java
--------------------------------------------------------

// This is the url linked to submit button on Index page


 @RequestMapping(value = "/save", method = RequestMethod.POST)
 public ModelAndView saveUser( @ModelAttribute("loginBean1") RegisterBean loginBean) {

//some code 
  return new ModelAndView("dashboard");
 }

 @RequestMapping(value = "/dashboard")
 public @ResponseBody
 String ShowUserDetails() {
Gson gson = new Gson();
arrayBean o1 = new arrayBean();
o1.setPeriod();
o1.setIpad();
o1.setIphone();
o1.setItouch();

return gson.toJson(o1);
 }

dashboard.js
------------------------------------

$(document).ready(function(){
 callAjax();

});

function callAjax() {

$.ajax({
       url : 'dashboard.html',       
       success : function(response) {
           var v = 0;
           var period1 = null;
           var iphone1 = null;
           var ipad1 = null;
           var itouch1 = null;
           var jsonType = JSON.parse(response);
           $.each(jsonType, function(key,value)
                   {
               if (v == 0)
                   {
                 
                    period1 = value;
                   v++;
           
                   }
               else if(v == 1)
                   {
                    iphone1 = value;
                   v++;
           
                   }
               else if(v == 2)
               {
                ipad1 = value;
               v++;
           
               }
               else if(v == 3)
               {
                itouch1 = value;
               v++;
       
               }
                   }
           
                 );         

    var data = [];
           for (var i = 0; i < 10; i++) {
             
              var x = {
                   period: period1[i],
                   iphone: iphone1[i],
                   ipad: ipad1[i],
                   itouch: itouch1[i]
               };
              data.push(x);
      
               }
          
       
          
           Morris.Area({
                element: 'morris-area-chart',
                data: data,
                xkey: 'period',
                ykeys: ['iphone', 'ipad', 'itouch'],
                labels: ['iPhone', 'iPad', 'iPod Touch'],
                pointSize: 2,
                hideHover: 'auto',
                resize: true
           });
    
       }
   });
}

From the standard page - pages/Index.jsp - I have removed external script call "<script src="./js/morris-data.js"></script> ", as, I have already manipulated the graph in dashboard.js and so calling this page would override the purpose of displaying a dynamic morris graph on dashboard.

Now the graph looks pretty much the same, with only difference that now the graph is dynamic.



Tuesday 19 January 2016

A 3rd Party Logistics brief flow (3PL) flow


Passing ArrayList from Spring controller class to AJAX

Initially I tried to pass ArrayList using GSON to AJAX but I could not do so. Then I bound the ArrayList in an object and then passed it to AJAX and then segregated the value to get each value individually.

Project Structure


web.xml
-------------------------------
<?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" version="2.5">
  <servlet>
    <servlet-name>sdnext</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/config/sdnext-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>sdnext</servlet-name>
    <url-pattern>*.html</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
</web-app>

sdnext-servlet.xml
--------------------------------------------------------------------

<?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"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
">


 <context:component-scan base-package="com.login" />
 <mvc:annotation-driven/>
<mvc:resources mapping="/resources/**" location="/resources/img" />
<mvc:resources mapping="/js/**" location="/js" />
<mvc:resources mapping="/css/**" location="/css" />




  <mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
            <property name="prefixJson" value="true"/>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

 <bean id="jspViewResolver"
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="viewClass"
   value="org.springframework.web.servlet.view.JstlView" />
  <property name="prefix" value="/WEB-INF/views/" />
  <property name="suffix" value=".jsp" />
 </bean>



<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
  <property name="webBindingInitializer">
    <bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer"/>
  </property>
  <property name="messageConverters">
    <list>
      <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
    </list>
  </property>
</bean>
</beans>

index.jsp
-----------------------------------------------

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
  <form:form method="POST" action="ajaxPage.html">
     <table>
      <tr>
        <td colspan="2"><input type="submit" value="Submit"/></td>
       </tr>
   </table>
  </form:form>
 

</body>
</html>

LoginController.java
-----------------------------------------------------------------

package com.login.controller;

import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;
import com.login.bean.testArrayListInAjax;


@Controller
public class LoginController {

 testArrayListInAjax obj1 = null;

 @RequestMapping(value = "/ajaxPage")
 public ModelAndView forwordLogin() {
 
  return new ModelAndView("ajax");
 }

 @RequestMapping(value = "/ajax")
 public @ResponseBody
 String ShowUserDetails() {
  Gson gson = new Gson();
  ArrayList<String> t1 = new ArrayList<String>();
obj1 = new testArrayListInAjax();
 obj1.setAr1();
t1 = obj1.getAr1();
 
  return gson.toJson(obj1);
 }

 @RequestMapping(value = "/index", method = RequestMethod.GET)
 public ModelAndView welcome() {

  return new ModelAndView("index");
 }
}


testArrayListInAjax.java
---------------------------------------------

package com.login.bean;

import java.util.ArrayList;

public class testArrayListInAjax
{

    ArrayList<String> ar1 = new ArrayList<String>();

    public ArrayList<String> getAr1()
    {
        return ar1;
    }

    public void setAr1()
    {
        ar1.add("ArrayValue1");
        ar1.add("ArrayValue2");
        this.ar1 = ar1;
    }   
   
   
}


ajax.js
------------------------------

$(document).ready(function(){
 callAjax();

});

function callAjax() {

$("#re").empty();
$.ajax({
       url : 'ajax.html',
       success : function(response) {
       
       var jsonType = JSON.parse(response);
        $.each(jsonType, function(key,value){
   
            alert("value 1" +value[0]);
            alert("value 2" +value[1]);
           
            for(var i = 0; i < value.length; i++)
                {
                  $("#re").append("<tr><th>"+key.toUpperCase()+"</th><td>"+value[i]+"</td></tr>");
                }           
        });
       }
   });
}

ajax.jsp
---------------------------------------

  <?xml version="1.0" encoding="ISO-8859-1" ?>
 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<script type="text/javascript" src="./js/jquery.js"></script>
<script type="text/javascript" src="./js/ajax.js"></script>


</head>
<body>
<table id="re" border="2" cellspacing="4" cellpadding="4">

</table>


</body>
</html>


Now, run the application:
------------------------------------------------------










Wednesday 13 January 2016

Bootstrap integration with Spring + Hibernate app

In this blog i will demonstrate a simple spring + hibernate app registration integration with bootstrap template.

I have downloaded and used template 2 from this link providing bootstrap template:

http://azmind.com/2015/11/06/bootstrap-login-register-forms-templates/


Project Structure:


NOTE: I have added downloaded assets file from the above link in WebContent folder. Also I have copied index.jsp (located at WebContent > views > index.jsp) from downloaded index.html from the above link.

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

<?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" version="2.5">
  <servlet>
    <servlet-name>sdnext</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/config/sdnext-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>sdnext</servlet-name>
    <url-pattern>*.html</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
</web-app>

sdnext-servlet.xml
------------------------------------
<?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"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
">
<context:property-placeholder location="classpath:resources/database.properties" />
 <context:component-scan base-package="com.c" />


 <tx:annotation-driven transaction-manager="hibernateTransactionManager"/>
 <mvc:annotation-driven />
<mvc:resources mapping="assets/**" location="/assets" />

 <bean id="jspViewResolver"
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="viewClass"
   value="org.springframework.web.servlet.view.JstlView" />
  <property name="prefix" value="/WEB-INF/views/" />
  <property name="suffix" value=".jsp" />
 </bean>

 <bean id="dataSource"
  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="${database.driver}" />
  <property name="url" value="${database.url}" />
  <property name="username" value="${database.user}" />
  <property name="password" value="${database.password}" />
 </bean>

 <bean id="sessionFactory"
  class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="annotatedClasses">
   <list>
    <value>com.c.model.Register</value>
   </list>
  </property>
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">${hibernate.dialect}</prop>
    <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
    <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>    
   </props>
  </property>
  
 </bean>

 <bean id="hibernateTransactionManager"
  class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory" />
 </bean>
</beans>

index.jsp (This file was taken as it is from index.html from the downloaded folder from the above mentioned template link. I just converted the form to JSP and changed form tags to make it a JSP file so that it can interact with controller class.)
-----------------------------------------------------------------------------------------------------------------------

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html lang="en">

    <head>

      <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Bootstrap Login &amp; Register Templates</title>

        <!-- CSS -->
        <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:400,100,300,500">
        <link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
        <link rel="stylesheet" href="assets/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="assets/css/form-elements.css">
        <link rel="stylesheet" href="assets/css/style.css">

        <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
        <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
        <!--[if lt IE 9]>
            <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
            <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
        <![endif]-->

        <!-- Favicon and touch icons -->
        <link rel="shortcut icon" href="assets/ico/favicon.png">
        <link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
        <link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
        <link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
        <link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">

    </head>

    <body>

        <!-- Top content -->
        <div class="top-content">
       
            <div class="inner-bg">
                <div class="container">
               
                    <div class="row">
                        <div class="col-sm-8 col-sm-offset-2 text">
                            <h1><strong>Elopade</strong></h1>
                            <div class="description">
                            <p>
                           <strong> Your DREAMS, Our AMBITION </strong> 
                           
                            </p>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-sm-5">
                       
                        <div class="form-box">
                        <div class="form-top">
                        <div class="form-top-left">
                        <h3>Login to our site</h3>
                            <p>Enter username and password to log on:</p>
                        </div>
                        <div class="form-top-right">
                        <i class="fa fa-key"></i>
                        </div>
                           </div>
                           <div class="form-bottom">
<form:form method="POST" action="login.html" commandName="loginBean" class="login-form">
<!-- Replace "commandName" with "modelAttribute" and it works just same-->
<%--       <div class="form-group">
           <td><form:label path="id" class="sr-only" for="form-username"> User ID </form:label> </td>
           <td><form:input path="id" type="text" value=""  name="form-username" placeholder="Username..." class="form-username form-control" id="form-username"/> </td>
      </div>
       <div class="form-group">
           <td><form:label class="sr-only" for="form-password" path="password">User Password:</form:label></td>
           <td><form:input path="password" type="password" name="form-password" placeholder="Password..." value="" class="form-password form-control" id="form-password"/></td>
      </div> --%>
<button type="submit" class="btn">Sign in!</button>
  
  </form:form>
                   </div>
                   </div>
               
                <div class="social-login">
                        <h3>...or login with:</h3>
                        <div class="social-login-buttons">
                        <a class="btn btn-link-1 btn-link-1-facebook" href="#">
                        <i class="fa fa-facebook"></i> Facebook
                        </a>
                        <a class="btn btn-link-1 btn-link-1-twitter" href="#">
                        <i class="fa fa-twitter"></i> Twitter
                        </a>
                        <a class="btn btn-link-1 btn-link-1-google-plus" href="#">
                        <i class="fa fa-google-plus"></i> Google Plus
                        </a>
                        </div>
                       </div>
                       
                        </div>
                        
                        <div class="col-sm-1 middle-border"></div>
                        <div class="col-sm-1"></div>
                       
                        <div class="col-sm-5">
                       
                        <div class="form-box">
                        <div class="form-top">
                        <div class="form-top-left">
                        <h3>Sign up now</h3>
                            <p>Fill in the form below to get instant access:</p>
                        </div>
                        <div class="form-top-right">
                        <i class="fa fa-pencil"></i>
                        </div>
                           </div>
                           <div class="form-bottom">
                           <form:form role="form" method="POST" class="registration-form" action="save.html" commandName="loginBean">
      <div class="form-group">
           <form:label path="first_name" class="sr-only" for="form-first-name"> First name </form:label>
           <form:input path="first_name" type="text" value=""  name="form-first-name" placeholder="First name..." class="form-first-name form-control" id="form-first-name"/> 
      </div>
       <div class="form-group">
          <form:label path="last_name" class="sr-only" for="form-last-name">Last name</form:label>
          <form:input path="last_name" type="text" name="form-last-name" placeholder="Last name..." class="form-last-name form-control" id="form-last-name"/>
      </div>

  <div class="form-group">
<form:label path="email_id" class="sr-only" for="form-email">Email</form:label>
 <form:input path="email_id" name="form-email" placeholder="Email..." class="form-email form-control" id="form-email" />
        </div>
<div class="form-group">
<form:label path="about_yourself" class="sr-only" for="form-about-yourself">About yourself</form:label>
<form:textarea path="about_yourself"  name="form-about-yourself" placeholder="About yourself..." class="form-about-yourself form-control" id="form-about-yourself" />
</div>

                       <button type="submit" class="btn">Sign me up!</button>
                </form:form>
                   </div>
                        </div>
                       
                        </div>
                    </div>
                    
                </div>
            </div>
            
        </div>

        <!-- Footer -->
        <footer>
        <div class="container">
        <div class="row">
       
        <div class="col-sm-8 col-sm-offset-2">
        <div class="footer-border"></div>
        <p>Made by Anli Zaimi at <a href="http://azmind.com" target="_blank"><strong>AZMIND</strong></a> 
        having a lot of fun. <i class="fa fa-smile-o"></i></p>
        </div>
       
        </div>
        </div>
        </footer>

        <!-- Javascript -->
        <script src="assets/js/jquery-1.11.1.min.js"></script>
        <script src="assets/bootstrap/js/bootstrap.min.js"></script>
        <script src="assets/js/jquery.backstretch.min.js"></script>
        <script src="assets/js/scripts.js"></script>
        
        <!--[if lt IE 10]>
            <script src="assets/js/placeholder.js"></script>
        <![endif]-->

    </body>

</html>

ControllerClass.java
----------------------------------

package com.c.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.c.bean.RegisterBean;
import com.c.model.Register;
import com.c.service.RegisterService;


@Controller
public class ControllerClass {

 @Autowired
 private RegisterService registerService;

 @RequestMapping(value = "/save", method = RequestMethod.POST)
 public ModelAndView saveUser( @ModelAttribute("loginBean1") RegisterBean loginBean) {
  Register login = prepareModel(loginBean);
  registerService.addUser(login);  
  return new ModelAndView("redirect:/index.html");
 }

 @RequestMapping(value = "/login", method = RequestMethod.POST)
 public ModelAndView loginUser( @ModelAttribute("loginBean1") RegisterBean loginBean) {

  return new ModelAndView("redirect:/index.html");
 }

 @RequestMapping(value = "/index", method = RequestMethod.GET)
 public ModelAndView welcome(@ModelAttribute("loginBean")  RegisterBean loginBean) {

  return new ModelAndView("index");
 }



 private Register prepareModel(RegisterBean loginBean){
  Register login = new Register();

 login.setEmail_id(loginBean.getEmail_id());
 login.setFirst_name(loginBean.getFirst_name());
 login.setLast_name(loginBean.getLast_name());
 login.setAbout_yourself(loginBean.getAbout_yourself());
 return login;
 }

}

RegisterBean.java
----------------------------------

package com.c.bean;

public class RegisterBean 
 private String email_id;
 private String first_name;
 private String last_name;
 private String about_yourself;
public String getEmail_id() {
return email_id;
}
public void setEmail_id(String email_id) {
this.email_id = email_id;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getAbout_yourself() {
return about_yourself;
}
public void setAbout_yourself(String about_yourself) {
this.about_yourself = about_yourself;


}

Register.java
------------------------------

package com.c.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;


@Entity
@Table(name="m_users")
public class Register implements Serializable{

 private static final long serialVersionUID = -723583058586873479L;

 @Id
/* @GeneratedValue(strategy=GenerationType.AUTO)*/
 @Column(name = "email_id")
 private String email_id;

 @Column(name="first_name")
 private String first_name;

 @Column(name="last_name")
 private String last_name;

 @Column(name="about_yourself")
 private String about_yourself;

public String getEmail_id() {
return email_id;
}

public void setEmail_id(String email_id) {
this.email_id = email_id;
}

public String getFirst_name() {
return first_name;
}

public void setFirst_name(String first_name) {
this.first_name = first_name;
}

public String getLast_name() {
return last_name;
}

public void setLast_name(String last_name) {
this.last_name = last_name;
}

public String getAbout_yourself() {
return about_yourself;
}

public void setAbout_yourself(String about_yourself) {
this.about_yourself = about_yourself;
}

public static long getSerialversionuid() {
return serialVersionUID;
}



}

RegisterService.java
-----------------------------------------

package com.c.service;

import java.util.List;

import com.c.model.Register;


public interface RegisterService {

 public void addUser(Register user);

}


RegisterServiceImpl.java
---------------------------------------------

package com.c.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.c.dao.RegisterDao;
import com.c.model.Register;

@Service("registerService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class RegisterServiceImpl implements RegisterService {

 @Autowired
 private RegisterDao registerDao;
 
 @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
 public void addUser(Register user) {
registerDao.addUser(user);
 }
 
}

RegisterDao.java
------------------------------------

package com.c.dao;

import java.util.List;

import com.c.model.Register;

public interface RegisterDao {
 
 public void addUser(Register user);

}

RegisterDaoImpl.java
-------------------------------------------------------

package com.c.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.c.model.Register;


@Repository("registerDao")
public class RegisterDaoImpl implements RegisterDao {

 @Autowired
 private SessionFactory sessionFactory;
 
 public void addUser(Register user) {
  sessionFactory.getCurrentSession().save(user);
 }
 

}


database.properties
-------------------------------------------

database.driver=org.postgresql.Driver
database.url=jdbc:postgresql://localhost:5432/elopade
database.user=postgres
database.password=01988
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update


Now run the app:

http://localhost:8080/springWIthBootstrapIntegration/
-----------------------------------------------------------------------------------------



Data in database after clicking on "Sign me up!"
------------------------------------------------------------------