Thursday, June 20, 2013

ExtJs 4 with Spring MVC: Fetching and displaying JSON data in grid panel

ExtJs 4 with Spring MVC: Fetching and displaying JSON data in grid Ext JS is a JavaScript framework for client side MVC. Its modern UI widgets help to render native desktop application like user interface. It can be integrated with any server side technology such as PHP, JSP or ASP to develop enterprise application. There are many tutorials that talk about Ext Js integration with PHP but not many bloggers have talked about integration of Ext Js with spring framework which can be used for implementing server side MVC. In this tutorial I’ll show how to create a grid panelwith json data. For this tutorial I have used eclipse IDE and Tomcat 6 as server.

 Prerequisite: 
  • Maven
  • Spring
  • Some background knowledge of how ExtJs works. 
As you might be expecting start with creating a new Dynamic web project in Eclipse. Convert it to Maven project and add following dependencies for including spring to your pom.xml

         <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-core</artifactId>  
                <version>${spring.version}</version>  
           </dependency>  
           <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-web</artifactId>  
                <version>${spring.version}</version>  
           </dependency>  
           <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-webmvc</artifactId>  
                <version>${spring.version}</version>  
           </dependency>  

Now edit your web.xml file to configure your servlet. Here is the content of my web.xml file

 <web-app id="WebApp_ID" version="2.4"  
      xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
      xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   
      http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
      <display-name>Spring with Extjs MVC Application</display-name>  
      <servlet>  
           <servlet-name>mvc-dispatcher</servlet-name>  
           <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
           <load-on-startup>1</load-on-startup>  
      </servlet>  
      <servlet-mapping>  
           <servlet-name>mvc-dispatcher</servlet-name>  
           <url-pattern>/</url-pattern>  
      </servlet-mapping>  
      <context-param>  
           <param-name>contextConfigLocation</param-name>  
           <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>  
      </context-param>  
      <listener>  
           <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
      </listener>  
 </web-app>  

In mvc-dispatcher-servlet.xml define your view resolver, base package for controller class and also create a mapping for all static resources {required to include JavaScript & CSS files for Ext JS}

 <context:component-scan base-package="com.abhas.controller" />  
      <bean  
           class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
           <property name="prefix">  
                <value>/WEB-INF/pages/</value>  
           </property>  
           <property name="suffix">  
                <value>.jsp</value>  
           </property>  
      </bean>  
      <mvc:resources mapping="/extjs/**" location="/WEB-INF/pages/extjs/" />  
      <mvc:annotation-driven/>  

Now create a controller class in the base package declared above. Include the mapping for your main page and json file as follows:

      @RequestMapping("/user_grid")  
      public String userGrid() {  
           return "user_grid";  
      }  
      @RequestMapping("/user.json")  
      public ModelAndView showUserJson() {  
 //          Here you can also write code to fetch data from a database and add it  
 //          As a model object to view in form of json string, the view can then   
 //          display the data. But for convenience I have hard-coded the json data  
 //          in my pages/showJson.jsp file which I am returning here as a view  
           return new ModelAndView("showJson");  
      }  

Now write the file that will act as view to display the data (pages/user_grid.jsp)

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
   pageEncoding="ISO-8859-1"%>  
 <!DOCTYPE html>  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <link rel="stylesheet" type="text/css" href="extjs/resources/css/ext-all.css" />  
 <script type="text/javascript" src="extjs/ext-all.js"></script>  
 <script type="text/javascript" src="extjs/ext-all-debug.js"></script>  
 <script>  
 Ext.define('User', {  
   extend: 'Ext.data.Model',  
   fields: [{  
     name: 'id',  
     type: 'int'  
   }, {  
     name: 'name',  
     type: 'string'  
   }, {  
     name: 'email',  
     type: 'string'  
   }]  
 });  
 Ext.onReady(function() {  
   var user = Ext.create('Ext.data.Store', {  
     storeId: 'user',  
     model: 'User',  
     autoLoad: 'true',  
     proxy: {  
       type: 'ajax',  
       url: 'user.json',  
       reader: {  
         type: 'json',  
         root: 'blah'  
       }  
     }  
   });  
   Ext.create('Ext.grid.Panel', {  
     store: user,  
     id: 'user',  
     title: 'Users',  
     columns: [{  
       header: 'ID',  
       dataIndex: 'id'  
     }, {  
       header: 'NAME',  
       dataIndex: 'name'  
     }, {  
       header: 'Email',  
       dataIndex: 'email'  
     }],  
     height: 300,  
     width: 300,  
     renderTo: Ext.getBody()  
   });  
 });  
 </script>  
 <title>User</title>  
 </head>  
 <body>  
 </body>  
 </html>  

You also need to define a file called (pages/showJson.jsp) This file is model for our client ExtJs and a view for our Spring framework:

 { "blah":   
   [{  
     "id": 1,  
     "name": "Abhas",  
     "email": "a@spcapitaliq.com"  
   },  
   {  
     "id": 2,  
     "name": "Keshav",  
     "email": "k@spcapitaliq.com"  
   }]  
 }  

That’s it.. If you have followed all steps correctly you’ll get following result on running the project on server.

Ext js spring mvc grid panel
Hope you enjoyed reading this tutorial. Special thanks to Munawar sir (my mentor at internship) & Keshav Sharma (Man who can delete errors from your java code) for inspiring me to write this.