Spring Boot with Angular Js Part 1

by Anand


Posted on : 01 Jan 2018

Required Tool : Apache Maven, Spring Tool Suite (optional), Java Development Kit. 

  1. Use Spring Too Suite to create application. You can also use http://start.spring.io/ to create spring boot application which provides same user interface.

  2. So Let’s start with Spring tool Suite.

  3. Goto File -> New -> Spring Starter Project.

  4. Provide Project Name, Group, Artifact and Package as i have mentioned. We will be creating Executable Jar file so packaging will be Jar file and type will be Maven as we are creating maven based project. Have a look below Screenshot.  

 

  

6) Now in Next Screen select dependencies for your project. Select  

Web dependencies to create Rest Endpoint,

H2 for in memory database, (Later i will change it to PostgresSQL or MYSQL)

JPA to persist entity class into database.

 

7) Then click on Next and Finish.

8) This is how my project structure looks like.

src  folder contains all required classes.

resources will contains application.properties file.

pom.xml contains information about the project , configuration details and dependencies used by Maven to build the project.

 

Now follow below steps to create application.

  1. Create Post entity class with required field.

  2. Store few entries in in memory database.

  3. Create Post Repository to fetch data from database.

  4. Create Rest EndPoint which get data from database and provide data in Json form.

 

So right click on src and create new package com.blog.domain.

 

And then create Post entity class.

 

package com.blog.domain;

import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;

@Entity
public class Post {

    @Id @GeneratedValue
    private Long id;
    
    @NotEmpty
    private String title;        

    @NotNull
    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat ( pattern="M/dd/yyyy hh:mm:ss a")
    private Date postedOn;    
        
    private Boolean active;
        
    @NotEmpty
    @Column(length=10485760)
    private String body;
        
    
    public Post(){
        this.postedOn = new Date();
        this.active = true;        
    }
    
    public Post(String title){
        this.setTitle(title);
    }    
    

    public Date getPostedOn() {
        return postedOn;
    }

    public void setPostedOn(Date postedOn) {
        this.postedOn = postedOn;
    }

    public Boolean getActive() {
        return active;
    }

    public void setActive(Boolean active) {
        this.active = active;
    }

    public Long getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }
}

 

7) Now Create PostRepository class under com.blog.repository which provide CRUD operation method.

 

package com.blog.repository;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.blog.domain.Post;

@Repository
public interface PostRepository extends CrudRepository<Post, Long> {
}

8) Now Create PostController class under com.blog.controller package. This class will provide Rest Endpoint. 

package com.blog.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
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;
    }
    
    @RequestMapping("/posts")
    public List<Post> getListOfPost(){
        List<Post> posts = (List<Post>) postRepository.findAll();            
        return posts;
    }    

}
 

9) Now before we start application, we need to persist few entries into database. So goto BlogApplication.java main class. You can use CommandLineRunner to persist few entries into database before you run your application. In inmemory database data will remain as long as your application is running.

So my MainClass will look like this. 

package com.blog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import com.blog.domain.Post;
import com.blog.repository.PostRepository;

@SpringBootApplication
public class BlogApplication {
        
    @Autowired
    private PostRepository pr;
    
    public BlogApplication(PostRepository pr){        
        this.pr = pr;
    }

    public static void main(String[] args) {
        SpringApplication.run(BlogApplication.class, args);
    }
    
        @Bean
        CommandLineRunner runner(){
            return new CommandLineRunner() {
                
                @Override
                public void run(String... arg0) throws Exception {
                    
                    Post post1 = new Post();
                    post1.setTitle("Blog Post 1");
                    post1.setBody("Blog Body 1");
                    pr.save(post1);
                    
                    Post post2 = new Post();
                    post2.setTitle("Blog Post 2");
                    post2.setBody("Blog Body 2");
                    pr.save(post2);
                    
                    Post post3 = new Post();
                    post3.setTitle("Blog Post 3");
                    post3.setBody("Blog Body 3");
                    pr.save(post3);
                }
            };
        }
}

 

Now let’s Run Main class. Right click on BlogApplication.java class and run as spring boot App.

10) open browser and goto http://localhost:8080/posts

 

In URL last “/posts” is mapto getListOfPost() method in PostController class. So it will call getListOfPost() method. Fetch List<Post> from database and provide JSON data as output.

Have a look Screenshot.

Now let’s create HTML, AngularJs application to consume this service and display data in UI.

 

11) create index.html file under resource/static folder and paste below code. 

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="app.js"></script>
<body>
<div ng-app="blog" ng-controller="blogController">
    <table width="100%" border="1">
          <tr ng-repeat="post in listOfPost">
            <td>{{ post.title }}</td>
            <td>{{ post.body }}</td>
          </tr>
    </table>
</div>
</body>
</html>

and Then,

 

12) create app.js file and paste below code. 

 

var app = angular.module('blog', []);
app.controller('blogController', function($scope, $http) {
    
     $http.get("/posts")
        .then(function(response) {
            $scope.listOfPost = response.data;
     });
});

Then right click on main class and run the app. you will be able to see data in index.html page render by AngularJS.

Have a look Screenshot. 

You can clone Git project https://github.com/anandgajjar2004/SpringBootBlog here.

(Part1 Folder)