Spring Boot with Angular Js Part 2

by Anand


Posted on : 01 Feb 2018

1) Now let's Update PostController class. Create New method for Create, Update and Delete Post.

package com.blog.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
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 com.blog.domain.Post;
import com.blog.repository.PostRepository;

@RestController
public class PostController {
    
    @Autowired
    private PostRepository postRepository;
    
    public PostController(PostRepository postRepository){        
        this.postRepository = postRepository;
    }
    
    /*
     * Get List of Post 
     */
    @RequestMapping(value = "/posts", method= RequestMethod.GET)
    public List<Post> getListOfPost(){
        List<Post> posts = (List<Post>) postRepository.findAll();            
        return posts;
    }
    
    /*
     * POST Method which accept Post object 
     * Persist Post object into database.
     * return Post object with Id.  
     */
    @RequestMapping(value = "/post", method = RequestMethod.POST)
    public Post savePost(@RequestBody Post post) {                
        return postRepository.save(post);            
    }
    
    /*
     * GET  Method which accept id 
     * get Post object from database using Id.
     * return Post object.  
     */
    @RequestMapping(value="/post/{id}",method = RequestMethod.GET)
    public Post getPostById(@PathVariable(value="id") Long id){        
        return postRepository.findOne(id);
    }
    
    /*
     * DELETE Method which accept id 
     * delete Post object from database using Id.
     * return Success Message.  
     */
    @RequestMapping(value="/post/{id}", method = RequestMethod.DELETE)
    public Map<String, String> deletePostById(@PathVariable Long id) {
        Map<String, String> message = new HashMap<String,String>();
        postRepository.delete(id);
        message.put("message", "Post Deleted Successfully");
        return message;
    }
    
      /*
      * PUT Method which accept id and Post object.  
      * update Post object into database.
      * return Updated Post object.  
      */
      @RequestMapping(value="/post/{id}", method=RequestMethod.PUT)
      public Post updatePost(@PathVariable Long id, @RequestBody Post post) {
        Post update = postRepository.findOne(id);
        update.setTitle(post.getTitle());
        update.setBody(post.getBody());               
        return postRepository.save(update);
      }
}

 

2) Now we will do some changes at UI side. app.js will contain only below line. 

var app = angular.module('blog', [ 'ngRoute']);

 

3)  Create new angular-routes.js file and add below code.

app.config(function($routeProvider) {
    $routeProvider.when('/posts/', {
        templateUrl : 'pages/listOfPost.html',
        controller : 'ListOfPostController'
    }).when('/post/new', {
        templateUrl : 'pages/addPost.html',
        controller : 'AddPostController'
    }).when('/post/:id', {
        templateUrl : 'pages/viewPost.html',
        controller : 'ViewPostController'
    }).otherwise({
        redirectTo : '/posts'
    });
});

 

4)  Create new angular-controllers.js file and add below code.

app.controller('blogController', function($scope, $http) {

});

app.controller('ListOfPostController', function($scope, $http, $location) {

    $http.get("/posts").then(function(response) {
        $scope.listOfPost = response.data;
    });

    $scope.deletePost = function(id) {
        $http({
            method : "DELETE",
            url : "/post/" + id
        }).then(function(response) {
            alert(response.data["message"]);
            window.location.reload();
        }, function(error) {

        });
    }
});

app.controller('AddPostController', function($scope, $http) {

    $scope.fields = {
        title : '',
        body : ''
    };
    
    $scope.createPost = function(fields) {
        $http({
            method : "POST",
            url : "/post/",
            data : fields,
            headers : {
                'Content-Type' : 'application/json'
            }
        }).then(function(result) {
            alert("Post Created Successfully");
            window.history.back();
        }, function(error) {
            console.log(error);
        });
    }
});

app.controller('ViewPostController', function($scope, $http, $routeParams) {

    $scope.id = $routeParams.id;
    $http.get("/post/" + $scope.id).then(function(response) {
        $scope.fields = response.data;
    });

});
 

 

5)  Update index.html file with below changes. 

  • Add new angular js file. (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js)
  • Add new user define angular-routes js file.  Add all required page into this file. 
  • Add angular-controllers js file. Add all required controller into this file. 
  • This is single page application. So in below code only <div ng-view></div> will keep on changing depending on which page you click. 

<html>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>
    <script src="app.js"></script>
    <script src="angular-routes.js"></script>
    <script src="angular-controllers.js"></script>
<body>
    <div ng-app="blog" ng-controller="blogController">
        <div ng-view></div>
    </div>
</body>
</html>

 

6) Create "pages" Folder under static folder and create 3 below  HTML page under pages folder.  

addPost.html (contain create form and on click of Create button it call createPost method under AddPostController. 

<div class="container">
    <div class="row">
        <div class="panel-heading">
            <h3 class="panel-title">Add Post</h3>
        </div>
        <div class="panel-body">
            <form name="form" class="form-horizontal">
                <fieldset>

                    <div class="form-group">
                        <label class="col-lg-3 control-label">Title: </label>
                        <div class="col-lg-9">
                            <input name="title" ng-model="fields.title" type="text"
                                class="form-control" required>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-lg-3 control-label">Body: </label>
                        <div class="col-lg-9">
                            <textarea name="body" ng-model="fields.body" class="form-control"
                                rows="3" required></textarea>
                        </div>
                    </div>

                    <div class="form-group">
                        <div class="col-lg-9 col-lg-offset-3">
                            <button ng-click="createPost(fields);" type="submit"
                                class="btn btn-primary">Create</button>
                        </div>
                    </div>
                </fieldset>
            </form>
        </div>
    </div>
</div>

 

listOfPost.html ( display list of post and on click of Delete it will call depetePost function under ListOfPostController. 

<table width="100%" border="1">
    <tr ng-repeat="post in listOfPost">
        <td>{{ post.title }}</td>
        <td>{{ post.body }}</td>
        <td width="10%"><a href="#/post/{{post.id}}">View</a></td>
        <td width="10%"><a href="#" ng-click="deletePost(post.id);">Delete</a></td>
    </tr>
</table>
<a href="#/post/new">Create New Post</a>

 

viewPost.html ( view Post by pasing id into URL )

<table>
    <tr>
        <td>Title :</td>
        <td>{{fields.title}}</td>
    </tr>
    <tr>
        <td>Body :</td>
        <td>{{fields.body}}</td>
    </tr>
</table>

 

https://github.com/anandgajjar2004/SpringBootBlog (Part2 Folder)