Spring MVC AngularJS integration

Spring MVC AngularJS integration

This tutorial will show you how to integrate Spring MVC application with AngularJS. Here I have made Spring MVC controller RESTFul web service where angularJS is requesting data through http protocol and response has been return back in XML format. Controller been mapped to return data in both format JSON/XML. Please see steps below to develop this application:

  • Create maven project name: SpringMVCAngularJS in eclipse
  • After all configuration and classes final project structure will look as below:

Spring MVC AngularJS integration

  • Maven pom.xml file:
<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>SpringMVCAngularJS</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringMVCAngularJS Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <SpringVersion>4.0.6.RELEASE</SpringVersion>
        <jackson.version>1.9.10</jackson.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</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>

        <!-- Jackson JSON Mapper -->
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>${jackson.version}</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>SpringMVCAngularJS</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.0</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

  • dispatcher-servlet.xml file inside WEB-INF folder:
<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-3.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <context:component-scan base-package="com.javahonk.controller" />
    <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>

</beans>
  • angularJS.jsp:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Spring MVC AngularJS demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script>

    var app = angular.module('myApp', []);
    
    function MyController($scope, $http){
        
        $scope.getPersonDataFromServer = function() {           
            $http({method: 'GET', url: 'springAngularJS.web'}).
            success(function(data, status, headers, config) {
                $scope.person = data;
            }).
            error(function(data, status, headers, config) {
              // called asynchronously if an error occurs
              // or server returns response with an error status.
            });
        
        };
    };
</script>
</head>
<body>
    <div data-ng-app="myApp">
        <div data-ng-controller="MyController">
            <button data-ng-click="getPersonDataFromServer()">Get Person data from server</button>
            <p>First Name : {{person.firstName}}</p>
            <p>Last Name : {{person.lastName}}</p>
        </div>
    </div>
</body>
</html>
  • web.xml file:
<?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"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <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>*.web</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>angularJS.web</welcome-file>
    </welcome-file-list>
    <display-name>SpringAngularJS</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
</web-app>
  • Person.java:
package com.javahonk.controller;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Person {
    
    private String firstName;
    private String lastName;
    
    @XmlAttribute
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    @XmlAttribute
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }   
    
}

  • SpringMVCController.java:
package com.javahonk.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class SpringMVCController {
    
    @RequestMapping(value="/angularJS.web",method = RequestMethod.GET)
    public String printWelcome(ModelMap model) {
        return "angularJS";
    }
    
    
    @RequestMapping(value="/springAngularJS.web", 
            method=RequestMethod.GET,
            produces={"application/xml", "application/json"})
    public @ResponseBody Person  getPerson() {      
        Person person = new Person();
        person.setFirstName("Java");
        person.setLastName("Honk");
        return person;
    }
}
  • To run: Right click project –> Run As –> Run on Server (Note: We are using tomcat server to run this application. If you are not sure how to configure tomcat server in eclipse please follow this link). You will see below page:

Spring MVC AngularJS integration

  • Click button: Get Person data from server to pass HTTP request using angularJS where spring controller will return data as below:

Spring MVC AngularJS integration

 

  • That’s it. For more information please read AngularJS tutorial here

download Download Project: SpringMVCAngularJS

13 thoughts on “Spring MVC AngularJS integration

  1. hi, I have tried your code and i got 405 server response. so please suggest how to remove this error. thanks 🙂

  2. With Spring 4.1.6, using Jackson 2.5 was required to get past the 406 errors. Without the right Jackson library, Spring won’t generate json responses, which is what angular has in its Accepts request header.

  3. How do we pass data in such request and retrieve them in the controller? can you please provide an example for it.

  4. Integration works well but how to redirect from jsp to html page, since angularjs uses html pages. tried showing 404 . please anyone can help on this.

Leave a Reply

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