HTML 5 – Web LocalStorage + JQuery to Cache data from SpringBoot RestAPIs

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

Related posts:
JQuery uses Bootstrap Table to display data from SpringBoot RestAPI
HTML 5 – Web SessionStorage + JQuery to Cache data from SpringBoot RestAPIs
Html5 DateTime + AngularJs + SpringBoot @JsonFormat example

I. HTML 5 – Web LocalStorage

With HTML 5 – Web LocalStorage, web applications can store data locally in browser. Unlike cookies, the storage limit is far larger (at least 5MB). HTML web storage provides two objects:

In the tutorial, we practice with window.localStorage. The data is stored as String name/value pairs. So we should convert them if needed. With Jquery, we can do as below:

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 localStorage
	var listOfCustomers = JSON.parse(localStorage.getItem('listOfCustomers'));
		
	...
	
	// store listOfCustomers to localStorage
	localStorage.setItem('listOfCustomers', JSON.stringify(listOfCustomers));

II. Goal

In the tutorial, we build a SpringBoot project as below:

HTML 5 - Web LocalStorage - Using JQuery to Cache data from SpringBoot RestAPIs - project structure

Run and check results:
– Make a first request:

HTML 5 - Web LocalStorage - Using JQuery to Cache data from SpringBoot RestAPIs - view

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

HTML 5 - Web LocalStorage - Using JQuery to Cache data from SpringBoot RestAPIs - record first request

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

HTML 5 - Web LocalStorage - Using JQuery to Cache data from SpringBoot RestAPIs - record cache data at local storage

– 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 - Using JQuery to Cache data from SpringBoot RestAPIs - record the second request

HTML 5 - Web LocalStorage - Using JQuery to Cache data from SpringBoot RestAPIs - log consoles

III. Practice

Step to do:
– Create Spring Boot project
– Create data models
– Create Web Controller to provide web views
– Create RestController for GET request
– Create an index.html view
– Implement JQuery loading data

1. Create Spring Boot project

Use SpringToolSuite to create a SpringBoot project SpringBootCachingWithJQueryWebLocalStorage 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. Create Web Controller to provide web views
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. Create RestController for GET request
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. Create an index.html view

 


      Spring Boot - DELETE-UPDATE AJAX Example
      
      
      
	  
	  
      

 

Customer Table

Id Name Age Street Postcode
6. Implement JQuery loading data
$(document).ready(function() {
	
	/**
	 * Load List of Customers then showing on Table view
	 */
	$(function loadData(){
		
		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 localStorage
			var listOfCustomers = JSON.parse(localStorage.getItem('listOfCustomers'));
			
			// render List of Customers on view
			renderCustomersByTableView(listOfCustomers);
		}else{
			
			console.log("--- Load From Back-End service ---");
			
			$.ajax({
				type : "GET",
				url : window.location + "api/customer/all",
				
				success: function(listOfCustomers){
					
					// store listOfCustomers to localStorage
					localStorage.setItem('listOfCustomers', JSON.stringify(listOfCustomers));
					
					// render List of Customers on view
					renderCustomersByTableView(listOfCustomers);
				},
				error : function(e) {
					alert("ERROR: ", e);
					console.log("ERROR: ", e);
				}
			});
		}
		
	});
	
	/**
	 * Render List of Customers by Table view
	 */
	function renderCustomersByTableView(listOfCustomers){
		if(listOfCustomers){
			
			$.each(listOfCustomers, function(i, customer){
			
				var customerRow = '' +
									'' + customer.id + '' +
									'' + customer.name.toUpperCase() + '' +
									'' + customer.age + '' +
									'' + customer.address.street + '' +
									'' + customer.address.postcode + '' +
								  '';
				
				$('#customerTable tbody').append(customerRow);
				
	        });
			
			$( "#customerTable tbody tr:odd" ).addClass("info");
			$( "#customerTable tbody tr:even" ).addClass("success");
		}
	}
})

IV. Sourcecode

SpringBootCachingWithJQueryWebLocalStorage

23 thoughts on “HTML 5 – Web LocalStorage + JQuery to Cache data from SpringBoot RestAPIs”

  1. Unquestionably consider that which you stated. Your
    favourite justification seemed to be on the web the simplest thing to bear
    in mind of. I say to you, I certainly get annoyed at the same time as other people think about issues that they just don’t recognize about.
    You controlled to hit the nail upon the highest
    as neatly as outlined out the whole thing without having
    side-effects , folks could take a signal. Will probably
    be back to get more. Thanks

  2. With havin so much written content do you ever run into any issues of
    plagorism or copyright infringement? My blog has a lot of exclusive content I’ve either authored myself or outsourced but it appears a lot
    of it is popping it up all over the internet without my authorization. Do you know any techniques to help reduce content from being
    ripped off? I’d certainly appreciate it.

  3. This is a really good tip especially to those new to the
    blogosphere. Brief but very accurate info… Thanks for sharing this one.
    A must read article!

  4. Hi! I understand this is sort of off-topic but I had to ask.
    Does managing a well-established blog like yours take a lot of work?

    I am brand new to blogging but I do write in my diary on a
    daily basis. I’d like to start a blog so I can easily share my personal experince and thoughts online.
    Please leet me know if you have any kind of recommendations or tips for new aspiring bloggers.
    Thankyou!

  5. Remarkable things here. I am very glad to peer your article.
    Thank you so much and I am taking a look forward to contact you.
    Will you kindly drop me a e-mail?

  6. Fantastіc site. Lotѕ of helpfuⅼ information here. I am sending it tto ssome bᥙddies
    ans also shaгing in delicious. And naturally, thank you on youг
    effort!

  7. Fantastic items from you, man. I’ve have in mind your stuff prior to and you’re simply too great.
    I really like what you’ve bought right here, certainly
    like what you are saying and the way through which you are saying it.

    You are making it enjoyable and you still
    care for to keep it sensible. I can’t wait to read much more from you.
    This is really a tremendous website.

  8. Hi, I do believe this is a great website. I stumbledupon it 😉
    I am going to come back once again since i have saved as a favorite
    it. Money and freedom is the greatest way to
    change, may you be rich and continue to guide other people.

  9. Hi, Neat post. There’s an issue with your website in internet explorer, may check this?
    IE nonetheless is the market chief and a huge portion of people will leave out your
    great writing due to this problem.

  10. An intriguing discussion is worth comment. I do believe that
    you ought to publish more on this topic,
    it may not be a taboo matter but typically
    folks don’t talk about such subjects. To the next! Kind regards!!

  11. My coder is trying to convince me to move to .net from
    PHP. I have always disliked the idea because of the expenses.
    But he’s tryiong none the less. I’ve been using
    Movable-type on a variety of websites for about a year and am anxious about
    switching to another platform. I have heard fantastic things about blogengine.net.
    Is there a way I can transfer all my wordpress posts into it?
    Any help would be really appreciated!

  12. Hmm it appears like your site ate my first comment (it was extremely long) so I guess I’ll just sum it up what I submitted and say,
    I’m thoroughly enjoying your blog. I too am an aspiring blog writer but I’m still new to everything.
    Do you have any suggestions for newbie blog writers?
    I’d certainly appreciate it.

Leave a Reply

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