AngularJS ng-grid Spring MVC example

AngularJS ng-grid Spring MVC example

Many component are available to show large data set in table or grid some component are below:

  • AngularUI Boostrap : Compatible with AngularJS
  • Bootstrap CSS 3
  • ng-grid Compatible with AngularJS

The ng-grid very suitable to show large data set in scrollable grid and if you have got thousands of data entries you can go for ng-grid pagination. In this demo we will see how to use ng-grid with AngularJS to show data’s in scrollable grid using Spring MVC framework. We will create sample page with select drop down box and based on user selection call will go to the server and render response back to ng-grid. Please see steps below:

  • Create maven project name: SpringMVCAngularJSService
  • Final project structure:

AngularJS ng-grid Spring MVC example

  • pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.javahonk</groupId>
  <artifactId>SpringMVCAngularJSService</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringMVCAngularJSService Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <properties>
		<junit.version>3.8.1</junit.version>
		<SpringVersion>4.0.6.RELEASE</SpringVersion>
		<spring-jdbc.version>4.0.6.RELEASE</spring-jdbc.version>
		<json.version>20140107</json.version>
		<jackson.version>1.9.10</jackson.version>
		<log4j.version>1.2.16</log4j.version>
		<jtds.version>1.2</jtds.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>
		<!-- Spring dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${SpringVersion}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${SpringVersion}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${SpringVersion}</version>
		</dependency>
		<!-- Spring and Transactions -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring-jdbc.version}</version>
		</dependency>

		<!-- Jackson JSON Mapper -->
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>${jackson.version}</version>
		</dependency>
		<dependency>
			<groupId>org.json</groupId>
			<artifactId>json</artifactId>
			<version>${json.version}</version>
		</dependency>
		<dependency>
			<groupId>net.sourceforge.jtds</groupId>
			<artifactId>jtds</artifactId>
			<version>${jtds.version}</version>
		</dependency>
		<!-- MySql 5.5 Connector -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.29</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>${log4j.version}</version>
		</dependency>

	</dependencies>
  <build>
    <finalName>SpringMVCAngularJSService</finalName>
    <plugins>
		<plugin>
			<artifactId>maven-compiler-plugin</artifactId>
			<configuration>
				<source>1.6</source>
				<target>1.6</target>
			</configuration>
			<version>3.1</version>
		</plugin>
	</plugins>
  </build>
</project>
  • web.xml:
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	version="2.5">
	<display-name>Archetype Created Web Application</display-name>

	<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>/</url-pattern>
	</servlet-mapping>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
	</context-param>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>

</web-app>
  • dispatcher-servlet.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" 
	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.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">

	<context:component-scan base-package="com.javahonk.controller" />
	<mvc:resources mapping="/static/**" location="/static/" />
    <mvc:annotation-driven/>
	
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix">
			<value>/WEB-INF/jsp/</value>
		</property>
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>  
	
	<!-- bind messages.properties -->
	<bean class="org.springframework.context.support.ResourceBundleMessageSource" id="messageSource">
		<property name="basename" value="messages" />
	</bean> 	

</beans>
  • angularJSngGrid.jsp:
<!DOCTYPE html>
<html data-ng-app="myApp">

<head lang="en">
  <meta charset="utf-8">
  <title>Active Basket</title>
  <link rel="stylesheet" type="text/css" href="http://angular-ui.github.com/ng-grid/css/ng-grid.css" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
  <script type="text/javascript" src="http://angular-ui.github.com/ng-grid/lib/ng-grid.debug.js"></script>
  <link rel="stylesheet" type="text/css" href="static/AngularJSService/css/style.css" />
  <script type="text/javascript">

    var app = angular.module('myApp', ['ngGrid']);
    
    app.controller('MyController', function($scope, $http) {

		$scope.populateGridData = function() {
			var myactivevalue = angular.element( document.querySelector('#activeTeam') ).val();	    	
			$http({method: 'GET', url: 'getActiveTeamData/'+myactivevalue}).
		    success(function(dataBasket, status, headers, config) {
		    	$scope.myData = dataBasket;	        	        	
		    }).
		    error(function(data, status, headers, config) {
		    	// called asynchronously if an error occurs show here	
		    });
		};
		
		$scope.filterOptions = {filterText: ''};
		$scope.gridOptions = { data: 'myData',showGroupPanel: true,filterOptions: $scope.filterOptions,showColumnMenu:true, showFilter:true,
	  		    selectedItems: $scope.mySelections,
	  		    multiSelect: false,
	  		    rowHeight: 22
	  	};
		
		 
		$scope.getDropDownDataFromServer = function() {
		
			$http({method: 'GET', url: 'getDropDownData'}).
			      success(function(data, status, headers, config) {
			      	$scope.activeTeam = data;	        	
			      }).
			      error(function(data, status, headers, config) {
			        // called asynchronously if an error occurs show here		          
			      });
			  
			  };
		   
	  });
  	
  </script>
