JavaScript: Step 12- Browser Storage (localStorage/sessionStorage)

Browser storage allows web browsers to store data locally on the user’s device, providing two primary types: localStorage and sessionStorage.

Comparing to Core Java:

  • Core Java Comparison: Core Java does not have a direct equivalent of localStorage or sessionStorage, but data persistence in Java can be handled using file I/O, serialization, or databases. For instance, storing user preferences or application settings can be done using file operations or databases.

Tabular Comparisons:

FeaturelocalStoragesessionStorage
Data StoredWithout expiration dateFor a single session or tab
Data DeletedExplicitly by user or applicationWhen the user closes the tab/window or browser

Text Diagram:

Browser Storage
  |
localStorage       sessionStorage
  |                    |
Data without         Data for a single
expiration date      session or tab
  |                    |
Explicitly deleted   Deleted when user
by user or website   closes tab/window,
or when browser      or when browser is closed
is closed            |
                     |

Basic Programs:

1. Storing and Retrieving Data Using localStorage:

// Store data
localStorage.setItem('name', 'John Doe');

// Retrieve data
const name = localStorage.getItem('name');
console.log(name); // "John Doe"

Core Java Comparison: In core Java, you might use file I/O to achieve a similar result:

import java.io.*;

public class LocalStorageExample {
    public static void main(String[] args) throws IOException {
        // Store data
        try (PrintWriter out = new PrintWriter(new FileWriter("data.txt"))) {
            out.println("John Doe");
        }

        // Retrieve data
        try (BufferedReader in = new BufferedReader(new FileReader("data.txt"))) {
            String name = in.readLine();
            System.out.println(name); // "John Doe"
        }
    }
}

2. Storing and Retrieving Data Using sessionStorage:

// Store data
sessionStorage.setItem('name', 'John Doe');

// Retrieve data
const name = sessionStorage.getItem('name');
console.log(name); // "John Doe"

Core Java Comparison: While Java does not have a direct session-based storage mechanism, you can simulate session-based data storage using temporary files or memory:

import java.util.HashMap;
import java.util.Map;

public class SessionStorageExample {
    public static void main(String[] args) {
        // Simulate session-based storage with a HashMap
        Map<String, String> sessionData = new HashMap<>();
        sessionData.put("name", "John Doe");

        // Retrieve data
        String name = sessionData.get("name");
        System.out.println(name); // "John Doe"
    }
}

3. Removing Data from localStorage:

localStorage.removeItem('name');

Core Java Comparison: In core Java, you can delete a file to simulate data removal:

import java.io.File;

public class DeleteDataExample {
    public static void main(String[] args) {
        File file = new File("data.txt");
        if (file.delete()) {
            System.out.println("File deleted successfully");
        } else {
            System.out.println("Failed to delete the file");
        }
    }
}

4. Removing All Data from localStorage:

localStorage.clear();

Core Java Comparison: Clearing all data in core Java can be done by deleting all files in a directory or clearing a database:

import java.io.File;

public class ClearDataExample {
    public static void main(String[] args) {
        File folder = new File("data_directory");
        File[] files = folder.listFiles();
        if (files != null) {
            for (File file : files) {
                file.delete();
            }
            System.out.println("All files deleted successfully");
        }
    }
}

To Run These Programs:

  1. JavaScript:
  • Create a .js file with the JavaScript code.
  • Include this JavaScript file in an HTML file.
  • Open the HTML file in a web browser to see the output in the console.
<pre class="wp-block-syntaxhighlighter-code">&lt;!-- index.html --&gt;
&lt;!DOCTYPE html&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;title&gt;Browser Storage Example&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
        <a href="http://script.js">http://script.js</a>
    &lt;/body&gt;
&lt;/html&gt;</pre>
// script.js
localStorage.setItem('name', 'John Doe');
const name = localStorage.getItem('name');
console.log(name); // "John Doe"
  1. Core Java:
  • Compile and run the Java code using a Java IDE or command line.

5 comments

  1. Nhằm tri ân sự tin tưởng của quý khách, SLOT365 triển khai gói quà tặng khởi nghiệp lên đến 150.000 VNĐ dành riêng cho thành viên mới đăng ký tài khoản chính thức. TONY07-05

  2. I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.

  3. Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?

Leave a Reply

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