Spring MVC AngularJS RESTFul Service example

Spring MVC AngularJS RESTFul Service example

In this demo we will develop Spring MVC AngularJS RESTFul Service complete application where we will use Spring MVC as RESTFul service and on the client side AngularJS as consumer of the service which will make “HTTP” call to service and process the response data received from the service.

Summary logic of this tutorial:

  • service.js making http call to service:
var serviceModule = angular.module('sampleService',[]);

	serviceModule.service('sampleService', function($http) {
		
		this.getUserData = function(){
			return $http.get("http://localhost:8080/SpringMVCAngularJSService/getSampleJSONData/JavaHonk");	        
		};	
		
	});
  • serviceController.js making call to the service and store data in the scope:
var serviceModule = angular.module('serviceModule', ['sampleService']);
	
	serviceModule.controller('myServiceController', function($scope, sampleService) {
	    
	    $scope.getJSONDataFromServer = function() {
	    	
	    	 sampleService.getUserData().success(function(data, status, headers, config) {
	         	$scope.data = data;	        	
	         }).error(function(data, status, headers, config) {
	 	          alert("Error Ocurred:"+status);
	 	     });
	    };
	
	});

 

Let’s see detail example step by step 

  • Create project name: SpringMVCAngularJSService
  • Final project structure:

Spring MVC AngularJS RESTFul Service 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>
  • log4j.xml to write log data on console and file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC
  "-//APACHE//DTD LOG4J 1.2//EN" "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.out" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %c{1} - %m%n" />
        </layout>
    </appender>
    
    <appender name="fileAppend" class="org.apache.log4j.RollingFileAppender">
        <param name="Threshold" value="debug" />
        <param name="File" value="C:/Javahonk/Log4jXML.log" />
        <param name="maxFileSize" value="1MB" />
        <param name="maxBackupIndex" value="5" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d %-5p  [%c{1}] %m %n" />
        </layout>
    </appender>

    <root>
        <priority value="debug" />
        <appender-ref ref="console" />
        <appender-ref ref="fileAppend" />
    </root>

</log4j:configuration>
  • messages_en.properties as resource bundle use as static data holder for the application:
label.name= RESTFul Service example</br>
  • AngularJSService.jsp
<!DOCTYPE html>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html data-ng-app="serviceModule">
<head>
<meta charset="ISO-8859-1">
<title>Spring MVC AngularJS RESTFul Service example</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="static/AngularJSService/serviceController.js"></script>
<script src="static/AngularJSService/service.js"></script>
</head>
<body data-ng-controller="myServiceController"> 
	
	<h3>${message} <spring:message code="label.name" /></h3>
	<p><button data-ng-click="getJSONDataFromServer()">Get JSON data from server</button></p>
	<p style="font-weight: bold;">Raw data received form server:</p>
	<p>{{data}}</p>
	<p style="font-weight: bold;">Iterate and align data received form server:</p>
	<div data-ng-repeat="dataDetails in data">Key: {{dataDetails.key}} Values: {{dataDetails.values}}</div>	

</body>
</html>
  • serviceController.js:
var serviceModule = angular.module('serviceModule', ['sampleService']);
	
	serviceModule.controller('myServiceController', function($scope, sampleService) {
	    
	    $scope.getJSONDataFromServer = function() {
	    	
	    	 sampleService.getUserData().success(function(data, status, headers, config) {
	         	$scope.data = data;	        	
	         }).error(function(data, status, headers, config) {
	 	          alert("Error Ocurred:"+status);
	 	     });
	    };
	
	});
  • service.js:
var serviceModule = angular.module('sampleService',[]);

	serviceModule.service('sampleService', function($http) {
		
		this.getUserData = function(){
			return $http.get("http://localhost:8080/SpringMVCAngularJSService/getSampleJSONData/JavaHonk");	        
		};	
		
	});
  • SpringMVCController.java:
package com.javahonk.controller;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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 = "/firstPage")
	public String firstPage(ModelMap model) {
		
		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");
		model.addAttribute("message", "Spring MVC AngularJS RESTFul Service");
		
		return "index";		
	}
	
	@RequestMapping(value = "/angularServiceCall")
	public String angularServiceCall(ModelMap model) {
		
		model.addAttribute("message", "Spring MVC AngularJS");		
		return "AngularJSService";		
	}

	@RequestMapping(value = "/getSampleJSONData/{name}")
	public @ResponseBody String getSampleJSONData(@PathVariable String name) {		

		JSONObject jo = new JSONObject();
		jo.put("values", new JSONArray(new Long[][]{{1025409600000L,23L},{1028088000000L,19L},{1030766400000L,21L},{1033358400000L,22L}}));		
		jo.put("key", "North America");
		
		JSONArray ja = new JSONArray();
		
		for (int i = 0; i < 10; i++) {
			ja.put(jo);
		}
		
		return ja.toString();	
	}


}
  • Now lets run this application (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:

Spring MVC AngularJS RESTFul Service example

  • Click “Get JSON data from server” button you will see below data:

Spring MVC AngularJS RESTFul Service example

  • That’s it we have created Spring MVC AngularJS RESTFul Service example and ran successfully.
  • For more information about Spring MVC RESTFul service please visit this tutorial
  • For AngularJS visit this tutorial

download Download Project: SpringMVCAngularJSRESTFulService

One thought on “Spring MVC AngularJS RESTFul Service example”
  1. Hello sir,

    Spring MVC AngularJS RESTFul Service example

    When I import into Eclipse STS, and run. then I clicked the button, but the error 0 occured coming

    Raw data received form server:

    Iterate and align data received form server:
    data not coming

    please sir give me good working

    regards
    arun

Leave a Reply

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