Spring 4 MVC+AngularJS CRUD Example using $http service

This post shows integrating AngularJS with Spring MVC 4. We will create a CRUD application using Spring REST API on back-end and AngularJS encapsulated within plain JSP on front-end, communicating asynchronously with server using $http service. We will also perform all sorts of validation on UI using AngularJS Form validations.


In our application, Client side is based on AngularJS , & server side is based on Spring REST API. This is what our final Application will look like.

Spring4MVCAngularJSCRUDExample_img1

Live Demo

Just for Fun, you can play with the Mock version of Front-end used in this example here. It’s a mini application, which is not interacting with server.So you need to refresh the page to reload the data.

Don’t worry. Full application will be developed in this post from scratch , explaining each step in detail.


Let’s get started.

Following technologies being used:

  • Spring 4.3.1.RELEASE
  • AngularJS 1.4.4
  • Maven 3
  • JDK 1.7
  • Eclipse JUNO Service Release 2
  • M2Eclipse plugin (Optional)

Project Structure

Spring4MVCAngularJSCRUDExample_img0

Provide Dependencies

<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.websystique.springmvc</groupId>
	<artifactId>Spring4MVCAngularJSExample</artifactId>
	<packaging>war</packaging>
	<version>1.0.0</version>
	<name>Spring4MVCAngularJSExample Maven Webapp</name>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<springframework.version>4.3.1.RELEASE</springframework.version>
		<jackson.version>2.7.5</jackson.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>${jackson.version}</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	</dependencies>


	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.2</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.4</version>
				<configuration>
					<warSourceDirectory>src/main/webapp</warSourceDirectory>
					<warName>Spring4MVCAngularJSExample</warName>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
		</plugins>
		<finalName>Spring4MVCAngularJSExample</finalName>
	</build>
</project>


1. Client Side

Client side of our Application is AngularJS based. If you would like to add AngularJs in your skill set, Detailed AngularJS Tutorial is available for you to deep dive in one of the most popular Javascript Meta framework.

Create AngularJS Module

Modules are the most important part of AngularJS application. A module in AngularJS can be thought of as packages in Java. It’s the container for the different parts of an application – controllers, services, filters, directives, etc. AngularJS can group together certain functionalities/Javascript under a single module.

A module can be used by AngularJS to bootstrap an application. By passing the module name to ng-app directive, we can tell AngularJS to load this module as the main entry point for the application. Below is our module. To know more in details about AngularJS Modules, please have a look at AngularJS Modules Explained.

app.js

'use strict';

var App = angular.module('myApp',[]);

Create AngularJS Service to communicate with Server

