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


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






Sunday 9 February 2014

Reverse Engineering Using Hibernate

Reverse Engineering Using Hibernate


                                         Hello Friends.today i am going to demonstrate how you can reverse engineer process of creating entities in eclipse using hibernate tools(originally JBoss tools).well you need to go through hibernate site to know about hibernate.revnge.xml ,well its not all about code .so i am putting snapshot of steps that you need to follow as per given below:


1)open hibernate perspective from from window->perspective & from then select hiebernate


(2)here i am demostrating example of sample database.
      in Hibernate Perspective, right click and select “Add Configuration…
In “Edit Configuration” dialog box,
  1. In “Project” box, click on the “Browse..” button to select your project.
  2. In “Database Connection” box, click “New..” button to create your database settings.
  3. In “Configuration File” box, click “Setup” button to create a new or use existing “Hibernate configuration file”, hibernate.cfg.xml



(3) List of tables is shown :


(4) Now, you are ready to generate the Hibernate mapping files and annotation codes.
 go to run->Hibernate Code Generation ,select Hibernate Code Generation Configuration

Create a new configuration, select your “console configuration”, puts your “Output directory” and checked option “Reverse engineer from JDBC Connection“.

In “Exporter” tab, select what you want to generate, Model , mapping file (hbm) , DAO, annotation code and etc.


(5) you can see using single reverse engineer file ,hibernate tools provide you easy way to get entity classes generated automatically.it reduces amount of work required to write entity classes by own.

 hibernate.reveng.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd" >

<hibernate-reverse-engineering>
<!-- sample is the name of database and student is the entity within sample database-->
  <table-filter match-catalog="sample" match-name="student"/>
 
</hibernate-reverse-engineering>

hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory name="MySessionFactory">
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">admin!@#</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/sample</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    </session-factory>
</hibernate-configuration>

the project structure will look like given below:



this is how you can apply reverse engineering process to get entity classes generated by hibernate itself


thanks for reading
for any query ping me on pathak.nisarg@yahoo.com

Regards












Monday 3 February 2014

Spring mvc with jqgrid simplified

Spring mvc with jqgrid simplified
Hello Friends.hope you all are fine.today i am going to demonstrate jqgrid functionality of jquery & how can we intract with database using spring mvc .jqgrid represents data in tabular  format.i am using json data for forwarding request & response to the client..
 
well i have included  jquery.jqGrid.min.js,jquery.min.js,jquery-ui.custom.js java script files into the classpath.
i am posting my code as given below :


Entity Class:
package org.demo.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
    private int studentid;

    @Column
    private String name;
    @Column
    private String college;
   
    public Student() { }
   
    public Student(int id, String name,String college)
    {
        this.studentid=id;
        this.name=name;
        this.college=college;
    }

    public int getStudentid() {
        return studentid;
    }

    public void setStudentid(int studentid) {
        this.studentid = studentid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCollege() {
        return college;
    }

    public void setCollege(String college) {
        this.college = college;
    }

}
Controller :

package org.demo.controller;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.demo.dao.StudentDAO;
import org.demo.model.Student;
import org.springframework.stereotype.Controller;
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.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.orb.Utills.JsonMapper;

@Controller
public class StudentController {

