この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。
今回はAMF通信でセッション管理する方法を調べました。
BlazeDSのバージョンは4.0を使ってます。
サーバの設定などに関しては先日設定した環境をそのまま使っています。
BlazeDSの設定とAMF通信のサンプル
サーバ側の実装ですがFlexContextのgetHttpRequestメソッドでHttpServletRequestクラスのオブジェクトを取得してから
HttpServletRequestクラスのgetSessionメソッドでHttpSessionクラスのオブジェクトを取得します。
あとはServletなどでのセッション管理と同様にsetAttributeメソッド、getAttributeメソッドで設定と取得を行います。
以下がサンプルになります。
■ Javaのソース
package sample;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import flex.messaging.FlexContext;
public class SampleService {
public void setValue(String value) {
HttpServletRequest request = FlexContext.getHttpRequest();
HttpSession session = request.getSession();
session.setAttribute("KEY", value);
}
public String getValue() {
HttpServletRequest request = FlexContext.getHttpRequest();
HttpSession session = request.getSession();
return (String)session.getAttribute("KEY");
}
}
次に作成したサービスを呼び出してみます。
SET VALUEボタンを押すとテキストインプットの内容をサーバに保存します。
GET VALUEボタンを押した場合はサーバで保存している情報をテキストインプットに表示します。
Flex SDKのバージョンは4.5.1です。
■ MXMLのソース
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
<fx:Declarations>
<s:RemoteObject id="service"
destination="sample"
endpoint="http://localhost:8080/SampleBlazeDS/messagebroker/amf"/>
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.rpc.AsyncToken;
import mx.rpc.Responder;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
/** button1押下時の処理 */
private function button1_clickHandler(event:MouseEvent):void{
var token:AsyncToken = service.getOperation("setValue").send(textInput.text);
token.addResponder(new mx.rpc.Responder(setValueResultHandler, faultHandler));
}
/** button2押下時の処理 */
private function button2_clickHandler(event:MouseEvent):void {
var token:AsyncToken = service.getOperation("getValue").send();
token.addResponder(new mx.rpc.Responder(getValueResultHandler, faultHandler));
}
/** setValueのResultEventHandler */
private function setValueResultHandler(event:ResultEvent):void{
textInput.text = "";
}
/** getValueのResultEventHandler */
private function getValueResultHandler(event:ResultEvent):void{
textInput.text = event.result as String;
}
/** FaultEventHandler */
private function faultHandler(event:FaultEvent):void{
label.text = event.toString();
}
]]>
</fx:Script>
<s:VGroup>
<s:HGroup>
<s:TextInput id="textInput"/>
<s:Button id="button1" label="SET VALUE" click="button1_clickHandler(event)"/>
<s:Button id="button2" label="GET VALUE" click="button2_clickHandler(event)"/>
<s:Label id="label"/>
</s:HGroup>
</s:VGroup>
</s:Application>