flex+servlet简单实例
下面是flex的主要代码
<?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" >
<s:layout>
<s:BasicLayout/>
</s:layout>
<fx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.events.FlexEvent;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.utils.UIDUtil;
protected function service_resultHandler(event:ResultEvent):void
{
//注意一定要加上toString,不然会有中文乱码出现
Alert.show(String(event.result.toString()));
}
protected function service_getString(event:ResultEvent):String
{
return String(event.result.toString());
}
protected function service_faultHandler(event:FaultEvent):void
{
Alert.show("请求异常");
}
protected function send_clickHandler(event:MouseEvent):void
{
// TODO Auto-generated method stub
Alert.show("inputName.text1="+inputName.text);
//如果直接在flex.do后面加参数,传到servlet时会有乱码出现
service.url = "http://localhost:8080/flexTest/flex.do";
service.send();
}
private function httpEncoding(param:String):String{
return encodeURIComponent(param);
}
]]>
</fx:Script>
<fx:Declarations>
<mx:HTTPService id="service" resultFormat="text" result="service_resultHandler(event)"
fault="service_faultHandler(event)" method="POST" >
<mx:request xmlns="">
<inputName>
{inputName.text}
</inputName>
</mx:request>
</mx:HTTPService>
</fx:Declarations>
<s:TextArea x="33" y="25" width="230" id="showHtml" text="{service.lastResult}"/>
<s:Button x="543" y="70" label="send" id="send" enabled="true" click="send_clickHandler(event)"/>
<s:TextInput x="375" y="69" id="inputName"/>
</s:Application>
在servlet里加了一个过滤器,在以POST提交时防止中文乱码,全部设置为UTF-8
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
chain.doFilter(request, response);
}
实例见附件