    @RequestMapping(value = "/Data", method = RequestMethod.GET)
    public @ResponseBody
    void getStudent(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        // to get applicationcontext associated with ioc container -use to get
        // specific beans

        WebApplicationContext context = WebApplicationContextUtils
                .getWebApplicationContext(request.getServletContext());
        StudentDAO dao = (StudentDAO) context.getBean("StudentDAO");

        List<Student> list = dao.saveAllStudents();
        Map<String, Object> personMap = new LinkedHashMap<String, Object>();
        List<Map<String, Object>> personList = new ArrayList<Map<String, Object>>();
        Map<String, Object> personSubMap = null;
        List<String> cell = null;
        int i = 0;
        for (Student p : list) {
            i++;
            personSubMap = new LinkedHashMap<String, Object>();
            personSubMap.put("id", p.getStudentid());
            cell = new ArrayList<String>();
            cell.add(p.getStudentid() + "");
            cell.add(p.getName());
            cell.add(p.getCollege());

            personSubMap.put("cell", cell);
            personList.add(personSubMap);
        }
        personMap.put("rows", personList);
        personMap.put("records", i);
        JsonMapper json = (JsonMapper) context.getBean("JsonMapper");

        json.WritecInJson(response, personMap);

        /* return personMap; */
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public @ResponseBody
    void edit(HttpServletRequest request, HttpServletResponse res) {
        WebApplicationContext context = WebApplicationContextUtils
                .getWebApplicationContext(request.getServletContext());

        System.out.println("inside");

        int id = Integer.parseInt(request.getParameter("id"));
        String name = request.getParameter("name");
        String college = request.getParameter("college");
        String operation = request.getParameter("oper");

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

        Student s = new Student(id, name, college);
        if (operation.equals("add")) {
            dao.insert(s);
            System.out.println(name);

            Map<String, Student> studentMap = new HashMap<String, Student>();
            studentMap.put("data", new Student(id, name, college));

            JsonMapper json = (JsonMapper) context.getBean("JsonMapper");

            json.WritecInJson(res, studentMap);

        }
        if (operation.equals("edit")) {
            System.out.println(name);

            dao.edit(id, name, college);

            Map<String, Student> studentMap = new HashMap<String, Student>();
            studentMap.put("data", new Student(id, name, college));

            JsonMapper json = (JsonMapper) context.getBean("JsonMapper");

            json.WritecInJson(res, studentMap);
        }
        if (operation.equals("del")) {
           dao.delete(id);
        }
   }
}
DAO:
package org.demo.dao;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.demo.model.Student;
import org.hibernate.Query;
import org.springframework.orm.hibernate3.HibernateTemplate;

public class StudentDAO
{
    private    HibernateTemplate template;
   
    public StudentDAO(HibernateTemplate template) throws Exception
    {
        this.template=template;
    }
   
public List<Student> saveAllStudents() throws Exception
{
    List<org.demo.model.Student> StudentList=template.find("FROM Student");
   
    return StudentList;
/*    System.out.println("Done");*/
}

public void insert(Student s)
{
    template.save(s);
}

public void edit(int id,String name,String college)
{
        
      Query query =template.getSessionFactory().openSession().createSQLQuery("update Student set name=? ,college=?  where studentid=? ");
      query.setString(0,name);
      query.setString(1,college);
     
      query.setInteger(2,id);
      
      int success=query.executeUpdate();
      System.out.println("updated SUCCESSFULLY!!!" +success);
   
}

public void delete(int id)
{       
        Query query =template.getSessionFactory().openSession().createSQLQuery("delete from  Student where studentid=? ");
                   
          query.setInteger(0,id);
          
          int success=query.executeUpdate();
          System.out.println("Deleted SUCCESSFULLY!!!");   
   
}
}
Mapper class: user defined json coverter 
package com.orb.Utills;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.http.server.ServletServerHttpResponse;

public class JsonMapper {

