• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

AngularJS Spring MVC integration

December 20, 2016 by javainterviewpoint Leave a Comment

In this tutorial, we will learn how to integrate AngularJS with Spring MVC application. We will be building a REST Web service using Spring MVC Controller (@RESTController), here AngularJS will request the data through the HTTP protocol and the RESTFul Web Service will return the JSON format response. Let’s now dig into the code.

Folder Structure:

AngularJS Spring MVC

  1. Create a simple Maven Project “Spring-Angularjs-Tutorial” and create a package for our source files “com.javainterviewpoint” under  src/main/java 
  2. Now add the following dependency in the 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/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.javainterviewpoint</groupId>
      <artifactId>Spring-Angularjs-Tutorial</artifactId>
      <packaging>war</packaging>
      <version>0.0.1-SNAPSHOT</version>
      <name>Spring-Angularjs-Tutorial Maven Webapp</name>
      <url>http://maven.apache.org</url>
      <dependencies>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>4.2.4.RELEASE</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-core</artifactId>
          <version>4.2.4.RELEASE</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>4.2.4.RELEASE</version>
        </dependency>
        <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>javax.servlet-api</artifactId>
          <version>3.1.0</version>
        </dependency>
        <dependency>
          <groupId>jstl</groupId>
          <artifactId>jstl</artifactId>
          <version>1.2</version>
        </dependency>
        <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-databind</artifactId>
          <version>2.3.3</version>
        </dependency>
       </dependencies>
     <build>
        <finalName>Spring-Angularjs-Tutorial</finalName>
     </build>
    </project>
  3. Create the Java classes HelloController.java and UserDetails.java under com.javainterviewpoint folder.
  4. Place the hello.jsp under /WEB-INF/Jsp directory.
  5. Place the web.xml and SpringAngular-servlet.xml under the /WEB-INF directory

AngularJS Spring MVC integration

HelloController

package com.javainterviewpoint;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

@RestController
public class HelloController
{
    @RequestMapping(value="/hello")
    public ModelAndView hello()
    {
        return new ModelAndView("hello");
    }
    @RequestMapping(value="/userdetails",method=RequestMethod.GET,produces="application/json")
    public UserDetails userdetails()
    {
        UserDetails userDetails = new UserDetails();
        userDetails.setName("JavaInterviewPoint");
        userDetails.setDepartment("Blogging");
        
        return userDetails;
    }
}
  • Our HelloController will act as the RESTFul Webservice, it has two methods.
    • hello() – This method simply redirects the user to hello.jsp
    • userdetails() – This method serves the request “/userdetails” returns the user information in the JSON format.

UserDetails

package com.javainterviewpoint;

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

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class UserDetails
{
    @XmlAttribute
    private String name;
    @XmlAttribute
    private String department;
    public UserDetails()
    {
        super();
    }
    public UserDetails(String name, String department)
    {
        super();
        this.name = name;
        this.department = department;
    }
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public String getDepartment()
    {
        return department;
    }
    public void setDepartment(String department)
    {
        this.department = department;
    }
}

UserDetails class is a simple POJO class consisting the details of the user such name and department.

index.jsp

 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%response.sendRedirect("hello");%>
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>

index page simply redirects the user to /hello and the controller in-turn redirects the user to hello.jsp

hello.jsp

 <!doctype html>
<html ng-app>
  <head>
    <title>Angularjs Spring MVC sample application</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
    <script>
      function Hello($scope, $http) {
        $scope.getUserDetails = function()
        {
           $http.get('http://localhost:8080/Spring-Angularjs-Tutorial/userdetails').
           success(function(data) {
           $scope.user = data;
        });
      }
    }
    </script>
   </head>
   <body>
     <div ng-controller="Hello">
       <h2>Angularjs Spring MVC sample application!!</h2>
       <button ng-click="getUserDetails()">Get User Details</button>
       <p>Name : {{user.name}}</p>
       <p>Department : {{user.department}}</p>
     </div>
   </body>
</html>

When the user clicks on the “Get User Details” button the getUserDetails() method will be called. The getUserDetails() method uses the $http service and hits our REST Service and retrieves the userDetails in the JSON format which will be binded and displayed in the Screen.

web.xml

 <!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Spring AngularJS Tutorial</display-name>
  <servlet>
   <servlet-name>SpringAngular</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
  <servlet-mapping>
   <servlet-name>SpringAngular</servlet-name>
   <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>
  • The web.xml has everything about the application that a server needs to know, which is placed under the WEB-INF directory.  It contains the name of the SpringConfiguration file, when the DispatcherServlet is initialized the framework will try to load a configuration file “[servlet-name]-servlet.xml” under the WEB-INF directory.

SpringAngular-servlet.xml

 <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">
 
 <context:component-scan base-package="com.javainterviewpoint" />
 <mvc:annotation-driven />
 
 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 <property name="prefix" value="/WEB-INF/Jsp/" />
 <property name="suffix" value=".jsp" />
 </bean>
</beans>
  • The SpringConfig-servlet.xml is also placed under the WEB-INF directory.
  • <context:component-scan> will let the Spring Container to search for all the annotation under the package “com.javainteriviewpoint”. 
  • <mvc:annotation-driven/> annotation will activate the @Controller, @RequestMapping, @Valid etc annotations.
  • The view is resolved through “org.springframework.web.servlet.view.InternalResourceViewResolver” which searches for the jsp files under the /WEB-INF/Jsp/ directory.

Output:

Angularjs Spring MVC sample application

Angularjs Spring MVC sample application 1

Other interesting articles which you may like …

  • AngularJS Hello World Example
  • AngularJS – Modules and Controllers
  • Two-Way Data Binding in AngularJS Example
  • ngBind, ngBindHtml and ngBindTemplate
  • AngularJS Form Validation with ngMessages
  • AngularJS Routing Example using ngRoute
  • AngularJS Spring MVC CRUD Example using $http service

Filed Under: AngularJS, J2EE, Java, JAX-RS, Spring MVC, Spring Tutorial Tagged With: AngularJS Spring MVC

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·