Angularjs and Spring Integration Tutorial
HTML5, rich browser-based features, and the single page application are extremely valuable tools for modern development. Every application requires a server side (backend) framework besides the client side (frontend) framework.
The server side can serve content, render dynamic HTML, authenticate users, secure access to protect resources or interact with Javascript in the browser through HTTP and JSON. Spring has been always one of the popular server sides framework in java world.
On the other hand, Angularjs becomes popular for the single page applications in the client side. In this tutorial, we show how this two framework integrate easily and works together.
AngularJS Programming Cookbook
In this ebook, we provide a compilation of AngularJS based examples that will help you kick-start your own web projects. We cover a wide range of topics, from Single Page Apps and Routing, to Data Binding and JSON Fetching. With our straightforward tutorials, you will be able to get your own projects up and running in minimum time. Download the cookbook by joining the Web Code Geeks Newsletter.
1. What is Spring?
The Spring Framework is a lightweight solution for enterprise applications. Spring is modular and allows you to use only those parts that you need, without having to bring in the rest. Spring is designed to be non-intrusive, meaning that your domain logic code generally has no dependencies on the framework itself. We show here how to integrate the spring easily with Angularjs in presentation layer.
2. What Is Angular?
AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML’s syntax to express your application’s components clearly and succinctly. Angular’s data binding and dependency injection eliminate much of the code you would otherwise have to write. And it all happens within the browser, making it an ideal partner with any server technology.
3. Create a New Project
Now, lets create a project and go through more details. The following project is created in IntellijIDEA 15 CE. The project developed based on jdk 1.8 and uses maven 3 and tomcat 7.
First, create a Maven project in your IDEA. The source directory of the project should be as below.
3.1. Maven dependencies
The first step is to configure the pom.xml
file to include all required dependencies in the project. In this tutorial, we use spring-context-4.2.4-RELEASE and spring-webmvc-4.2.4-RELEASE to configure the spring. Also, we use webjars libraries to include all required js files.
WebJars is simply taking the concept of a JAR and applying it to client-side libraries or resources. For example, the Angularjs
library may be packaged as a JAR and made available to your Spring MVC application. Many WebJars are available through Maven Central with a GroupID of org.webjars
. A complete list is available at webjars.org.
JavaScript package management is not a new concept. In fact, npm and bower are two of the more popular tools, and currently offer solutions to managing JavaScript dependencies. Spring’s Understanding JavaScript Package Managers guide has more information on these. Most JavaScript developers are likely familiar with npm and bower and make use of those in their projects. However, WebJars utilizes Maven’s dependency management model to include JavaScript libraries in a project, making it more accessible to Java developers.
This tutorial illustrates how simple it is to use WebJars in your Spring MVC application, and how WebJars provide a convenient way of managing JavaScript packages and dependencies.
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?> <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> <packaging>war</packaging> <groupId>spring-angularjs-tutorial</groupId> <artifactId>spring-angularjs-tutorial</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</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>org.webjars</groupId> <artifactId>angularjs</artifactId> <version>1.4.8</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>bootstrap</artifactId> <version>3.3.6</version> <scope>runtime</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.6</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <path>/</path> </configuration> </plugin> </plugins> </build> </project>
maven-compiler-plugin
is used to compile the project and maven-war-plugin
is used to build the war file. As we configure the web app in java file in this tutorial, there is no web.xml
file in the source directory. So, the following configuration is required in the maven-war-plugin
to prevent any further exceptions regarding missing web.xml
file <failOnMissingWebXml>false</failOnMissingWebXml>.
Another plugin that is used is tomcat7-mabven-plugin
, to run the application without installing any tomcat server (You can install the tomcat and deploy the project in your tomcat).
3.2. Web app java-based configuration
Since Spring 3, WebApplicationInitializer
is implemented in order to configure the ServletContext programmatically in replacement of the WEB-INF/web.xml
file. Most Spring users building a web application will need to register Spring’s DispatcherServlet
. Here is the equivalent DispatcherServlet
registration logic in form of a java class.
WebAppInitializer.java
package com.javacodegeeks.examples; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; public class WebAppInitializer implements WebApplicationInitializer { private static final String CONFIG_LOCATION = "com.javacodegeeks.examples.config"; @Override public void onStartup(ServletContext servletContext) throws ServletException { System.out.println("***** Initializing Application for " + servletContext.getServerInfo() + " *****"); // Create ApplicationContext AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext(); applicationContext.setConfigLocation(CONFIG_LOCATION); // Add the servlet mapping manually and make it initialize automatically DispatcherServlet dispatcherServlet = new DispatcherServlet(applicationContext); ServletRegistration.Dynamic servlet = servletContext.addServlet("mvc-dispatcher", dispatcherServlet); servlet.addMapping("/"); servlet.setAsyncSupported(true); servlet.setLoadOnStartup(1); } }
The following class extends WebMvcConfigurerAdapter
to customise the java-based configuration for SpringMVC. It is as opposed to the mvc-dispatcher.xml
. To configure the resources and viewResolver, addResourceHandlers
and getViewResolver
are overridden as below.
WebConfig.java
package com.javacodegeeks.examples.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; @EnableWebMvc @Configuration @ComponentScan("com.javacodegeeks.examples") public class WebConfig extends WebMvcConfigurerAdapter{ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/static/js/**") .addResourceLocations("/resources/static/js/"); registry.addResourceHandler("/resources/static/css/**") .addResourceLocations("/resources/static/css/"); registry.addResourceHandler("/resources/static/views/**") .addResourceLocations("/resources/static/views/"); registry.addResourceHandler("/resources/static/**") .addResourceLocations("/resources/static/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("/webjars/"); } @Bean public ViewResolver getViewResolver(){ InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix("/WEB-INF/jsp/"); resolver.setSuffix(".jsp"); return resolver; } @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } }
3.3. SpringMVC controller and jsp
The following class is only a simple controller which is implemented to handle the request to '/'
and render the request to homepage.jsp
.
MainController.java
package com.javacodegeeks.examples.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class MainController { @RequestMapping("/") public String homepage(){ return "homepage"; } }
In the homepage.jsp
, there are some front end code to display links in the page which handled by Angularjs
. Also, there are some script tags which included all required Angularjs js files.
homepage.jsp
<!DOCTYPE html> <!--[if lt IE 7]> <html lang="en" ng-app="app" class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html lang="en" ng-app="app" class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html lang="en" ng-app="app" class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html lang="en" ng-app="app" class="no-js"> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Spring and Angularjs Tutorial</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="../resources/static/css/app.css"> </head> <body> <h2>Spring and Angularjs Tutorial</h2> <div class="home-section"> <ul class="menu-list"> <li><a href="#/gallery">Photo Gallery</a></li> <li><a href="#/contactus">Contact</a></li> </ul> </div> <div ng-view></div> <script src="./webjars/angularjs/1.4.8/angular.js"></script> <script src="./webjars/angularjs/1.4.8/angular-resource.js"></script> <script src="./webjars/angularjs/1.4.8/angular-route.js"></script> <script src="../resources/static/js/app.js"></script> <script src="../resources/static/js/controller.js"></script> <link rel="stylesheet" href="./webjars/bootstrap/3.3.6/css/bootstrap.css"> </body> </html>
ng-view
is a directive that complements the $route
service by including the rendered template of the current route into the main layout. Every time the current route changes, the included view changes with it according to the configuration of the $routeProvider
.
3.4. Angularjs controllers and js files
app.js
file defines the application module configuration and routes. To handle a request to e.g. '/'
, it needs an Angularjs module, called ngRoute. To use ngRoute
and inject it into our application. We use angular.module
to add the ngRoute
module to our app as shown below.
app.js
var app = angular.module('app', ['ngRoute','ngResource']); app.config(function($routeProvider){ $routeProvider .when('/gallery',{ templateUrl: 'resources/static/views/gallery.html', controller: 'galleryController' }) .when('/contactus',{ templateUrl: 'resources/static/views/contactus.html', controller: 'contactusController' }) .otherwise( { redirectTo: '/'} ); });
Then, in the app.config
, each route is mapped to a template and controller.
Controller.js
contains implementation of controllers. The controller is simply a constructor function that takes a $scope
parameter. You might notice that we are injecting the $scope
service into our controller. Yes, AngularJS comes with a dependency injection container built in to it.
Here, a headingtitle is set in scope to display in the view, either gallery or contactInfo.
controller.js
app.controller('galleryController', function($scope) { $scope.headingTitle = "Photo Gallery Items"; }); app.controller('contactusController', function($scope) { $scope.headingTitle = "Contact Info"; });
The concept of a scope in Angular is crucial. A scope can be seen as the glue which allows the template, model and controller to work together. Angular uses scopes, along with the information contained in the template, data model, and controller, to keep models and views separate, but in sync. Any changes made to the model are reflected in the view; any changes that occur in the view are reflected in the model.
contactus.html
<div class="section"> <h3>{{headingTitle}}</h3> <div> <ul type="disc"> <li>Address: Unit 10, Sydney, NSW, Australia</li> <li>Phone: 1111 2222</li> <li>Fax: 4444 5555</li> </ul> </div> </div>
In this two html files, you can see the {{headingTitle}}
which will be filled later by the value that is set in scope.
gallery.html
<div class="section"> <h3>{{headingTitle}}</h3> <div class="gallery-section"> <img class="photo" src="./resources/static/images/images.jpeg"/> <img class="photo" src="./resources/static/images/images2.jpeg"> </div> </div>
3.5. Build and run the application on tomcat
Now, it is time to deploy and run the project. To do so, go to the project directory and run:
mvn clean install
Then, run the application on tomcat.
mvn tomcat7:run
And you can navigate the project as below.
4. Download the source code
This was a Tutorial about Angularjs and Spring Integration.
You can download the full source code of this example here: Angularjs and Spring integration tutorial