[转]flex与servlet交互

1.新建一个felx工程,其中引入一个TextInput,ID=idFlex。再引入一个Button,ID=btnGetSvr,其事件click="getSvrInfo()"
flex基本代码如下:
<![CDATA[
  import mx.controls.Alert;
           
  public function getSvrInfo():void
  {
    //首先发送servlet请求 (此flex为servlet名)
    var request:URLRequest=new URLRequest("http://127.0.0.1:8080/webHello/flex");
    request.method=URLRequestMethod.POST;
    request.data = new URLVariables("flex="+tiFlex.text); //flex为参数名

    var loader:URLLoader=new URLLoader();
    loader.load(request);
    loader.addEventListener(Event.COMPLETE, onLoaderComplete); //后台数据到达事件
  }

  private function onLoaderComplete(event : Event):void //后台数据到达后激活
  {
    //servlet端传回来的参数
    var str : String = ((event.target) as URLLoader).data;
    trace("servlet端传回来的参数:"+str);
    taResult.text = str;
  }
]]>

要点:
该段代码使用了URLRequest、URLLoader组件,而URLLoader响应onLoaderComplete事件,表示后台数据就绪。

2.servlet代码:
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8"); //flex中隐含为utf-8编码
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
          String flex=request.getParameter("flex");
          System.out.print("felx参数:"+flex);
          out.println("servlet返回:"+flex);
        } finally {
            out.close();
        }
    }

你可能感兴趣的:(html,servlet,Flex)