HTML 5 – Web LocalStorage Cache + AngularJS + SpringBoot RestAPIs

In the tutorial, JavaSampleApproach will show you how to use HTML 5 – Web LocalStorage to store data locally within the user’s browser for caching purpose with AngularJs and SpringBoot RestAPI.

Related posts:
HTML 5 – Web SessionStorage Cache + AngularJS + SpringBoot RestAPIs
AngularJs Table display Data Objects from RestAPIs remote | SpringBoot & BootStrap

I. Technologies

– Java 1.8
– Maven 3.6.1
– Spring Tool Suite – Version 3.9.0.RELEASE
– HTML 5
– AngularJS
– Bootstrap
– Spring Boot – 1.5.9.RELEASE

II. Goal

In the tutorial, We use Html 5 Web LocalStorage and AngularJs to cache data from SpringBoot RestAPI:

if(typeof(Storage) !== "undefined" // check Web Storage support
	&& localStorage.getItem("listOfCustomers") !== null){ // check listOfCustomers is cached in localStorage before
	
	console.log("--- Load From LocalStorage ---");
	
	// get cached listOfCustomers in Web-LocalStorage
	$scope.listCustomers = JSON.parse(localStorage.getItem('listOfCustomers'));
}else{
	...
	
	// do getting
	$http.get(url).then(function (response) {
		
		// store listOfCustomers to Web-LocalStorage
		localStorage.setItem('listOfCustomers', JSON.stringify(response.data));
	}
	...
}

We build a SpringBoot project as below:

Html 5 Web LocalStorage - AngularJs + SpringBoot RestAPI - project structure

Run and check results:
– Make a first request:

Html 5 Web LocalStorage - AngularJs + SpringBoot RestAPI - result

-> It loads data from SpringBoot back-end : /api/customer/all

Html 5 Web LocalStorage - AngularJs + SpringBoot RestAPI - log request

-> Then store result as key/value in localStorage:

Html 5 Web LocalStorage - AngularJs + SpringBoot RestAPI - localstorage

– shutdown then start user’s browser again. Make the request http://localhost:8080, the web application uses caching data from localStorage to display:

Html 5 Web LocalStorage - AngularJs + SpringBoot RestAPI - console log message

III. Practice

Step to do:
– Create Spring Boot project
– Create data models
– Implement Web Controller
– Implement RestAPI
– Implement index view
– Implement AngularJs application

1. Create Spring Boot project

Use SpringToolSuite to create a SpringBoot project with dependencies:


	org.springframework.boot
	spring-boot-starter-thymeleaf


	org.springframework.boot
	spring-boot-starter-web

2. Create data models

– Create Address model:

package com.javasampleapproach.weblocalstorage.model;
 
public class Address {
	 
	private String street;
	private String postcode;
	
	public Address(){}
	
	public Address(String street, String postcode){
		this.street = street;
		this.postcode = postcode;
	}
 
	public String getStreet() {
		return street;
	}
 
	public void setStreet(String street) {
		this.street = street;
	}
 
	public String getPostcode() {
		return postcode;
	}
 
	public void setPostcode(String postcode) {
		this.postcode = postcode;
	}
 
	@Override
	public String toString() {
		return "Address {street:" + street + ", postcode:" + postcode + "}";
	}
}

– Create Customer model:

package com.javasampleapproach.weblocalstorage.model;
 
public class Customer {
	private Long id;
	private String name;
	private Integer age;
	private Address address;
	
	public Customer(){}
	
	public Customer(Long id, String name, Integer age, Address address){
		this.id = id;
		this.name = name;
		this.age = age;
		this.address = address;
	}
 
	public Long getId() {
		return id;
	}
 
	public void setId(Long id) {
		this.id = id;
	}
	
	public String getName() {
		return name;
	}
 
	public void setName(String name) {
		this.name = name;
	}
 
	public Integer getAge() {
		return age;
	}
 
	public void setAge(Integer age) {
		this.age = age;
	}
 
	public Address getAddress() {
		return address;
	}
 
	public void setAddress(Address address) {
		this.address = address;
	}
 
	@Override
	public String toString() {
		return "Customer {name:" + name + ", age:" + age + ", address:" + address + "}";
	}
 
}
3. Implement Web Controller
package com.javasampleapproach.weblocalstorage.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
 
@Controller
public class WebController {
 
	@GetMapping(value="/")
    public String homepage(){
        return "index";
    }
}
4. Implement RestAPI
package com.javasampleapproach.weblocalstorage.controller;
 
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
 
import javax.annotation.PostConstruct;
 
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
import com.javasampleapproach.weblocalstorage.model.Address;
import com.javasampleapproach.weblocalstorage.model.Customer;
 
 
@RestController
@RequestMapping("/api/customer")
public class RestAPIs {
	
	Map custStores = new HashMap();
	
	@PostConstruct
    public void initIt() throws Exception {
        custStores.put(Long.valueOf(1), new Customer(new Long(1), "Jack", 25, new Address("NANTERRE CT", "77471")));
        custStores.put(Long.valueOf(2), new Customer(new Long(2), "Mary", 37, new Address("W NORMA ST", "77009")));
        custStores.put(Long.valueOf(3), new Customer(new Long(3), "Peter", 18, new Address("S NUGENT AVE", "77571")));
        custStores.put(Long.valueOf(4), new Customer(new Long(4), "Amos", 23, new Address("E NAVAHO TRL", "77449")));
        custStores.put(Long.valueOf(5), new Customer(new Long(5), "Craig", 45, new Address("AVE N", "77587")));
    }
	 
	@GetMapping(value = "/all")
	public List getResource() {
		
		List custList = custStores.entrySet().stream()
		        .map(entry -> entry.getValue())
		        .collect(Collectors.toList());
		
		return custList;
	}
}
5. Implement index view

 


	  AngularJs PUT Form Nested Object to SpringBoot Example
	  
	  %MINIFYHTML8a7674da27d0fcf82c30d90e9e49060216%%MINIFYHTML8a7674da27d0fcf82c30d90e9e49060217%

 

Customer List:

No Name Age Street PostCode
{{ $index + 1 }} {{ cust.name | uppercase}} {{ cust.age}} {{ cust.address.street}} {{ cust.address.postcode}}
%MINIFYHTML8a7674da27d0fcf82c30d90e9e49060218%
6. Implement AngularJs application
var app = angular.module('app', []);
 
//#######################
//JSA CONTROLLER
//#######################
 
app.controller('jsaController', function($scope, $http, $location) {

	$scope.listCustomers = [];
	$scope.getDivAvailable = false;

	function getAllCustomer(){
		
		if(typeof(Storage) !== "undefined" // check Web Storage support
			&& localStorage.getItem("listOfCustomers") !== null){ // check listOfCustomers is cached in localStorage before
			
			console.log("--- Load From LocalStorage ---");
			
			// get cached listOfCustomers in Web-LocalStorage
			$scope.listCustomers = JSON.parse(localStorage.getItem('listOfCustomers'));
			$scope.getDivAvailable = true;
		}else{
			// get URL
			var url = $location.absUrl() + "api/customer/all";
			
			// do getting
			$http.get(url).then(function (response) {
				$scope.getDivAvailable = true;
				$scope.listCustomers = response.data;
				
				// store listOfCustomers to Web-LocalStorage
				localStorage.setItem('listOfCustomers', JSON.stringify($scope.listCustomers));
			}, function error(response) {
				$scope.postResultMessage = "Error Status: " +  response.statusText;
			});	
		}
		
	}
	
	getAllCustomer();
});

IV. Sourcecode

SpringBootCachingWithHtml5WebLocalStorage



By grokonez | November 29, 2017.


Related Posts


Got Something To Say:

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

*