Kotlin SpringBoot RestAPI – AngularJs Ajax POST/GET messages – style with Bootstrap 4

In the tutorial, JavaSampleApproach will show you how to create a web application with Kotlin SpringBoot RestAPI, AngularJs Ajax POST/GET messages and styling with Bootstrap 4.

I. Technologies

– Java 1.8
– Maven 3.6.1
– Spring Tool Suite – Version 3.9.0.RELEASE
– Bootstrap 4
– AngularJs
– Spring Boot – 1.5.9.RELEASE
– Kotlin

II. Goal

We create a Kotlin SpringBoot project that uses AngularJs Ajax to Post/Get messages, the project as below structure:

Kotlin SpringBoot with AngularJs Ajax Post-Get messages + BootStrap 4 - project structure

Run & check results
-> post message:

Kotlin SpringBoot with AngularJs Ajax Post-Get messages + BootStrap 4 - post logs request

-> get message:

Kotlin SpringBoot with AngularJs Ajax Post-Get messages + BootStrap 4 - get logs request

-> result:

Kotlin SpringBoot with AngularJs Ajax Post-Get messages + BootStrap 4 - result

III. Practice

Step to do:
– Create Kotin SpringBoot project
– Create Customer model
– Implement Index view Controller
– Implement RestAPIs
– Create index view
– Implement AngularJs Post/Get script

1. Create Kotin SpringBoot project

Use SpringToolSuite to create SpringBoot project with Kotlin language, see dependencies as below:

<properties>
	<kotlin.compiler.incremental>true</kotlin.compiler.incremental>
	<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
	<java.version>1.8</java.version>
	<kotlin.version>1.1.61</kotlin.version>
</properties>

<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-thymeleaf</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
	<dependency>
		<groupId>org.jetbrains.kotlin</groupId>
		<artifactId>kotlin-stdlib-jre8</artifactId>
		<version>${kotlin.version}</version>
	</dependency>
	<dependency>
		<groupId>org.jetbrains.kotlin</groupId>
		<artifactId>kotlin-reflect</artifactId>
		<version>${kotlin.version}</version>
	</dependency>

	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<scope>test</scope>
	</dependency>
</dependencies>

<build>
	<sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
	<testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
	<plugins>
		<plugin>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-maven-plugin</artifactId>
		</plugin>
		<plugin>
			<artifactId>kotlin-maven-plugin</artifactId>
			<groupId>org.jetbrains.kotlin</groupId>
			<version>${kotlin.version}</version>
			<configuration>
				<compilerPlugins>
					<plugin>spring</plugin>
				</compilerPlugins>
				<jvmTarget>1.8</jvmTarget>
			</configuration>
			<executions>
				<execution>
					<id>compile</id>
					<phase>compile</phase>
					<goals>
						<goal>compile</goal>
					</goals>
				</execution>
				<execution>
					<id>test-compile</id>
					<phase>test-compile</phase>
					<goals>
						<goal>test-compile</goal>
					</goals>
				</execution>
			</executions>
			<dependencies>
				<dependency>
					<groupId>org.jetbrains.kotlin</groupId>
					<artifactId>kotlin-maven-allopen</artifactId>
					<version>${kotlin.version}</version>
				</dependency>
			</dependencies>
		</plugin>
	</plugins>
</build>

2. Create Customer model


package com.javasampleapproach.angularjsajax.model

data class Customer(
		val firstname : String = "",
        val lastname  : String = "",
		val age :Int = 0
){}

3. Implement Index view Controller


package com.javasampleapproach.angularjsajax.controller

import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.GetMapping

@Controller
class WebController {
	
    @GetMapping(value="/")
    fun homepage() : String {
        return "index";
    }
}

4. Implement RestAPIs


package com.javasampleapproach.angularjsajax.controller

import com.javasampleapproach.angularjsajax.model.Customer
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RestController

@RestController
class RestWebController {
 
	val custStore = mutableListOf()
 
	@GetMapping(value = "/getallcustomer")
	fun getResource() : List{
		return custStore;
	}
 
	@PostMapping(value = "/postcustomer")
	fun postCustomer(@RequestBody customer: Customer) : String{
		custStore.add(customer);
		return "Post sucessfully!" + " - " + customer.firstname;
	}
}

5. Create index view

– Create index.html view with Bootstrap 4:

<!DOCTYPE HTML>

<html  lang="en">
<head>
	  <title>AngularJs + Kotlin SpringBoot + Bootstrap 4</title>
	  <meta charset="utf-8" />
  	  <meta name="viewport" content="width=device-width, initial-scale=1" />
	  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
	  <script src="/js/angularJsApp.js"></script>
	  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" />
  	  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.6/umd/popper.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container" ng-app="app">

	<h6 style="color:blue; margin-top:10px">AngularJs + Kotlin SpringBoot + Bootstrap 4</h6>
	<div class="row">
	<div class="col-sm-4">
	<div ng-controller="postcontroller">
		<form name="customerForm" ng-submit="submitForm()">
			<div class="form-group">
				<label for="firstname">FirstName:</label>
				<input type="text" class="form-control" id="firstname" placeholder="Enter FirstName" ng-model="firstname"/>
			</div>
			<div class="form-group">
				<label for="lastname">LastName:</label>
				<input type="text" class="form-control" id="lastname" placeholder="Enter LastName" ng-model="lastname"/>
			</div>
			<div class="form-group">
				<label for="age">Age:</label>
				<input type="number" class="form-control" id="age" placeholder="Enter Age" ng-model="age"/>
			</div>
			<button type="submit" class="btn btn-outline-primary btn-sm">Post Customer</button>
		</form>

		<div style="margin-top:5px; margin-bottom:5px">
			<p>{{returnMessage}}</p>
		</div>
	</div>
	
	<div style="margin-bottom:5px; margin-bottom:5px" ng-controller="getcontroller">
		<button id="btn-id" type="button" class="btn btn-outline-info btn-sm" ng-click="getfunction()">Get Customers</button>
		<ul style="margin-top:5px">
        	<li ng-repeat="cust in customerList">{{"fullname: " + cust.firstname + " " + cust.lastname + ", age = " + cust.age}}</li>
    	</ul>
	</div>
	</div>
	</div>
</div>
</body>
</html>

6. Implement AngularJs Post/Get script

We implement 2 AngularJs controllers postcontroller, and getcontroller:


var app = angular.module('app', []);
app.controller('postcontroller', function($scope, $http, $location) {
	$scope.submitForm = function(){
		var url = $location.absUrl() + "postcustomer";
		
		// configure text return
		var config = {
                headers : {
                    'Accept': 'text/plain'
                }
        }
		
		// prepare data
		var data = {
            firstname: $scope.firstname,
            lastname: $scope.lastname,
            age: $scope.age
        };
		
		// do post to remote-server
		$http.post(url, data, config).then(function (message) {
			$scope.returnMessage = message.data;
		}, function error(response) {
			$scope.returnMessage = "Error";
		});
		
		// reset input data in view
		$scope.firstname = "";
		$scope.lastname = "";
		$scope.age = "";
	}
});

app.controller('getcontroller', function($scope, $http, $location) {
	$scope.getfunction = function(){
		var url = $location.absUrl() + "getallcustomer";
		
		$http.get(url).then(function (response) {
			$scope.customerList = response.data;
		}, function error(response) {
			$scope.returnMessage = "Error";
		});
	}
});

IV. Sourcecode

KotlinSpringBootAngularJsAjaxClient

2 thoughts on “Kotlin SpringBoot RestAPI – AngularJs Ajax POST/GET messages – style with Bootstrap 4”

Leave a Reply

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