Tuesday 11 February 2014

Spring FreeMarker Integration

Spring FreeMarker Integration 
hello Friends today i am going to demonstrate Spring +Freemarker integration.there are many view technology available in the market. you can also use Velocity, you need to have jboss tools into eclipse.you can get jboss tools by querying eclipse marketplace..ftl is the extension of freemarker file.you need to have freemarker.jar into the classpath.
the detail code is posted below:

Project Structure 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 :-StudentController.java

package org.controller;

import java.util.ArrayList;
import java.util.List;

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;

@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 = "/add", method = RequestMethod.POST)
    public String add(@ModelAttribute("user") Student user,
            HttpServletRequest request, HttpServletResponse response) {

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

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

        Student student = new Student();
        student.setId(user.getId());
        student.setName(user.getName());

        studentdao.save(student);

        if (null != user && null != user.getId() && null != user.getName()
                && !user.getId().isEmpty()) {

            synchronized (userList) {
                userList.add(user);
                // userList.add(student);
            }

        }

        return "redirect:index.html";
    }

}
DAO: -StudentDAO.java

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);
    }  
}

index.ftl

<html>
<head>
<title>Spring freemarker integration </title>
<body>   
 
  <form name="user" action="add.html" method="post">
    Id: <input type="text" name="id" /> <br/>
    Name: <input type="text" name="name" />   <br/>
    <input type="submit" value="Save" />
  </form>
 
  <br/>
  <table>
    <tr>
        <th>ID</th>  <th>NAME</th>
    </tr>
    <#list model["userList"] as student>
    <tr>
        <td>${student.id}</td> <td>${student.name}</td>
    </tr>
    </#list>
  </table>

</body>
</html>

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>

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>

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">  

    <!-- freemarker configuration-->
    <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
      <property name="templateLoaderPath" value="/WEB-INF/ftl/"/>
    </bean>
    
    <!--   Freemarker view resolver    -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
      <property name="cache" value="true"/>
      <property name="prefix" value=""/>
      <property name="suffix" value=".ftl"/>
    </bean>

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

snapshot of output is as given below:
(1) table popluated with some static data

(2) Record inserted into table as well as database

 
 (3) Entry of record  into the database:


 


hope you will get my point
Thanks for reading.
for any query ping me on pathak.nisarg@yahoo.com
Regards






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...