简体   繁体   中英

How to set and read cookie value using Java

I am working on a mobile app, I build it using HTML 5, Ajax, jQuery and CSS.
I wrote the following codes to store loged-in user ID and name;

<script>
    document.cookie = "id="+"1";
    document.cookie = "name="+"Demo Name";
</script>

I have also written this function to read value of a cookie using its name;

function readCookie(name) {
    name += '=';
    for (var ca = document.cookie.split(/;\s*/), i = ca.length - 1; i >= 0; i--)
        if (!ca[i].indexOf(name))
            return ca[i].replace(name, '');
}

I call the following to read the name of the logged-in user into a variable called name;

var name = readCookie('name'); 

The codes above works fine while testing on a web browser but when i try to run it in the mobile app (compiled with Phonegap), the var name returns "undefined", which means that the script was not able to read the cookie value..

Please can anyone help me out here!

I cant figure out what i did or if am missing something.

I need to use cookie to validate logged in user in my mobile app.

Thanks

On Phonegap document.cookie is empty, since index.html and all other files are loaded with file:// protocol. Phonegap manages cookies internally, but doesn't expose any function for clearing them.

You might want to have a look at the plugin:

https://github.com/bez4pieci/Phonegap-Cookies-Plugin

The plugin works like the following:

window.cookies.clear(function() {
    console.log('Cookies cleared!');
});

I have found a solution after a long digging...
Cookie will not work on mobile app (using webview or similar), so I used local storage instead.

To store my data, i used

window.localStorage.setItem("key", "value");

To retrieve the data, i simply used

var data = window.localStorage.getItem("key");

That's it... it works fine on iOS, Android and windows Mobile.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM