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
Contents
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:
- window.localStorage – data is stored with no expiration date
- window.sessionStorage – data is stored within one session
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:
1 2 3 4 5 6 7 8 9 10 11 12 |
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:
Run and check results:
– Make a first request:
-> It loads data from SpringBoot back-end : /api/customer/all
-> Then store result as key/value in localStorage:
– shutdown then start user’s browser again. Make the request http://localhost:8080
, the web application uses caching data from localStorage to display:
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:
1 2 3 4 5 6 7 8 |
<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> |
2. Create data models
– Create Address model:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
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<Long, Customer> custStores = new HashMap<Long, Customer>(); @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<Customer> getResource() { List<Customer> custList = custStores.entrySet().stream() .map(entry -> entry.getValue()) .collect(Collectors.toList()); return custList; } } |
5. Create an index.html view
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<!DOCTYPE HTML> <html> <head> <title>Spring Boot - DELETE-UPDATE AJAX Example</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="/js/jqueryAjaxGet.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/> </head> <body> <div class="container"> <h1>Customer Table</h1> <div class="row col-md-7 table-responsive"> <table id="customerTable" class="table table-bordered table-hover"> <thead> <tr> <th>Id</th> <th>Name</th> <th>Age</th> <th>Street</th> <th>Postcode</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> </body> </html> |
6. Implement JQuery loading data
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
$(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 = '<tr>' + '<td>' + customer.id + '</td>' + '<td>' + customer.name.toUpperCase() + '</td>' + '<td>' + customer.age + '</td>' + '<td>' + customer.address.street + '</td>' + '<td>' + customer.address.postcode + '</td>' + '</tr>'; $('#customerTable tbody').append(customerRow); }); $( "#customerTable tbody tr:odd" ).addClass("info"); $( "#customerTable tbody tr:even" ).addClass("success"); } } }) |