    public void WritecInJson(HttpServletResponse res, Object object) {
        MappingJacksonHttpMessageConverter jsonConverter = new MappingJacksonHttpMessageConverter();
        MediaType jsonMimeType = MediaType.APPLICATION_JSON;

        if (jsonConverter.canWrite(object.getClass(), jsonMimeType)) {
            try {
                jsonConverter.write(object, jsonMimeType,
                        new ServletServerHttpResponse(res));

            } catch (IOException e) {
                e.printStackTrace();
            } catch (HttpMessageNotWritableException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("reached in else");
        }

    }
}
JqgridDemo.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="script/jquery.min.js"></script>
<script type="text/javascript" src="script/jquery.jqGrid.min.js"></script>
<script type="text/javascript" src="script/jquery-ui.custom.min.js"></script>



<link type="text/css" rel="stylesheet" href="css/style.css" />

<link type="text/css" rel="stylesheet" href="css/jquery-ui-1.10.0.custom.css"/>

<link type="text/css" rel="stylesheet" href="css/ui.jqgrid.css" />

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>JQGrid Demo</title>

<script type="text/javascript">

jQuery().ready(function (){
   

    /*
    $("#dialog").dialog({
        autoOpen : false,
        width : 650,
        resizable:false,
        modal : true,
        close : function(ev, ui) {
           
            alert("closed");
        }
    });
   
    $("#btn").click(function(){
       
       
        $("#dialog").dialog('open');
       
    }); */
   
   
    jQuery("#list1").jqGrid({
        url:'Data.html',
        editurl:'edit.html',
                datatype: "json",
                colNames:['ID','NAME','COLLEGE'],
                colModel:[
                         
                           {name:'id',index:'id', width:80,align:"right",editable:true,editoptions:{rows:"2",cols:"20"}},
                           {name:'name',index:'name', width:80,align:"right",editable:true,editoptions:{rows:"2",cols:"20"}},
                           {name:'college',index:'college', width:150, sortable:false,editable:true, editoptions:{rows:"2",cols:"20"}} ],
                           rowNum:10,
                           autowidth: true,
                           rowList:[10,20,30],
                           pager: jQuery('#pager1'),
                           sortname: 'id',
                           viewrecords: true,
                           sortorder: "desc",
                           caption:"CRUD" }).navGrid('#pager1',{ 'cellEdit': true,add : true,edit :true,save :true,addtext: 'Add',edittext:'edit',searchtext:'Search',deletetext:'delete',savetext:'Save',canceltext: 'Cancel',editable:true},{});
       
   


});

 $.jgrid.edit = {
        addCaption: "Add Student",
        editCaption: "Edit Student",
     
        bSubmit: "Submit",
        bCancel: "Cancel",
        bClose: "Close",
        bYes : "Yes",
        bNo : "No",
        bExit : "Cancel",
        closeAfterAdd:true,
        closeAfterEdit:true,
        reloadAfterSubmit:true,
       
        errorTextFormat: function (response) {
            if (response.status != 200) {
                return "Error encountered while processing. Please check the accuracy of data entered.";
            }
        },
      
        afterSubmit : function(response,postdata) {
                            return(true,"ok");
                            }
    };

 $("#dedata").click(function(){ var gr = jQuery("#delgrid").jqGrid('getGridParam','selrow'); if( gr != null ) jQuery("#list").jqGrid('delGridRow',gr,{reloadAfterSubmit:false}); else alert("Please Select Row to delete!"); });

$.jgrid.del = {
        caption: "Delete Student",
        msg: "Delete selected student?",
        bSubmit: "Delete",
        bCancel: "Cancel",
        reloadAfterSubmit:true,
        closeOnEscape:true,
        onclickSubmit : function(eparams) {
                                var rowData = $("#list").jqGrid('getRowData', 1);
                                var retarr = {'id':rowData['id']};
                                return retarr;
                                }  
    };
 jQuery("#list1").jqGrid('editRow',1,
        {
            keys : true,
            oneditfunc: function() {
                alert ("edited");
            }
        }); 
jQuery("#list1").jqGrid('navGrid', '#pager1', {edit : false,add : false,del : false,search : false});
jQuery("#list1").jqGrid('inlineNav',"#pager1",{add : true,edit :false,save :true,addtext: 'Add',savetext:'Save',canceltext: 'Cancel'});
    </script>
</head>
<body>
<div id="dialog">
<table id="list1"></table> <div id="pager1"></div>
</div>
<button id="btn" value="show"></button>

</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>TestJquery</display-name>
  <welcome-file-list>
       <welcome-file>jqgridDemo.jsp</welcome-file>
  </welcome-file-list>
 
  <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
   
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/context-conf.xml</param-value>
    </context-param>
 
  <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
</web-app>

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


<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <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" value="org.demo.model.Student">
            <!-- <props>
                <prop key="classes" >org.demo.model.Student</prop>
            </props>
            <list>
                <value>org.demo.model.Student</value>
            </list> -->
        </property>

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">false</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>
    <bean id="JsonMapper" class="com.orb.Utills.JsonMapper"></bean>
 