</head>

<body data-ng-controller="MyController" style="overflow: auto;">

	<div class='tab'>
	
		<div  data-ng-init="getDropDownDataFromServer()" class="activeTeamsDropdownStyle">
		    <b>Active Team:</b>
		    <select id="activeTeam" data-ng-model="selectedTeam" data-ng-change="populateGridData();" style="font-size: 11px">
				<option value="">-- Select Active Team --</option>
				<option data-ng-repeat="(key, value) in activeTeam" value="{{key}}">{{value}}</option>
			</select><br>
			<p><b>Filter Columns: </b><input type="text" data-ng-model="filterOptions.filterText" /></p>				
		</div>	

		<div class="filler"></div>
		<div class="gridModelStyle" data-ng-grid="gridOptions"></div>	
	
	</div>
	
</body>

</html>
  • SpringMVCController.java:
package com.javahonk.controller;

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

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
public class SpringMVCController {
	
	private static final Logger logger = Logger.getLogger(SpringMVCController.class);
	
	@RequestMapping(value = "/angularServiceCall")
	public String angularServiceCall() {
		
		logger.info("Log4j info is working");
        logger.warn("Log4j warn is working");       
        logger.debug("Log4j debug is working");
        logger.error("Log4j error is working");
        System.out.println("System out is working");
		return "angularJSngGrid";		
	}
	
	@RequestMapping(value = "/getDropDownData")
	public @ResponseBody Map<String, String> getDropDownData() {		

		Map<String, String> dropDownData = new HashMap<String, String>();
		dropDownData.put("Prime_Option", "Prime Option");
		dropDownData.put("Prime_Equity", "Prime Equity");
		dropDownData.put("Prime_Optimus", "Prime Optimus");		
		
		return dropDownData;	
	}
	
	@RequestMapping(value = "/getActiveTeamData/{name}")
	public @ResponseBody List<Map<String, Object>> getActiveTeamData(@PathVariable String name) {		

		List<Map<String, Object>> activeTeamMap = new ArrayList<Map<String,Object>>();
		for (int i = 0; i < 4; i++) {
			Map<String, Object> dropDownData = new HashMap<String, Object>();
			dropDownData.put("Name", "Java Honk");
			dropDownData.put("Positon", "Architect");
			dropDownData.put("Salary", "$000,800");
			dropDownData.put("Office", "NY");
			dropDownData.put("Start_Date", "05/05/2010");
			activeTeamMap.add(dropDownData);
			
			dropDownData = new HashMap<String, Object>();
			dropDownData.put("Name", "Igor Vornovitsky");
			dropDownData.put("Positon", "Sr. Architect");
			dropDownData.put("Salary", "$400,800");
			dropDownData.put("Office", "NY");
			dropDownData.put("Start_Date", "05/05/2011");
			activeTeamMap.add(dropDownData);
			
			dropDownData = new HashMap<String, Object>();
			dropDownData.put("Name", "Ramesh Arrepu");
			dropDownData.put("Positon", "Architect");
			dropDownData.put("Salary", "$300,400");
			dropDownData.put("Office", "NY");
			dropDownData.put("Start_Date", "05/05/2009");
			activeTeamMap.add(dropDownData);
		}
		
		return activeTeamMap;	
	}
	

}
  • Lets run this application now (We are using tomcat server with eclipse to run this if you are not sure how to configure and run tomcat with eclipse please follow this tutorial). To run: Right click project –> Run As –> Run on Server where you will see below page:

AngularJS ng-grid Spring MVC example

  • For this demo: form the drop down box select active team “Prime Equity” (You could choose any value). You will see below sample data populated in ng-grid:

AngularJS ng-grid Spring MVC example

ng-grid provide so many in-build functionality some of them have been implemented shown below: 

  • Filter column and show remove column:

AngularJS ng-grid Spring MVC example

  • Drag drop column and sorting:

AngularJS ng-grid Spring MVC example

  • That’s it. If you want to try more functionality of ng-grid please download project in bottom download link and read ng-grid tutorial here 

download Download Project: SpringMVCAngularJSnggrid

6 thoughts on “AngularJS ng-grid Spring MVC example”
    1. Thanks Vaquar appreciate your feedback. This tutorial is compatible with that version and may not work properly with latest version. We would like to keep version as it is. We will write another tutorial using new version of both AngularJS and JQuery.

  1. Thanks for the sample.
    I tried this to run this example — the grid is not being populated with data. I am using java 8 and tomact 9.x
    Miya.

  2. Thanks,but i am facing an issue under pom.xml and on building the project below error appears:

    Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.5 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-resources-plugin:jar:2.5
    Plugin org.apache.maven.plugins:maven-resources-plugin:2.5 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-resources-plugin:jar:2.5

Leave a Reply

Your email address will not be published. Required fields are marked *