简体   繁体   English

如何使用Java设置和读取Cookie值

[英]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. 我正在开发一个移动应用程序,我使用HTML 5,Ajax,jQuery和CSS进行构建。
I wrote the following codes to store loged-in user ID and name; 我编写了以下代码来存储登录的用户ID和名称;

<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; 我还编写了此函数以使用cookie的名称读取cookie的值。

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; 我调用以下命令将登录用户的名称读入一个名为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.. 上面的代码在Web浏览器上测试时可以正常工作,但是当我尝试在移动应用程序(与Phonegap编译)中运行它时,var名称返回“ undefined”,这意味着脚本无法读取cookie值。 。

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. 我需要使用cookie来验证移动应用程序中的登录用户。

Thanks 谢谢

On Phonegap document.cookie is empty, since index.html and all other files are loaded with file:// protocol. 在Phonegap上, document.cookie为空,因为index.html和所有其他文件都使用file://协议加载。 Phonegap manages cookies internally, but doesn't expose any function for clearing them. Phonegap在内部管理cookie,但不提供清除它们的任何功能。

You might want to have a look at the plugin: 您可能想看看插件:

https://github.com/bez4pieci/Phonegap-Cookies-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. Cookie无法在移动应用程序(使用Webview或类似工具)上运行,因此我改用本地存储。

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. 就是这样...它在iOS,Android和Windows Mobile上都能正常运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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