    <bean id="StudentDAO" class="org.demo.dao.StudentDAO">
        <constructor-arg ref="hibernateTemplate" />
    </bean>
  
</beans>

the output will look like as given below :






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


Wednesday 29 January 2014

Hibernate JSF integration

Hibernate JSF integration

                         Hello Friends,today i am going to demonstrate you how hibernate orm framework can be integrated with JavaServerFaces.well for sake of simplicity i am not using annotation based configuration.i am pasting my code as given below.i am going to use traditional Student class for demonstrating the concept :

ManagedBean

package org.managedbean;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import org.dao.StudentDAO;


@ManagedBean(name="student")
@SessionScoped
public class StudentBean
{

        private int id;
        private String name;
        private String college;
        @ManagedProperty(value="#{studentDAO}")
        private StudentDAO dao;
       
       
        public StudentDAO getDao() {
            return dao;
        }
        public void setDao(StudentDAO dao) {
            this.dao = dao;
        }
        public StudentBean() {
            // TODO Auto-generated constructor stub
           
        }
        public StudentBean(int id,String name,String college)
        {
            this.id=id;
            this.name=name;
            this.college=college;
           
        }
       
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getCollege() {
            return college;
        }
        public void setCollege(String college) {
            this.college = college;
        }
       
        public void insert()
        {
            getDao().insert(this);

        }
       
}
 

DAO LAYER:
package org.managedbean;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import org.dao.StudentDAO;

@ManagedBean(name="student")
@SessionScoped
public class StudentBean
{

        private int id;
        private String name;
        private String college;
        @ManagedProperty(value="#{studentDAO}")
        private StudentDAO dao;
      
      
        public StudentDAO getDao() {
            return dao;
        }
        public void setDao(StudentDAO dao) {
            this.dao = dao;
        }
        public StudentBean() {
            // TODO Auto-generated constructor stub
          
        }
        public StudentBean(int id,String name,String college)
        {
            this.id=id;
            this.name=name;
            this.college=college;
          
        }
      
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getCollege() {
            return college;
        }
        public void setCollege(String college) {
            this.college = college;
        }
      
        public void insert()
        {
            getDao().insert(this);

        }
     
}

Util class:( for creating session factory)
package org.util;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

@ManagedBean
@SessionScoped
public class HibernateUtil
{
   
    private static final SessionFactory sessionfactory=buildSessionFactory();

    public static SessionFactory buildSessionFactory()
    {   
       
        try {
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    public static SessionFactory getSessionfactory() {
        return sessionfactory;
       
    }
  }
hibernate.cfg.xml-Configuration file
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  
    <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/sample</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">admin!@#</property>
    <property name="hibernate.current_session_context_class">org.hibernate.context.ThreadLocalSessionContext</property>
    <mapping resource="Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>

Student.cfg.xml -mapping file
 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
     <class name="org.managedbean.StudentBean" table="student" catalog="sample">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <property name="name" type="string">
            <column name="name" length="45" not-null="true" />
        </property>
        <property name="college" type="string">
            <column name="college" length="45" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

data.xhtml
 <?xml version="1.0" encoding="UTF-8"?>
<!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"
      xmlns:f="http://java.sun.com/jsf/core"     
      xmlns:h="http://java.sun.com/jsf/html">

    <h:head>
        <title>Hibernate + JSF CRUD</title>
    </h:head>
    <h:body>
       
        <h:form>
        <table>
        <tr>
        <td><h:outputLabel value="id"> </h:outputLabel>
       
        <h:inputText id="id" value="#{student.id}"></h:inputText></td>
        </tr>
       
        <tr>
        <td><h:outputLabel value="name"> </h:outputLabel>
       
        <h:inputText id="name" value="#{student.name}"></h:inputText></td>
        </tr>
       
        <tr>
        <td><h:outputLabel value="college"> </h:outputLabel>
       
        <h:inputText id="college" value="#{student.college}"></h:inputText></td>
        </tr>
       
        </table>
           <h:commandButton value="Insert"   action="#{student.insert}"></h:commandButton>
        </h:form>
    </h:body>
</html>

index.jsp
<jsp:forward page="data.xhtml"></jsp:forward>



here is the entry in the mysql:


i hope you will get my point.for any query related to this topic ping me on pathak.nisarg@yahoo.com
thanks for reading  this post,in the next post i am going to demonstrate  how we can reverse engineer on hibernate ORM.
Regards



Monday 20 January 2014

Spring MVC+ Ajax + Itext PDF

Spring MVC+ Ajax + Itext PDF
 
Hello Friends.hope you all are doing well.today i am going to demonstrate you how to display pdf using spring mvc and itext library.well i am taking my traditional Student class to demonstrate the concept.i am making ajax call to the controller from where view will be returned &  pdf will be displayed on browser.

you need to have itext library along with spring jars into your classpath.

Model Class:-  Student.java
package org.demo.model;

public class Student
{
private String id;

private String name;
private String college;

public Student() {}
public Student(String id,String name,String college)
{
    this.id=id;
    this.name=name;
    this.college=college;
   
}

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

public String getCollege() {
    return college;
}

public void setCollege(String college) {
    this.college = college;
}
 
}

Controller :StudentController.java

package org.demo.controller;

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

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

import org.demo.model.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.servlet.ModelAndView;

@Controller
public class StudentController
{

        @RequestMapping(value="/test",method=RequestMethod.POST)
        public ModelAndView processAjax(HttpServletRequest request,HttpServletResponse response)
        {
           
           
           
            String id=request.getParameter("id");
            String username=request.getParameter("name");
            String college=request.getParameter("college");
           
            System.out.println("ID:"+id);
           
            Student s=new Student(id,username,college);
            List<Student> studList =new ArrayList<Student>();
           
            studList.add(s);
           
           
            return new ModelAndView("PdfView","listStudent",studList);
           
        }
}

User Defined View Resolver class: PdfViewHandler.java


package org.demo.view;

import java.util.List;
import java.util.Map;

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

import org.demo.model.Student;
import org.springframework.web.servlet.view.document.AbstractPdfView;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Font;
import com.itextpdf.text.Font.FontFamily;
import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Rectangle;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.PdfWriter;

public class PdfViewHandler extends AbstractPdfView
{

    @Override
    protected void buildPdfDocument(Map<String, Object> model, Document document,
            PdfWriter arg2, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        List<Student> listStudent=(List<Student>)model.get("listStudent");
       
        //adding Response header inorder to change default name of .pdf file
        response.addHeader("content-disposition","inline;filename=StudentReport.pdf");
       
       
        Table table=new Table(3);
        table.addCell("Id");       
        table.addCell("Name");
        table.addCell("College");
       
        for(Student  s: listStudent)
        {
            table.addCell(s.getId()+"");
            table.addCell(s.getName());
            table.addCell(s.getCollege());
        }
       
        document.add(table);
       
    }

}
index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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">

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<title>Sample pdf code</title>

 <script type="text/javascript">

$(document).ready(function(){
   
    $('#btn1').click(function() {
       
        $.ajax({
            url: "${pageContext.request.contextPath}/test.html",
            dataType:'json',
            method:'post',
            data:{id:$('#txtid').val(),name:$('#txtname').val(),college:$('#txtcollege').val()}
            });
       
    });
   
});




</script>


</head>
<body>
<form id="f1" method="post">
<table>
    <tr>
        <td>ID:<input type="text" id="txtid" name="txtid"> </td>
    </tr>
    <tr>
        <td>Name:<input type="text" id="txtname" name="txtname"> </td>
    </tr>
    <tr>
        <td>College:<input type="text"  id="txtcollege" name="txtcollege"></td>
    </tr>
     <tr>
        <td><input type="button"  id="btn1" value="submit"> </td>
    </tr>
   
</table>
</form>
</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>SpringwithPdf</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
 
 <servlet>
     <servlet-name>dispatcherservlet</servlet-name>
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 </servlet>

 <servlet-mapping>
    
     <servlet-name>dispatcherservlet</servlet-name>
     <url-pattern>*.html</url-pattern>
 </servlet-mapping>
</web-app>

view.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.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
   
    <bean id="PdfView" class="org.demo.view.PdfViewHandler"></bean>
   
    </beans>
dispatcherservlet-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.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
   
   <context:annotation-config></context:annotation-config>
  
  
   <context:component-scan base-package="org.demo.controller"></context:component-scan>
  
   <bean class="org.springframework.web.servlet.view.XmlViewResolver">
       <property name="order" value="1"></property>
       <property name="location">
          <value>/WEB-INF/view.xml</value>
       </property>
    </bean>  
  
   </beans>

the output will look like given below:
1) Ajax Call 



2)dowload dialog box opened & ask to download pdf ,pdf gets opened


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


Saturday 18 January 2014

AbstractExcelView Using Spring MVC


 AbstractExcelView Using Spring MVC

Hello Friends Hope you all are fine.today i am going to demonstrate how we can work with Excel using Spring mvc.i am using AbstractExcelView using which we can add/display excel data. i am putting sample code here:

Model :
package org.demo.model;

public class Student
{
    private int id;
    private String name;
    private String college;
   
   
    public Student() { }
   
      public Student(int id,String name,String college)
      {
          this.id=id;
          this.name=name;
          this.college=college;
      }
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCollege() {
        return college;
    }

    public void setCollege(String college) {
        this.college = college;
    }
}



Controller Class:


package org.demo.controller;

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

import org.demo.model.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class MainController
{
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String viewHome()
    {
        return "home";
    }
   
    @RequestMapping(value = "/downloadExcel", method = RequestMethod.GET)
    public ModelAndView downloadExcel()
    {
        // create some sample data
        List<Student> listStudents= new ArrayList<Student>();
        listStudents.add(new Student(1,"Nisarg","Semcom"));
        listStudents.add(new Student(2,"Raj","GLS"));
        listStudents.add(new Student(3,"Kinjal","Semcom"));
      

        // return a view which will be resolved by an excel view resolver
        return new ModelAndView("excelView", "listStudents", listStudents);
    }

}

ExcelBuilder.java which prepares view to be resolved


package org.demo.view;

import java.util.List;
import java.util.Map;

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

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.demo.model.Student;
import org.springframework.web.servlet.view.document.AbstractExcelView;

public class ExcelBuilder extends AbstractExcelView
{

    @Override
    protected void buildExcelDocument(Map<String, Object> model,HSSFWorkbook workbook, HttpServletRequest arg2, HttpServletResponse arg3)
            throws Exception
    {
    List<Student> listStudents=(List<Student>) model.get("listStudents");
       
        HSSFSheet sheet=workbook.createSheet("listStudents");
        sheet.setDefaultColumnWidth(30);
       
        HSSFRow header=sheet.createRow(0);
        header.createCell(0).setCellValue("id");
        header.createCell(1).setCellValue("Name");
        header.createCell(2).setCellValue("College");

        int r=1;
       
        for(Student s: listStudents)
        {
            HSSFRow arow=sheet.createRow(r++);
           
            arow.createCell(0).setCellValue(s.getId());
            arow.createCell(1).setCellValue(s.getName());
            arow.createCell(2).setCellValue(s.getCollege());
           
        }
       
    }

}


home.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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>
<h3><a href="/downloadExcel">Download Excel Document</a></h3>
</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_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SpringExcelView</display-name>

 
  <servlet>
      <servlet-name>dispatcherservlet</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
 
  <servlet-mapping>
      <servlet-name>dispatcherservlet</servlet-name>
      <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

 
View.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    
    <bean id="excelView" class="org.demo.view.ExcelBuilder" />
    
</beans>

dispatcherservlet-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"
    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.demo.controller" />

   <bean id="viewResolver1" class="org.springframework.web.servlet.view.XmlViewResolver">
        <property name="order" value="1"/>
        <property name="location" value="/WEB-INF/views.xml"/>
    </bean>
    
    <bean id="viewResolver2"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="order" value="2"/>
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
    </bean>

    
</beans>

the output will look like as given below:








Thanks for Reading this article.
for any query ping me on pathak.nisarg@yahoo.com
Regards




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