In our application, we will be communicating with Server which in our example is Spring REST API based back-end. In AngularJS based applications, the preferred way to communicate with server is using AngularJS built-in $http Service. AngularJS $http service allows us to communicate with server endpoints using XHR [browser's XMLHttpRequest Object] API. The $http API is based on the deferred/promise APIs exposed by the $q service which is an implementation of Promise interface, based on Kris Kowal’s Q proposal, which is a standardized way of dealing with asynchronous calls in JavaScript.

To know more in details about AngularJS Services, please have a look at Server communication with AngularJS $http service.

user_service.js

'use strict';

angular.module('myApp').factory('UserService', ['$http', '$q', function($http, $q){

    var REST_SERVICE_URI = 'http://localhost:8080/Spring4MVCAngularJSExample/user/';

    var factory = {
        fetchAllUsers: fetchAllUsers,
        createUser: createUser,
        updateUser:updateUser,
        deleteUser:deleteUser
    };

    return factory;

    function fetchAllUsers() {
        var deferred = $q.defer();
        $http.get(REST_SERVICE_URI)
            .then(
            function (response) {
                deferred.resolve(response.data);
            },
            function(errResponse){
                console.error('Error while fetching Users');
                deferred.reject(errResponse);
            }
        );
        return deferred.promise;
    }

    function createUser(user) {
        var deferred = $q.defer();
        $http.post(REST_SERVICE_URI, user)
            .then(
            function (response) {
                deferred.resolve(response.data);
            },
            function(errResponse){
                console.error('Error while creating User');
                deferred.reject(errResponse);
            }
        );
        return deferred.promise;
    }


    function updateUser(user, id) {
        var deferred = $q.defer();
        $http.put(REST_SERVICE_URI+id, user)
            .then(
            function (response) {
                deferred.resolve(response.data);
            },
            function(errResponse){
                console.error('Error while updating User');
                deferred.reject(errResponse);
            }
        );
        return deferred.promise;
    }

    function deleteUser(id) {
        var deferred = $q.defer();
        $http.delete(REST_SERVICE_URI+id)
            .then(
            function (response) {
                deferred.resolve(response.data);
            },
            function(errResponse){
                console.error('Error while deleting User');
                deferred.reject(errResponse);
            }
        );
        return deferred.promise;
    }

}]);

Note: Please note the hard-coded URL in above service [http://localhost:8080/]. Make sure to align the host/ports according to your setup when deploying on a server.

Create AngularJS Controller

Controllers are the most useful part of an AngularJS application. These are javascript functions/objects which perform majority of UI related work. They can be considered as the driver for Model and View changes. They are the gateway between the model (the data in our application), and the view (whatever a users sees on screen and interacts with).
There core responsibilities includes, Providing Data to UI [Data can be static or fetched from server], Managing presentation logic, such as which element to show/hide, what style to apply on them, etc, Handling user input, such as what happens when a user clicks something or how a text input should be validated, Processing data from user input to be sent to server etc.

To know more in details about AngularJS Controllers, please have a look at AngularJS Controllers Explained.

user_controller.js

'use strict';

angular.module('myApp').controller('UserController', ['$scope', 'UserService', function($scope, UserService) {
    var self = this;
    self.user={id:null,username:'',address:'',email:''};
    self.users=[];

    self.submit = submit;
    self.edit = edit;
    self.remove = remove;
    self.reset = reset;


    fetchAllUsers();

    function fetchAllUsers(){
        UserService.fetchAllUsers()
            .then(
            function(d) {
                self.users = d;
            },
            function(errResponse){
                console.error('Error while fetching Users');
            }
        );
    }

    function createUser(user){
        UserService.createUser(user)
            .then(
            fetchAllUsers,
            function(errResponse){
                console.error('Error while creating User');
            }
        );
    }

    function updateUser(user, id){
        UserService.updateUser(user, id)
            .then(
            fetchAllUsers,
            function(errResponse){
                console.error('Error while updating User');
            }
        );
    }

    function deleteUser(id){
        UserService.deleteUser(id)
            .then(
            fetchAllUsers,
            function(errResponse){
                console.error('Error while deleting User');
            }
        );
    }

    function submit() {
        if(self.user.id===null){
            console.log('Saving New User', self.user);
            createUser(self.user);
        }else{
            updateUser(self.user, self.user.id);
            console.log('User updated with id ', self.user.id);
        }
        reset();
    }

    function edit(id){
        console.log('id to be edited', id);
        for(var i = 0; i < self.users.length; i++){
            if(self.users[i].id === id) {
                self.user = angular.copy(self.users[i]);
                break;
            }
        }
    }

    function remove(id){
        console.log('id to be deleted', id);
        if(self.user.id === id) {//clean form if the user to be deleted is shown there.
            reset();
        }
        deleteUser(id);
    }


    function reset(){
        self.user={id:null,username:'',address:'',email:''};
        $scope.myForm.$setPristine(); //reset Form
    }

}]);

Create View for Spring MVC application

Here we are acting on a bit traditional side and using plain JSP encapsulating all AngularJS code we wrote above. Note that you can use other FE technologies instead of JSP (Velocity templates for example). We have also added bootstrap in our view to enhance it’s look & feel. Additionally, we will also perform required Form validation. To know Form Validation in details [in general in AngularJS], please have a look at AngularJS Form Validation Explained.

UserManagement.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
  <head>  
    <title>AngularJS $http Example</title>  
    <style>
      .username.ng-valid {
          background-color: lightgreen;
      }
      .username.ng-dirty.ng-invalid-required {
          background-color: red;
      }
      .username.ng-dirty.ng-invalid-minlength {
          background-color: yellow;
      }

      .email.ng-valid {
          background-color: lightgreen;
      }
      .email.ng-dirty.ng-invalid-required {
          background-color: red;
      }
      .email.ng-dirty.ng-invalid-email {
          background-color: yellow;
      }

    </style>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
     <link href="<c:url value='/static/css/app.css' />" rel="stylesheet"></link>
  </head>
  <body ng-app="myApp" class="ng-cloak">
      <div class="generic-container" ng-controller="UserController as ctrl">
          <div class="panel panel-default">
              <div class="panel-heading"><span class="lead">User Registration Form </span></div>
              <div class="formcontainer">
                  <form ng-submit="ctrl.submit()" name="myForm" class="form-horizontal">
                      <input type="hidden" ng-model="ctrl.user.id" />
                      <div class="row">
                          <div class="form-group col-md-12">
                              <label class="col-md-2 control-lable" for="uname">Name</label>
                              <div class="col-md-7">
                                  <input type="text" ng-model="ctrl.user.username" id="uname" class="username form-control input-sm" placeholder="Enter your name" required ng-minlength="3"/>
                                  <div class="has-error" ng-show="myForm.$dirty">
                                      <span ng-show="myForm.uname.$error.required">This is a required field</span>
                                      <span ng-show="myForm.uname.$error.minlength">Minimum length required is 3</span>
                                      <span ng-show="myForm.uname.$invalid">This field is invalid </span>
                                  </div>
                              </div>
                          </div>
                      </div>
                        
                      
                      <div class="row">
                          <div class="form-group col-md-12">
                              <label class="col-md-2 control-lable" for="address">Address</label>
                              <div class="col-md-7">
                                  <input type="text" ng-model="ctrl.user.address" id="address" class="form-control input-sm" placeholder="Enter your Address. [This field is validation free]"/>
                              </div>
                          </div>
                      </div>

                      <div class="row">
                          <div class="form-group col-md-12">
                              <label class="col-md-2 control-lable" for="email">Email</label>
                              <div class="col-md-7">
                                  <input type="email" ng-model="ctrl.user.email" id="email" class="email form-control input-sm" placeholder="Enter your Email" required/>
                                  <div class="has-error" ng-show="myForm.$dirty">
                                      <span ng-show="myForm.email.$error.required">This is a required field</span>
                                      <span ng-show="myForm.email.$invalid">This field is invalid </span>
                                  </div>
                              </div>
                          </div>
                      </div>

                      <div class="row">
                          <div class="form-actions floatRight">
                              <input type="submit"  value="{{!ctrl.user.id ? 'Add' : 'Update'}}" class="btn btn-primary btn-sm" ng-disabled="myForm.$invalid">
                              <button type="button" ng-click="ctrl.reset()" class="btn btn-warning btn-sm" ng-disabled="myForm.$pristine">Reset Form</button>
                          </div>
                      </div>
                  </form>
              </div>
          </div>
          <div class="panel panel-default">
                <!-- Default panel contents -->
              <div class="panel-heading"><span class="lead">List of Users </span></div>
              <div class="tablecontainer">
                  <table class="table table-hover">
                      <thead>
                          <tr>
                              <th>ID.</th>
                              <th>Name</th>
                              <th>Address</th>
                              <th>Email</th>
                              <th width="20%"></th>
                          </tr>
                      </thead>
                      <tbody>
                          <tr ng-repeat="u in ctrl.users">
                              <td><span ng-bind="u.id"></span></td>
                              <td><span ng-bind="u.username"></span></td>
                              <td><span ng-bind="u.address"></span></td>
                              <td><span ng-bind="u.email"></span></td>
                              <td>
                              <button type="button" ng-click="ctrl.edit(u.id)" class="btn btn-success custom-width">Edit</button>  <button type="button" ng-click="ctrl.remove(u.id)" class="btn btn-danger custom-width">Remove</button>
                              </td>
                          </tr>
                      </tbody>
                  </table>
              </div>
          </div>
      </div>
      
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script>
      <script src="<c:url value='/static/js/app.js' />"></script>
      <script src="<c:url value='/static/js/service/user_service.js' />"></script>
      <script src="<c:url value='/static/js/controller/user_controller.js' />"></script>
  </body>
</html>




2. Server Side

Create REST Controller for Spring MVC application

Below shown is a REST based Controller. It is the same controller as explained in Spring MVC 4 RESTFul Web Services CRUD Example+RestTemplate. Only difference is that User [the model object] have different properties, based on User interface in this example. Please visit the mentioned post to clarify any doubts you might have regarding REST support in Spring.

package com.websystique.springmvc.controller;
 
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
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.util.UriComponentsBuilder;

import com.websystique.springmvc.model.User;
import com.websystique.springmvc.service.UserService;
 
@RestController
public class HelloWorldRestController {
 
    @Autowired
    UserService userService;  //Service which will do all data retrieval/manipulation work
 
    
    //-------------------Retrieve All Users--------------------------------------------------------
     
    @RequestMapping(value = "/user/", method = RequestMethod.GET)
    public ResponseEntity<List<User>> listAllUsers() {
        List<User> users = userService.findAllUsers();
        if(users.isEmpty()){
            return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND
        }
        return new ResponseEntity<List<User>>(users, HttpStatus.OK);
    }
 
 
    
    //-------------------Retrieve Single User--------------------------------------------------------
     
    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<User> getUser(@PathVariable("id") long id) {
        System.out.println("Fetching User with id " + id);
        User user = userService.findById(id);
        if (user == null) {
            System.out.println("User with id " + id + " not found");
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<User>(user, HttpStatus.OK);
    }
 
     
     
    //-------------------Create a User--------------------------------------------------------
     
    @RequestMapping(value = "/user/", method = RequestMethod.POST)
    public ResponseEntity<Void> createUser(@RequestBody User user,    UriComponentsBuilder ucBuilder) {
        System.out.println("Creating User " + user.getUsername());
 
        if (userService.isUserExist(user)) {
            System.out.println("A User with name " + user.getUsername() + " already exist");
            return new ResponseEntity<Void>(HttpStatus.CONFLICT);
        }
 
        userService.saveUser(user);
 
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getId()).toUri());
        return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
    }
 
    
     
    //------------------- Update a User --------------------------------------------------------
     
    @RequestMapping(value = "/user/{id}", method = RequestMethod.PUT)
    public ResponseEntity<User> updateUser(@PathVariable("id") long id, @RequestBody User user) {
        System.out.println("Updating User " + id);
         
        User currentUser = userService.findById(id);
         
        if (currentUser==null) {
            System.out.println("User with id " + id + " not found");
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
 
        currentUser.setUsername(user.getUsername());
        currentUser.setAddress(user.getAddress());
        currentUser.setEmail(user.getEmail());
         
        userService.updateUser(currentUser);
        return new ResponseEntity<User>(currentUser, HttpStatus.OK);
    }
 
    
    
    //------------------- Delete a User --------------------------------------------------------
     
    @RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<User> deleteUser(@PathVariable("id") long id) {
        System.out.println("Fetching & Deleting User with id " + id);
 
        User user = userService.findById(id);
        if (user == null) {
            System.out.println("Unable to delete. User with id " + id + " not found");
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
 
        userService.deleteUserById(id);
        return new ResponseEntity<User>(HttpStatus.NO_CONTENT);
    }
 
     
    
    //------------------- Delete All Users --------------------------------------------------------
     
    @RequestMapping(value = "/user/", method = RequestMethod.DELETE)
    public ResponseEntity<User> deleteAllUsers() {
        System.out.println("Deleting All Users");
 
        userService.deleteAllUsers();
        return new ResponseEntity<User>(HttpStatus.NO_CONTENT);
    }
 
}

Create Main Controller for Spring MVC application

This is a trivial controller which will serve our main page.

package com.websystique.springmvc.controller;

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

@Controller
@RequestMapping("/")
public class IndexController {

	  @RequestMapping(method = RequestMethod.GET)
	    public String getIndexPage() {
	        return "UserManagement";
	    }

}

Create Spring based Service to handle user related operations

package com.websystique.springmvc.service;

import java.util.List;

import com.websystique.springmvc.model.User;



public interface UserService {
	
	User findById(long id);
	
	User findByName(String name);
	
	void saveUser(User user);
	
	void updateUser(User user);
	
	void deleteUserById(long id);

	List<User> findAllUsers(); 
	
	void deleteAllUsers();
	
	public boolean isUserExist(User user);
	
}

package com.websystique.springmvc.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

import org.springframework.stereotype.Service;

import com.websystique.springmvc.model.User;

@Service("userService")
public class UserServiceImpl implements UserService{
	
	private static final AtomicLong counter = new AtomicLong();
	
	private static List<User> users;
	
	static{
		users= populateDummyUsers();
	}

	public List<User> findAllUsers() {
		return users;
	}
	
	public User findById(long id) {
		for(User user : users){
			if(user.getId() == id){
				return user;
			}
		}
		return null;
	}
	
	public User findByName(String name) {
		for(User user : users){
			if(user.getUsername().equalsIgnoreCase(name)){
				return user;
			}
		}
		return null;
	}
	
	public void saveUser(User user) {
		user.setId(counter.incrementAndGet());
		users.add(user);
	}

	public void updateUser(User user) {
		int index = users.indexOf(user);
		users.set(index, user);
	}

	public void deleteUserById(long id) {
		
		for (Iterator<User> iterator = users.iterator(); iterator.hasNext(); ) {
		    User user = iterator.next();
		    if (user.getId() == id) {
		        iterator.remove();
		    }
		}
	}

	public boolean isUserExist(User user) {
		return findByName(user.getUsername())!=null;
	}
	
	public void deleteAllUsers(){
		users.clear();
	}

	private static List<User> populateDummyUsers(){
		List<User> users = new ArrayList<User>();
		users.add(new User(counter.incrementAndGet(),"Sam", "NY", "sam@abc.com"));
		users.add(new User(counter.incrementAndGet(),"Tomy", "ALBAMA", "tomy@abc.com"));
		users.add(new User(counter.incrementAndGet(),"Kelly", "NEBRASKA", "kelly@abc.com"));
		return users;
	}

}

Create Model

package com.websystique.springmvc.model;

public class User {

	private long id;
	
	private String username;
	
	private String address;
	
	private String email;
	
	public User(){
		id=0;
	}
	
	public User(long id, String username, String address, String email){
		this.id = id;
		this.username = username;
		this.address = address;
		this.email = email;
	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + (int) (id ^ (id >>> 32));
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (!(obj instanceof User))
			return false;
		User other = (User) obj;
		if (id != other.id)
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", address=" + address
				+ ", email=" + email + "]";
	}
	

	
}

Create Spring Configuration Class

package com.websystique.springmvc.configuration;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.websystique.springmvc")
public class HelloWorldConfiguration extends WebMvcConfigurerAdapter{
	
	@Override
	public void configureViewResolvers(ViewResolverRegistry registry) {
		InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
		viewResolver.setViewClass(JstlView.class);
		viewResolver.setPrefix("/WEB-INF/views/");
		viewResolver.setSuffix(".jsp");
		registry.viewResolver(viewResolver);
	}

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/static/**").addResourceLocations("/static/");
	}

}

Create Spring Initializer class

Look at how we are registering CORS filter with Spring configuration, which will help us to get away with Same Origin Policy issues.

package com.websystique.springmvc.configuration;

import javax.servlet.Filter;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class HelloWorldInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
 
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] { HelloWorldConfiguration.class };
    }
  
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return null;
    }
  
    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
    
    @Override
    protected Filter[] getServletFilters() {
    	Filter [] singleton = { new CORSFilter() };
    	return singleton;
	}
 
}

Create Filter to handle Same Origin Policy related issues

package com.websystique.springmvc.configuration;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;


public class CORSFilter implements Filter {

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		System.out.println("Filtering on...........................................................");
		HttpServletResponse response = (HttpServletResponse) res;
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
		response.setHeader("Access-Control-Max-Age", "3600");
		response.setHeader("Access-Control-Allow-Headers", "X-requested-with, Content-Type");
		chain.doFilter(req, res);
	}

	public void init(FilterConfig filterConfig) {}

	public void destroy() {}

}

Deploy & Run

Now build the war (either by eclipse as was mentioned in previous tutorials) or via maven command line( mvn clean install). Deploy the war to a Servlet 3.0 container . Since here i am using Tomcat, i will simply put this war file into tomcat webapps folder and click on startup.bat inside tomcat/bin directory.

Open browser and browse at http://localhost:8080/Spring4MVCAngularJSExample/

Spring4MVCAngularJSCRUDExample_img1

Fill in details to add a new user

Spring4MVCAngularJSCRUDExample_img2

Click on Add, user should be added asynchronously.

Spring4MVCAngularJSCRUDExample_img3

Click on Delete for a user, user should be deleted asynchronously.

Spring4MVCAngularJSCRUDExample_img4

Click on Edit for a user, user details should be shown on form. Update details.

Spring4MVCAngularJSCRUDExample_img5

Now click on Update, user should be updated asynchronously.

Spring4MVCAngularJSCRUDExample_img6

Thanks to AngularJS Form validation, if you try to provide input which is not as per requirement, you will see validation errors like shown below.You can of course adapt messages and presentation as per your project.

Spring4MVCAngularJSCRUDExample_img7

That’s it.

Download Source Code



References

If you like tutorials on this site, why not take a step further and connect me on Facebook , Google Plus & Twitter as well? I would love to hear your thoughts on these articles, it will help me improve further our learning process.

If you appreciate the effort I have put in this learning site, help me improve the visibility of this site towards global audience by sharing and linking this site from within and beyond your network. You & your friends can always link my site from your site on www.websystique.com, and share the learning.

After all, we are here to learn together, aren’t we?

  • Pingback: dadafdf3ddafdsa()

  • Pingback: dadafdf3ddafdsa()

  • Ravi Kumar

    Hi Websystique,

    i have taken your example reference but my problem is when i sent a post request so i want a immediate response data from the controller why because if any error is happening while persisting the data or any server side validation is happening so i want so at client side, So please let me know how to do ? Please suggest me.

  • Pingback: me rt last()

  • Ashutosh Saini

    Thanks a lot for the tutorial, I setup the tomcat as per your tutorial and able to get the tomcat home page but when running the application its giving me 404 error. I downloaded the source code from above post and imported in eclipse directly. https://uploads.disquscdn.com/images/b7404dff5f76132589031bc252e313ef2c8a5936ac5ebaea9d19520c6dbf7d85.jpg

    • websystique

      Hi Ashutosh, It is probably related to the tomcat setup. Did you follow Setup Tomcat With Eclipse, specially the assembly step?

      • Ashutosh Saini

        Hi, yes i did followed the tomcat setup and completed the assembly setup. I can see the Maven dependencies in web deployment assembly. Thanks for your response.

      • Ashutosh Saini

        I was able to run it successfully after updating the maven. Thanks.

  • Pingback: Молодежка4сезон25серия26серия()

  • Boppana Bhanu Prakash

    @websystique:disqus I have added one more view say “EmployeeManagement”. I’m able to see this view if I change the IndexController. How can I access two views from the browser?

    • websystique

      Hi Bhanu,

      If you have multi view app, i would recommend start using AngularJs ui-router instead. Have a look at this post, most of your doubts would be resolved.

  • Pingback: lastssadsafdsa()

  • Pingback: molodejka4seria25()

  • Boris Petrov

    Hi, I am very interested how would this work if I have multiple pages? app like for login, logout, create issues and stuffs which are not all on one page.

    • websystique

      Hi Boris, AngularJS apps are one-page app, and we oftern use ui-router kind of stuff to load multiple views/templates while staying on the same page. These views can be login/cart/payment etc..

      In any case, if you have an existing multipage non-angular app, which you want to angularfy but still keeping all your page, you can create multiple angular apps and include them on different pages. Have a look at AngularJs ui-router tutorial and things will start making more sense.

  • Pingback: molodejka4sezon21seria21seria22seria23()

  • Pingback: molodezhka4sezon212223seriya()

  • Pingback: xml181120167()

  • Pingback: xml18112016()

  • Pingback: link2016()

  • Pingback: molodejka4s21()

  • Pingback: nolodejka4sezonl332()

  • Pingback: molodejka4sezon21222324252617()

  • Pingback: AngularJS+Spring Security using Basic Authentication - WebSystique()

  • Pingback: Spring MVC 4 + Spring Security 4 + Hibernate Example - WebSystique()

  • Pingback: molodejka4sezon19()

  • Pingback: ok.rumolodezhka4sezon17seriya18192s()

  • Pingback: molodejka.4.sezon.18.19.seriya()

  • Pingback: molodezhka-4-sezon-18-serija-148-seria-17-seria-18-seria()

  • Pingback: molodezjka()

  • Pingback: molodezhka4sezon()

  • Pingback: molodezhka4sezon17seriya18192()

  • Pingback: molodejka()

  • Pingback: molodezhka4seria()

  • Pingback: trumpnews()

  • Dwayne

    I am getting an error when submitting the page:
    WARNING: No mapping found for HTTP request with URI [/Spring4MVCAngularJSExample/user/] in DispatcherServlet with name ‘dispatcher’

    • websystique

      Hi Dwayne, Was the deployment itself was fine? If you are using Eclipse+Tomcat, you may want to look at Setup Tomcat With Eclipse.

      • Dwayne

        Hi..got it to work. Do you know if its possible to use Dart instead of Javascript? Or Typescript? I was looking into using dart maven plugin but doesn’t look straightforward.

        • websystique

          Hi Dwayne, i know nothing about Dart. Surely you should be able to use TypeScript instead.

  • Pingback: mirdikogozapada2016()

  • Pingback: mirdikogozapada()

  • Pingback: djekricardnetorrentonline()

  • Akshay Joshi

    Thanks for the tutorial .. It is great !!

  • Pingback: gidrofob()

  • Saagar Tripathi

    Hi I run this app I got this error “The requested resource is not available.” I am using tomcat 8 instead of Tomcat 7

    • websystique

      Hi Saagar, perhaps it is related to your Eclipse+Tomcat setup. Please have a look at Setup Tomcat + Eclipse.

  • Saagar Tripathi

    I run this application but I got problem. There is problem called

    The requested resource is not available.

  • Pingback: novinki kino 2016()

  • Pingback: lopoda()

  • Everett

    It is a nice article. I have spent quite a bit of time to understand it, since I am new to this. I feel I got most of it, so I started adding things into yours. The first thing I added is a drop down list say State. Here are my changes:

    User,java:
    private String state;
    state also into constructor and getter and setter functions.

    In UserServiceImpl.java add state in populateDummyUsers
    users.add(new User(counter.incrementAndGet(),”Sam”, “”, “AL”, “sam@abc.com”));

    In user_controller.js
    self.user={id:null,username:”,address:”,state:”, email:”};

    In UserManagement.jsp, after address row

    State

    Select your state
    Alabama
    Arkansas
    California

    EVERYTHING WORKS FINE. My question is that I do not want to hard code the state dropdown list like I did now. I want to get a list of states in the UserServiceImpl, pass it to controller or whatever. Eventually, I can use this list in the UserManagement.jsp. Can you give me the direction and some simple codes?

    I have tried to find any example, but I can not find with Spring 4 MVC, REST api, and Angularjs

    Thank you so much.

  • Pingback: JAVA | Pearltrees()

  • Pingback: doktor.strendj.online.kino.()

  • Pingback: aisti.online.smotret.aisti.mult()

  • Pingback: mir.dikogo.zapada.ceria.sezon()

  • jaanu

    Hi,what about running it in net beans.please guide

  • Pingback: top2017bloomingme()

  • Pingback: jpmsru()

  • Pingback: jpmsruvideotoppornovideo()

  • Pingback: drama2016()

  • Pingback: kinoklub()

  • Prashant Ravi

    can you connect this example with hibernet ,mysql .so this will be very helpful for me..

  • vb

    Thanks a lot!.. works great.

  • Bhavesh Tamrakar

    Hi , Good application working fine.
    Can you please help on navigate to another page ?
    The scenario is : I have created the login form ” UserManagement2.jsp” as you created in this application and corresponding “user_service2.js” and “user_controller2.js” . this page is loading successfully . Now once its load i filled username and password for this. Once is success from backend i want to navigate to “UserManagement.jsp” that i copied from this application.

    So in my application, i have
    UserManagement2.jsp (Login page)
    user_service2.js
    user_controller2.js
    UserManagement.jsp
    user_service.js
    user_controller.js

    and backend code that is working fine , application structure is same as this application.

    But i am not able to navigate from UserManagement2.jsp (login Page) to UserManagement.jsp based on successfully authenticate. I have tried some $routeProvider and all but not working for me .
    Please provide help on this.
    Thanks Looking for your response :)

  • Binod Raj ʎǝpuɐd

    Its great tutorial but while running this project, I couldn’t retrieve list of users, neither could create new user. It seems user service is not working? can you please tell me what could be the error??

    • Binod Raj ʎǝpuɐd

      Oh I solved this after correcting port number 8084 as my server is using it.

  • maarc

    Hi I deployed the project and made changes in the tomcat as you mentioned in one of the comments.But i am not lucky. I could not see the list of users in the home page as soon as i run the project on server. could please help me in this issue.
    And if try adding the users the data being sent to the server is null. I am not sure wat went wrong at my end.I am new to Angular Js.

    it would be great if some one could help me in this issue.Thank you in advance

    • websystique

      Hi Maarc, Sorry i missed your message.If you are still stuck, may i ask you to first build the project on command line[ mvn clean install] and deploy the war on an external tomcat instance, start tomcat and check if you are able to use the application properly? If yes, then issue is still related to your local setup. Specially, look at the ‘Dependency Management’ section in that Setting up Tomcat with Eclipse. If you still face issue, please send me a screenshot of Developer tools [F12 on chrome]/Network tab when using this application.

      • maarc

        thank you .. i got it solved…:)

  • Pingback: tubepatrolporn()

  • Pingback: toilehtml()

  • Pingback: sunnyleonelatest()

  • Pingback: sunnyleone()

  • Pingback: mp4hdru()

  • Pingback: Лучшие фильмы2()

  • Pingback: Лучшие фильмы()

  • Pingback: hqporn2016()

  • Pingback: pornozavrnet()

  • Pingback: sister-helping-brother-to-masturbaste()

  • Pingback: sister-caught-on-hiddencam-peter()

  • Pingback: xnxxtagssunnyleonexxxbrotherrapessister()

  • Pingback: PussyHerpussyissotight...()

  • Pingback: 18 year old noelle free mobile porn video()

  • Pingback: hqpornforiphonlatestmp43gp()

  • Pingback: hqpornforiphonlatestmp4()

  • Pingback: hqpornforiphonlatest()

  • Pingback: hqpornforiphon()

  • Pingback: sitemaplist()

  • Pingback: online()

  • Pingback: online()

  • Pingback: Tech Updates()

  • Pingback: manastirski_chay_2016ua()

  • Pingback: manastirski_chay_2016()

  • Pingback: manastirski_chay()

  • Abdul Habeeb

    Thanks for providing the tutorial . it is working as shown in the example

    • websystique

      Glad you liked it Abdul.

    • Siva Pandian

      Hi Abdul, i need help to deploy. how did you deploy the code?

  • Pingback: 2016()

  • Pingback: HDKINOONLINE()

  • Pepe Suca

    very thanks, nice post!

  • Pingback: illuziaobmana()

  • Balwant Kumar Singh

    I’ve done tomcat server setup using http://websystique.com/misc/how-to-setup-tomcat-with-eclipse/ link. Still getting 404 while running the application on eclipse. I’ve just downloaded your code, unzipped it and imported and done maven install. The project structure looks like shown in image below. Not sure why red mark is coming in Java Resources folder.

    • Pepe Suca

      solution?

    • websystique

      Hi Balwant,

      About those red mark on resources, most probably you need to perform maven update. Additionally, Eclipse sometime complains about Dynamic web module version issue [No wonder why people prefer IntelliJ over Eclipse]. Please open “Problems” tab [search in quick access on top bar if it is not yet visible]. You will see the details of problems. I explained the solution for that in my comments here. For the 404, this has to be related to tomcat-setup. Please fix the facet issue first, perform maven update, and then perform a deploy again on tomcat, should be fine.

  • Pingback: clic()

  • MAndar Teli

    I am getting nested exception is com.fasterxml.jackson.databind.JsonMappingException error I am trying pass simple values ( bean) why requestbody is not able to deserizlaize.

    Bean

    @Entity

    @Table(name=”travellerlist”)

    public class Traveller {

    public Traveller(){}

    public Traveller( Long id,

    String userName,

    String destination){

    this.id=id;

    this.userName=userName;

    this.destination=destination;

    }

    @JsonProperty(“id”)

    private Long id;

    private String userName;

    Service:– saveTravellerTrips:function(traveller){

    console.log(‘Test1′+JSON.stringify(traveller));

    return $http.post(‘http://pinkeey:8181/travelbookSpringHibernetAngularJS/register/’,traveller)

    .then(

    function(response){

    console.error(‘after retruning from controller’+response.data);

    return response.data;

    },

    function(errResponse){

    console.error(‘Error while register users2′);

    return $q.reject(errResponse);

    }

    );

    }

    controller-

    @RequestMapping(value=”/register/”, method=RequestMethod.POST)

    public ResponseEntity registerTravelBookTraveller(@RequestBody Traveller traveller , UriComponentsBuilder ucBuilder)

    {

    System.out.println(“inside controller XXXX “+traveller.getDestination());

    travelBookDao.saveOrUpdate(traveller);

    HttpHeaders headers = new HttpHeaders();

    headers.setLocation(ucBuilder.path(“/register/{id}”).buildAndExpand(traveller.getId()).toUri());

    return new ResponseEntity(headers,HttpStatus.CREATED);

    }

    private String destination;

  • Pingback: clic here()

  • Pingback: helou zis me()

  • Pingback: helou zis me()

  • Pingback: ukraine girl kiev lviv 2016()

  • Pingback: ukraine girl kiev lviv()

  • Pingback: film()

  • Pingback: more()

  • Jim C

    Please, can you give a superficial explanation how is AngularJS dependencies treated in your project? I am using it successfully. Actually, I have just created an EAR file and deployed it to Websphere 8 hosted in mainframe z/OS. I know that there are several tutorials explaining about Angular dependencies based on npm and bower but since I am stick to your design as my starting point, and it has showed a very good choice, it will be very helpful if you can give an overview about how is the Angular libraries managed in your project. I searched in pom.xml and I didn’t see any suggestion on it. Additionally, I didn’t find any specific javascript library attached to the downloaded project. Is the angularjs libraries already included in Chrome version 45? Is the libraries downloaded on demand when I hit url in Chrome? If so, where is the url pointing to it? Finally, only for learning purpose, let’s say I want to change from Angular 1.4.4 to the next version (maybe 1.5) or previous one (maybe 1.3), where do I change it?

    • websystique

      Hi Jim,

      In my setup, i am referring to angularjs library in my entry page [UserManagement.jsp], like following:

      However, you may prefer to download the js files (keep them in a sub-folder within static folder lets say) and refer to them in your index/entry page instead of referring to the ones on internet. Hope it clarifies your doubts.

  • Deme Carv

    Please, could you give an overview if would be significant improvement in case of AngularJS 2 was used? I guess not unless such example was aimed for mobiles.

    • websystique

      Hi Deme, for the moment i am not really into AngularJS2, so can’t really say much about it. But what i learned is that Angular 2 differs a lot from Angular 1.x. According to Google , Angular 2.x component based approach will simply the development, but so far, developers have shown little enthusiasm towards this move. I prefer to stick with 1.x for the time being, and let 2 gets matured over the time.

      • Deme Carv

        Your comment makes a lot of sense to me. When compared with version 1, I can’t find too many examples in internet even though when the examples are recently published

  • Pingback: Spring 4 MVC+Apache Tiles 3 Example - WebSystique()

  • Pingback: jykfqy abkmvs cvjnhtnm ,tp htubcnhfwbb()

  • Pingback: лучшие фильмы года 2016()

  • Prakash

    Thank you for this wonderful tutorial, it provides a good understanding on setting up a Spring MVC app with angularJS for a beginner. Could you also provide a tutorial on how to implement spring security in this application ?

  • Brian

    I want to download the source code. Apparently there is a trojan virus in there, can you please remove it so I can download the source code safely?

    • websystique

      Hi Brian,I’ve just downloaded the source-code from site, and did a scan with a licensed avast version, and did not find any threat. Are you sure you found a threat in there? Which Antivirus are you using?

      • Brian

        hmm I’m using windows defender (lol I know) I decided to take a risk and ignore it and I don’t think there’s a virus. I hope…thanks for the tutorial I ended up getting a 404 and I’ll try and figure it out. I like all the code and structure of the project though, thanks.

  • Pingback: лучшие фильмы 2016 2016 года список новые фильмы()

  • Hajder Rabiee

    Hello in your JS you’re assigning functions to self, like self.submit etc. I found that in order for the form to work I had to assign it to $scope. Not sure if there’s a difference between angular versions?

    • websystique

      Hi Hajder,

      These are two different ways for doing the same thing, not related at all with angular versions. With $scope style, within your html you don’t have to prefix the properties/methods, while with self approach, you prefix them with controller name/alias. Personally, i found self approach more intuitive, in that it makes clear in HTML which JS property/method belongs to which controller, easier to understand.You can choose whatever approach you prefer.

      • Hajder Rabiee

        Great, I was suspecting it was a ‘minor’ difference and tried it as well but it didn’t work. That’s why I asked, I’ll review the code again to see if I can get it work with self.xxx :).

  • Deme Carv

    Excellent post. Unfortunatelly I can run it perfectly in TomCat 8 but I can’t in Websphere Liberty Profile 8.5. Do you know what I have to do? The well-come table appears in browser but the Add button doesn’t work. I created a question in http://stackoverflow.com/questions/36950825/how-to-make-spring-mvc-4-and-angular-run-in-websphere-8 with all details.

    • websystique

      Hi Deme,Just saw the StackOverflow post, and learned that you have lost some time due to hard-coded port in URL. I’ve updated the post to highlight this point explicitly. Thanks.

      • Deme Carv

        Thanks. I am using your example as base for a small but significant application. By “base” I mean, I am follwoing same structure and way to approach AngularJS. In such application I will have a grid like your example but a rich workflow with few pages allowing me to create a registry spreaded around several tables. As an analogogy, imagine you have an extra step: enter multiple works for your user. Can you give me some tricks or suggestions for this scenario? Or could you improve your example to cover at least one more table with many-to-many joins (e.g. http://websystique.com/springmvc/springmvc-hibernate-many-to-many-example-annotation-using-join-table/)?

  • Dileep Kumar Kottakota

    Hi,
    Getting following error in console.

    Eclipse Console : Apr 29, 2016 6:31:56 PM org.springframework.web.servlet.PageNotFound handleHttpRequestMethodNotSupported
    WARNING: Request method ‘GET’ not supported

    Browser Console: Failed to load resource: the server responded with a status of 405 (Method Not Allowed)

    Able to access webservices from browser using
    ‘http://localhost:8085/Spring4MVCHelloWorldNoXMLDemo/user/’

    this is in user_service.js
    fetchAllUsers: function() {
    return $http.get(‘http://localhost:8085/Spring4MVCHelloWorldNoXMLDemo/user/’)
    .then(
    function(response){
    return response.data;
    },
    function(errResponse){
    console.error(‘Error while fetching users’);
    return $q.reject(errResponse);
    }
    );
    },

    Unable to call webservice from js.

    Let me know reason please..

    • Amol Jadhav

      plaese send me app.css and bootstrap.css

  • Pingback: Дивергент, глава 3: За стеной / Allegiant, Высотка / High-Rise,()

  • Pingback: film online 2016 free ua ru kz()

  • Pingback: zootopia 2016()

  • Pingback: знакомства с Украинскими девушками()

  • Ashmin Pathak

    Could anyone tell me why the equals and hashcode methods have been overrriden in the model class?

    • websystique

      Overriding hash-code & equals method are recommended if you are planning to use those objects in a container [HashMap,Set, List]. Basically, java will use your overridden methods while making decisions if two objects are equal in a given container. equal() method defines the basis[the logic] when two objects can be considered equal while hashcode() returns an integer that is guranteed to be equal for two instances of objects that are equal. You may prefer to use Apache commons lang:HashCodeBuilder/EqualBuilder for coding hashcode/equal in your application objects.

      • Ashmin Pathak

        Got it. Thanks!

  • gmarshall56

    Thank you for this. Very thorough and clean.
    WebLogic Server Version: 12.1.3.0.0:: Built and deployed succesfully.
    When accessing the url: http://localhost/Spring4MVCAngularJSExample/…..getting Error 403–Forbidden
    When accessing the url http://localhost/Spring4MVCAngularJSExample/UserManagement… getting Error 404–Not Found
    I think there needs to be a welogic.xml file included in the WAR file for running this app in Weblogic Server however I don’t know what entries should be made in that file.

  • Pingback: backlink Site List 2016()

  • FaisalHyder

    @websystique:disqus kindly sir, please update comments on your code so that we can understand your code thoroughly so that we can use it according to our project.

  • Yahalom Raviv Maimon

    hi,

    i download Luna eclipse

    i have jdk 8

    tomcat 8

    i import this project and i am getting to exceptions:

    1. One or more constraints have not been satisfied.

    2. Cannot change version of project facet Dynamic Web Module to 3.1.

    why i get it? how can i solve it?

  • FaisalHyder

    Thanks alot for such a nice and great tutorial , kindly update it with Spring boot, Gradle (for better and simplified approach) and MongoDB dataBase as backend !

    • websystique

      Hi Faisal, indeed a good combination of techs,thanks, probably something for near future.

      • FaisalHyder

        Hi there, i have successfully developed API using above mentioned technologies :) If any body needs any help feel free to ask :)

        • lakshman

          Hi Faisal, Can you please share this example with MongoDB and spring boot/

          • FaisalHyder

            Hi lakshman, i am currently working on this project, it is 95% done, i am working on file upload pages, you can have this project on GitHub (github.com/MFaisalHyder/REST_API) kindly fork and star it and keep an eye on it for all the changes i make in this project.

          • mariha noor

            in above app where is db and table name mentioned?

          • FaisalHyder

            As salam o alaikum Mariha, in above tutorial there is no Database included , have a look at the class UserServiceImpl here he is providing the static data to be displayed on the page.
            If you need any to get data from DB , like i am doing my Project kindly see mentioned above github project , i have used MongoDB and i think that using MS SQL Server for backend is more easy to use than MongoDB in spring, have a try if not done then i might help.

          • mariha noor

            Walaikumasalam, I need help in creating a Spring CRUD application connected with MySQL, since i am new to it will you help me in building the application?

          • websystique
          • FaisalHyder

            Have a look at the tutorial he gave, if still issues , you can ask, you can email me at

            mfaisalhyder@gmail.com

          • vivek

            Hi Faisal,
            I was able to successfully build your project from Git. I changed the host to my localhost and even installed mongodb locally. When i deployed i do see in my tomcat logs(check below ) that it connected to db .

            But when I lanch the app I see home page. When i click login, it throws 404 error.

            Also, does springboot automatically create “springtest” DB or do i need to create a db and even apply it’s schema? Looking for insights from you

            13:50:08.843 [cluster-ClusterId{value='57a0e56043121f29a8e5c647', description='null'}-localhost:27017] DEBUG org.mongodb.driver.cluster – Checking status of localhost:27017
            13:50:08.847 [cluster-ClusterId{value='57a0e56043121f29a8e5c647', description='null'}-localhost:27017] DEBUG org.mongodb.driver.cluster – Updating cluster description to {type=STANDALONE, servers=[{address=localhost:27017, type=STANDALONE, roundTripTime=0.6 ms, state=CONNECTED}]

          • FaisalHyder

            sprintest db needs to be created in mongodb first, then everything will be done, by application :)

          • SahanDll

            HI,
            Im new to angular js.
            Can you please tel me why i get an error saying functions in the factory cannot be accessed from the controller.
            Error: UserService.getAllCustomers is not a function

          • websystique

            Hi, perhaps your question is not related to the code from this post. Anyway,make sure that ‘getAllCustomers’ function exist in your UserService.

          • FaisalHyder

            i also suggest the same. @SahanDII

    • usebrain

      Faisal what is the use of Spring Boot?

      • FaisalHyder

        Sorry for getting late, Spring boot gives you a great advantage for not setting all useless web.xml files and you can literally save yourself from writing mind boggling xml code by just having normal java code. Other thing is that you will get tomcat server auto embedded in it.

        • usebrain

          Oh OK, let me have a look over it.

  • rysull

    Downloaded Zip. Using Spring Tool Suite I imported the zip as “existing project”. Not sure how to get the application running. I’ve done the Spring Guide to “Consuming rest APIs using AngularJS” and it worked well. Is this a slightly different approach? Thanks for help.

    • websystique

      Hi rysull, I just have Eclipse installation on my side. Anyway, It should work with STS as well. Did you check your local setup with server is fine?

  • aabb

    can any1 share a working link for a similar example…i am stuck

    • FaisalHyder

      This example is working out of the box , if you have changed or amended something in it for your own project need then it is different thing.

    • websystique

      Hi aabb, This example is indeed working [thanks Faisal]. A little bit detail from your side would be helpful to resolve your problem. Could you please explain a bit more on what error are you getting?

  • aabb

    This example is not working :( :(

    • websystique

      Hi aabb, can you explain a bit more about your problem? Did you try to see if your local setup [tomcat+eclipse] itself is fine? Have a look at this post.Additionally make sure that your eclipse internal browser configuration is up-to-date.

      • https://favoorr.github.io Jerry

        javax.servlet
        javax.servlet-api
        3.1.0
        provided

        Edit the pom.xml , And add provided ,it will be work

  • Prashant Rai

    hello in this example in angullar part
    let I want edit button on different page and text boxes of detail on different page. let I reload the page there should all should be empty in text box and
    let I click on edit then there should be all text boxes should be filled by the old data how can I do this ?
    how can I identify that when page is loading which is for edit request and which is for only reload page?

  • Pingback: How to force all my pages in Spring to https protocol [on hold] * VPN SSL Online()

  • Pingback: How to force all my pages in Spring to https protocol * VPN SSL Online()

  • Rinaldo

    I deployed the war file to heroku but I got an error of mixed content since I am request from http from a https page, how can I fix it?

  • krishn

    hi

    thanks for you post… very helpful while learning
    i liked it a lot
    i am getting 404 error …. and there is one error mark on the project and java resourse as in below screen shot. ….no errors in any file …tomcat also working fine for other projects…
    thanks for ur post

  • leonardo i

    Hi,
    I like the idea of angularJS, but do you have some solution for the SEO issue like {{title}}.
    Thanks in advance.

  • krishn

    getting Syntax error on token “.”, , expected in user_service.js

    • websystique

      Hi Krishn,

      That’s just another idiosyncrasy of Eclipse [or whatever IDE you are using], not an error. Ignore it or remove/filter out the javascript validation in your IDE.

    • leonardo i

      I resolved that changing
      return $http.delete(‘http://localhost:8080/Spring4MVCAngularJSExample/user/’+id)
      FOR
      return $http['delete'](‘http://localhost:8080/Spring4MVCAngularJSExample/user/’+id)
      Thanks.

  • Mark

    The downloaded zip file has incorrect code:

    =================================================

    self.remove = function(id){

    console.log(‘id to be deleted’, id);

    for(var i = 0; i < self.users.length; i++){

    if(self.users[i].id == id) {

    self.reset();

    break;

    }

    }

    self.deleteUser(id);

    };

    =======================================================
    instead of :

    the correct:

    self.remove = function(id){

    console.log('id to be deleted', id);

    if(self.user.id === id) {//clean form if the user to be deleted is shown there.

    self.reset();

    }

    self.deleteUser(id);

    };

    • websystique

      Hi Mark,
      Thanks for reporting that. Indeed the download had this issue. Corrected and uploaded. Thanks again.

  • Pingback: NewHindi Songs Lyrics 2016()

  • mini

    Hi,

    As others mentioned , I am also getting HTTP Status 404 error. I am using Tomcat 8 with jdk 1.8 . I have followed your post for configuring tomcat with eclipse and it is working fine(tested with other deployed apps). Please let me know where can I be wrong. Also is there any change in the pom.xml as few people mentioned in previous comments?
    Pleas help.

  • Srinivas P

    Hi,
    Please tell me how to implement pagination for the above example.

    • websystique

      Hi Srinivas, For pagination you can use popular ng-table plugin.Their documentation explains how to plug it in to your application.

      • Srinivas P

        Hi

        Thank u for replying I had implemeted it by using dirPagination.js and successfully deployed.

  • Bhakavathy Adithan

    Hi,

    The application works fine with Tomcat but with Weblogic it shows 404. This occurs for every @Configuration projects. If we change the project to XML based then it works flawlessly. Could you please provide your inputs

  • Andrada Popa

    Hello,
    I took the AngularJS part and I added to my project but it’s not working properly. I can add a user, but the existing users don’t appear in the table. I don’t know what is going on. Can you help me please?
    My backend is ok, because I tested it wih a REST client and it’s working fine. Even when I run the project with Tomcat it shows me in the console that my database is accessed, but my view is not updated.
    I am thinking that something is happening there, because the EDIT and DELETE button appear. Here is a printscreen.

    Thank you in advance,
    Andrada

  • knack of flying

    I was able to make the web page come up, but the urls to render the data are not working.
    they are not rendering any json data either on the webpage nor by hitting the url.
    Any advice would be greatly appreciated.

    thanks

    • websystique

      Hi,

      Open Developer tools in your browser, go to network tab and check if you are even getting response from server. If you are running from within Eclipse, make sure that your local tomcat setup is working. For setup, please follow Setup Tomcat With Eclipse. Let me know if you still face issue.

      • knack of flying

        I checked with the developer tools. I’m not getting any response from the server for the http://localhost:8080/Spring4MVCAngularJSExample/user/ . This returns a 404 even in the browser. Bottom line – this mapping is not working.

        • websystique

          Hi, As i mentioned above, you need to check your tomcat+eclipse setup.

          • maarc

            I have the same issue. I modified the tomcat server locations and added to project to the tomcat.When i run the project. I cannot set any list of users, in the page.I printed the list to the eclipse.i results are good. But there is no data being sent to the page.

            And if i try adding a user the data is being sent is null.
            Please help me in this issue.

          • websystique

            Hi Marc, Did you try to build and deploy to an external tomcat instance, to be sure that it’s not your eclipse+tomcat setup which is creating issue? Also, please open developer tools->Network and check the response for http requests.

  • Srinivas P

    Hi,
    I am trying to implement a functionality which is when i want to delete particular record it must show an alert message saying are you sure do u want to continue.
    But angular.js is their in remote files how should i specify using any idea please ping me ??

    • websystique

      Hi Srinivas, What do you mean by angularjs is in remote files? You can simply attach a controller property(confirm e.g.) to set it true/false based on what user have chosen, and then send, an HTTP DELETE to server.

  • Deepak Burnwal

    Where is web.xml ?

    • websystique

      It’s Servlet 3.x application, no web.xml required.Everything you provide in web.xml can be configured in HelloWorldInitializer.

      • Deepak Burnwal

        I set up tomcat 8 in my elipse and directly tried to run on server. No luck !!! Not working. Can you please help me on this?

        • websystique

          Hi Deepak,
          Probably your local Eclipse+Tomcat setup is not configured properly. Please follow Setup Tomcat With Eclipse. Let me know if you still face issue.

          • Manas Naik

            If we develop normal dynamic web project then its working.there might be Maven dependency is there.

  • Texan Rock

    set my jdk to 1.8 and mvn it. deploy to tomcat 8 and it is working

  • narayanam

    It seems this should be run on the following platform
    Java 8
    JRE 1.8
    Tomcat 8
    And added the following plugin in pom.xml

    org.apache.maven.plugins
    maven-compiler-plugin
    3.3

    true
    true
    ${JAVA_HOME}binjavac
    1.8
    1.8
    1.8

    I got 404 error initially when I tried to run it on JRE 1.8 Tomcat 7.

    • websystique

      Hi Narayanam,
      Probably your local Eclipse+Tomcat setup is not configured properly. Please follow Setup Tomcat With Eclipse. Let me know if you still face issue.

      • narayanam

        I actually got it fixed and working with the above mentioned config.

        BTW initially when I was facing the problem, Eclipse and Tomcat 7 was working perfectly fine with other applications.

        • websystique

          Great.

          • narayanam

            Thanks a lot for posting such a good example and quick response to any request for help!!

          • websystique

            Glad it was helpful.

  • Srinivas P

    Hi ,
    After adding the data ,the data is not showing in the list. can help me ???

    • websystique

      Hi Srinivas, Could you provide bit more information on your problem? Could you open the Developer tools and check what happens once you add the user. Once clicking on Add, you should see two request to server : first one sending data to server, followed by second one asking a list of users from server.

      • http://hendisantika.wordpress.com Hendi Santika

        I have same issue like Srinivas.

        • http://hendisantika.wordpress.com Hendi Santika

          Oooo.. Now I know the problem.

          The problem is the service is not there.

          But, when I delete teh context path ‘Spring4MVCAngularJSExample’ the url on user_service.js . the service is OK.

          • websystique

            Hi Hendi, you should’t be deleting context path just like that. Problem is not the context path, but your server/service communication. And service need the URL with context path in order to communicate with server.

          • http://hendisantika.wordpress.com Hendi Santika

            But, When I change the Context Path the Program is OK and all the service is just fine. CRUD services work well.

  • Pingback: Spring 4 MVC+AngularJS CRUD Application using ngResource - WebSystique()

  • Pingback: AngularJS $http service example-server communication - WebSystique()

  • manjeer

    Registered user can Create, Edit, Comment, Add Photo, and the photo should be show on web not in the file format that showing above please healp on this

  • Nitya Nanda

    your application is perfectly amazing and requesting you to please add pagination in the above example,

  • Nag

    Hi,

    I downloaded the application and I have run it,but I am getting issue like

    HTTP Status 404 – /Spring4MVCAngularJSExample. And in the project didn’t used web.xml.Please suggest me what is wrong going here.I have setup requirements in POM.xml as you given.

    Thanks,
    Nag

    • websystique

      Hi, Are you trying to run it via tomcat integrated within Eclipse? Then please make sure that your eclipse+tomcat setup itself is working fine. This Post will help you for that. For your other question : there is no web.xml required as it is for Servlet 3.x environment. Any other issue, let me know.

      • Nag

        Thanks for your quick response.

        I used eclipse Luna+tomcat8 and configured but still getting the same issue i.e

        HTTP Status 404 – /Spring4MVCAngularJSExample.

        Thanks,
        Nag

        • websystique

          Did you try to deploy any dummy project [a simple hello world app e.g.] with your setup & checked if it is working. It seems to be setup related.

          • Nag

            Hi,

            Thank you, now application is running successfully.Previously I didn’t applied This Post configurations, I was tried to run application asusual in eclipse.

            Thanks,
            Nag

          • websystique

            That’s great. You may also like AngularJS blog which explains each concept in detail.

  • Pingback: Spring MVC 4 File Download Example - WebSystique()

  • Pingback: Spring 4 MVC Form Validation and Resource Handling (Annotations) - WebSystique()

  • Pingback: Spring 4 MVC REST Service Example using @RestController - WebSystique()

  • Pingback: Spring MVC 4 RESTFul Web Services CRUD Example+RestTemplate - WebSystique()

  • Ernesto Antonio Rodriguez Acos

    Hi,
    I downloaded the project code (I’m using MyEclipse 2015) and I was able to running after make the deployment in Tomcat 7.
    After some searchs to get the right pom.xml, I was able to get the application running.
    For those that were in the same situation, here is the code for the pom.xml:

    4.0.0
    com.websystique.springmvc
    Spring4MVCAngularJSExample
    war
    1.0.0
    Spring4MVCAngularJSExample Maven Webapp




    ${project.build.directory}/endorsed
    3.1
    2.1
    2.8
    2.4

    4.2.0.RELEASE
    4.1.4.RELEASE
    2.5.3
    3.1.0
    1.2
    1.2

    org.springframework
    spring-core
    ${springframework.version}

    org.springframework
    spring-context
    ${springframework.version}

    org.springframework
    spring-beans
    ${springframework.version}

    org.springframework
    spring-web
    ${springframework.version}

    org.springframework
    spring-webmvc
    ${springframework.version}

    org.springframework
    spring-tx
    ${springframework.version}

    org.springframework
    spring-expression
    ${springframework.version}

    org.springframework
    spring-aop
    ${springframework.aop.version}

    com.fasterxml.jackson.core
    jackson-core
    ${jackson.version}

    com.fasterxml.jackson.core
    jackson-annotations
    ${jackson.version}

    com.fasterxml.jackson.core
    jackson-databind
    ${jackson.version}

    javax.servlet
    javax.servlet-api
    ${javax.servlet-api.version}
    provided

    javax.servlet
    jstl
    ${jstl.version}

    commons-logging
    commons-logging
    ${commons.login.version}

    org.apache.maven.plugins
    maven-compiler-plugin
    ${maven.compiler.plugin.version}

    compile
    compile

    compile

    1.7
    1.7

    ${endorsed.dir}

    org.apache.maven.plugins
    maven-dependency-plugin
    ${maven.dependency.plugin.version}

    copy-endorsed
    validate

    copy

    ${endorsed.dir}
    true

    javax
    javaee-endorsed-api
    7.0
    jar

    copy-all-dependencies
    compile

    copy-dependencies

    ${project.build.directory}/lib
    compile

    org.apache.maven.plugins
    maven-war-plugin
    ${maven.war.plugin.version}

    false

    org.eclipse.m2e
    lifecycle-mapping
    1.0.0

    org.apache.maven.plugins
    maven-dependency-plugin
    [1.0.0,)

    copy-dependencies
    copy

    Spring4MVCAngularJSExample

  • nmpg

    I still have the same issue. I get Forbidden 403 when accessing http://localhost:7001/Spring4MVCAngularJSExample/, and Not Found 404 for http://localhost:7001/Spring4MVCAngularJSExample/user/

    Any advice?

    • nmpg

      I also have ‘jsp package javax.servlet.jsp does not exist’ error at UserManagement.jsp, I guess it is related… But how can I fix that?

      I saw some forum posts suggesting changing javax.servelet scope’s in pom.xml to ‘provided’. but alas it did not help..

      • websystique

        Hi nmpg,

        Did you succeed deploying any project (a simple spring based hello wold e.g.) with your setup (you were using weblogic i remember) and see if your setup itself is fine?

        Have you additionally tried to deploy this project(or any other project) on tomcat instance, as mentioned here, to see if tomcat setup works fine at your end(it must because it works). Additionally, as i asked you , please have a look at this post.

        For JSP errors, if your server does not include it( i doubt it though), you can include the dependency (just remove ‘provided’ scope). You can refer to this post to find necessary dependencies.

        If it still does not solve your issue, i will try to setup weblogic at my end and look into it, but first please do try to perform the task i mentioned.

        • nmpg

          Hi.

          Yes, In the past I deployed projects (my own and from here) successfully.. Not sure why this is happening now..

          Probably this is a simple dependency issue with Maven, but I don’t know how I can fix it..

          Also tried changing the ‘provided’ to ‘compile’ scope, still, no luck

    • Geeth Lochana

      Is it your war file “Spring4MVCAngularJSExample.war” after build?

  • Pingback: Spring 4 MVC+Hibernate Many-to-many JSP Example with annotation - WebSystique()

  • Pingback: Spring 4 MVC+Hibernate 4+MySQL+Maven integration example using annotations - WebSystique()

  • Urstruly Tom

    This example is working in Chrome. But not in IE. The problem in IE is the Grid is not updating when you perform any action (add, update, delete). Any reason for this behavior?

    • websystique

      Hi Tom,

      First of All, thanks for reporting it. I have indeed tested it on chrome and Firefox only.
      However, Angular latest versions are OFFICIALLY not supporting IE out-of-box anymore, and some work needs to be done from Developers side to avoid [Or FEED???] IE idiosyncrasy. This will be in my TODO list.