Monday 17 February 2014

Spring +Apache Velocity +AJAX

 Spring  + Velocity Integration with ajax

Hello Friends ,hope you all are doing well.today i am going to demonstrate how apache velocity is integrated with Spring framework.first of all you have to download apache velocity from this link: http://velocity.apache.org/download.cgi 

Apache velocity is view template that defines view template language which will be used to referance java objects. 

another thing that you need to add is velocity UI from :http://veloedit.sourceforge.net/
in order to enable velocity syntax in eclipse.all you need to do is install new software and paste the link that i have mentioned above.

in order to render view of velocity ,you need to have following confugration :

      <!-- velocity configuration-->
     
    <bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
      <property name="resourceLoaderPath" value="/WEB-INF/vm/"/>
    </bean>
    
    <!--   velocity view resolver    -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
      <property name="cache" value="true"/>
      <property name="prefix" value=""/>
      <property name="suffix" value=".vm"/>
    </bean>


in order to render .vm page you need to add above configuration into context file.
 Project structure will look like as given below:


the detail code is as given below:
Model class:
package org.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "student")
public class Student
{

    @Id
    @Column(name = "studentid")
    private String id;
    @Column
    private String name;
    public Student() {
    }
    public Student(String id, String name) {
        this.id = id;
        this.name = name;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

}
Controller:
package org.controller;

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

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

import org.dao.StudentDAO;
import org.model.Student;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;
import net.sf.json.JSONArray;
@Controller
public class StudentController {

    private static List<Student> userList = new ArrayList<Student>();

    static {
        userList.add(new Student("Cust101", "Nisarg"));
        userList.add(new Student("Cust102", "Kinjal"));
        userList.add(new Student("Cust103", "Mayur"));
        userList.add(new Student("Cust104", "Parth"));
        userList.add(new Student("Cust105", "Ankit"));
    }

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(@ModelAttribute("model") ModelMap model) {

        model.addAttribute("userList", userList);

        return "index";
    }

    @RequestMapping(value = "/testing", method = RequestMethod.POST)
    public @ResponseBody void testing(@ModelAttribute("user") Student user,
            HttpServletRequest request, HttpServletResponse response) {

         WebApplicationContext context = WebApplicationContextUtils
                .getWebApplicationContext(request.getServletContext());

        StudentDAO studentdao = context.getBean("StudentDAO", StudentDAO.class);

        Student user1 = new Student();
        String id=request.getParameter("id");
        String name=request.getParameter("name");
       
         user1.setId(id);
         user1.setName(name);
         studentdao.save(user1);
          userList.add(user1);
          Map<String, List<Student>> model = new HashMap<String, List<Student>>();
          model.put("users", userList);

            JSONArray jsonarray = JSONArray.fromObject(userList);
           response.getWriter().println(jsonarray);
    }
}
  
DAO:
package org.dao;
import org.model.Student;
import org.springframework.orm.hibernate3.HibernateTemplate;

public class StudentDAO
{   
    private HibernateTemplate template;   
    public HibernateTemplate getTemplate() {
        return template;
    }
   public void setTemplate(HibernateTemplate template)
    {
        this.template = template;
    }
    public StudentDAO(HibernateTemplate template)
    {      
        this.template=template;  
    }
    public void save(Student student)
    {
        template.save(student);
    }
   
}
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"
        id="WebApp_ID" version="2.5">
    
  <display-name>Freemarker_SpringMVC_example</display-name> 
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
 
   <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
    <listener>
        <listener-class>
            org.springframework.web.context.request.RequestContextListener
        </listener-class>
    </listener>
 
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/context-config.xml</param-value>
    </context-param>
 
  <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
</web-app>

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

     <context:component-scan
        base-package="org.controller" />  

      <!-- velocity configuration-->     
    <bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
      <property name="resourceLoaderPath" value="/WEB-INF/vm/"/>
    </bean>    
    <!--   velocity view resolver    -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
      <property name="cache" value="true"/>
      <property name="prefix" value=""/>
      <property name="suffix" value=".vm"/>
    </bean>       
</beans>

context-config.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.1.xsd">
   
<context:component-scan base-package="org.controller"></context:component-scan>

<!-- Hibernate Configuration -->
 <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" >
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/demo" />
        <property name="username" value="root" />
        <property name="password" value="admin!@#"/>
</bean>

<bean id="mySessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="myDataSource" />

        <property name="annotatedClasses">
            <list> <value>org.model.Student</value></list>                                
</property>

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">none</prop>
            </props>
        </property>
    </bean>
   
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
        <constructor-arg ref="mySessionFactory" />
    </bean>

<!-- list of bean definations  -->
<bean id="StudentDAO"  class="org.dao.StudentDAO">
   <constructor-arg ref="hibernateTemplate" />
</bean>

</beans>

index.vm
<!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>Spring-Velocity Integration</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>


<script>

$(document).ready(function()
         {
           
             $('#submitdata').click(function()
            {
                 
                 $.ajax({
                        url: "testing.html",
                        dataType:'json',
                        method:'post',
                        data:{id: $('#id').val(),name:$('#name').val()},
                       
                        success: function(data)
                        {
                            $('#here_table').append(  '<table border="2">' );
                            $('#here_table').append(  '<th>ID </th>  <th>NAME </th>' );
                           
                            $.each(data, function(index, item)
                            {
                                 $('#here_table').append( '<tr><td>'  +  item.id + '</td>' + '<td>'  +  item.name + '</td></tr>' );
                               
                               
                            });
                            $('#here_table').append(  '</table>' );
                        }  
                    });          
             });
         });
</script>
</head>
<body>
  <form name="user"  method="post">
    Id: <input type="text" name="id"  id="id" /> <br/>
    Name: <input type="text" name="name" id="name" />   <br/>
    <input id="submitdata" type="button" value="Save" />
         
  </form>
<div id="here_table">
  </div>    
      
</body>
</html>
Output will look like as given below:
(1) empty form

(2) form with data ,it also show list of students into table


(3) record insertion into table


hope you will get my point
thanks for reading 
Happy Learning ...!!!!!!


No comments:

Post a Comment

Spring Boot SSL configuration -Tomcat Server

Hi Friends hope you all are doing well. Today I am going to demonstrate about how to configure SSL in Spring boot web Application. Need o...