本文介绍了Dart是否像$ _SESSION(会话)一样支持PHP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
服务器端Dart是否支持PHP中的会话:
Does server side Dart support sessions like in PHP:
<?php
session_start();
$_SESSION['fruit'] = 'apple';
数据在页面加载时保留。
The data is kept upon page loads.
推荐答案
是的Dart支持与PHP差不多的会话。
Yes Dart has support for sessions which are more or less like in PHP.
让我们编写一个简单的程序来随机分配一个
Let's write a simple program that randomizes a fruit between apples and bananas and saves the choice to the session.
import 'dart:io';
import 'dart:math';
// A method that returns "apple" or "banana" randomly.
String getRandomFruit() => new Random().nextBool() ? 'apple' : 'banana';
main() {
var server = new HttpServer();
server.defaultRequestHandler = (HttpRequest req, HttpResponse res) {
// Initialize session with an empty {} object as data.
var session = req.session((s) => s.data = {});
// Save fruit to session if there is nothing in there.
if (session.data['fruit'] == null)
session.data['fruit'] = getRandomFruit();
// Retrieve fruit from the session.
var fruit = session.data['fruit'];
res.outputStream.writeString("Your fruit: $fruit", Encoding.UTF_8);
res.outputStream.close();
};
server.listen('127.0.0.1', 80);
}
现在运行代码并转到 http :// localhost
,只要会话保持打开状态,每次您看到相同的水果,因为我们将水果保存到会话中。
Now when you run the code and go to http://localhost
, every time you see the same fruit as long as the session stays open, because we save the fruit to the session.
注释:
- 类具有此方法会初始化(或返回)实例。
-
HttpSession
具有一个名为data
的属性,但是您可能希望首先将其初始化为空的{}
。
- The
HttpRequest
class has this methodsession()
which initializes (or returns) theHttpSession
instance. - The
HttpSession
has a property calleddata
, but you might want to initialize it first to be an empty{}
.
这篇关于Dart是否像$ _SESSION(会话)一样支持PHP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!