flex与servlet 数据通信实例

 这个例子展示了flex如何与servlet通信。

首先,用flex buider2创建工程,工程名字为flexCalculaotr,然后创建mxml主文件,主文件名为flexCalculator.mxml,

以下为flexCalculator.mxml的代码

<? xml version="1.0" encoding="utf-8" ?>
< mx:Application  xmlns:mx ="http://www.adobe.com/2006/mxml"  layout ="absolute"
 creationComplete
="initApp()" >
   
< mx:HTTPService  id ="flex"  useProxy ="false"  method ="POST"
      url
="http://localhost:8080/flexCalculator/Calculate" />
<!-- 下面这段代码的意思是:数据绑定,即把firstNumber.text的内容绑定在firstNumber中,后台(如JSP,Servlet)使用request.getParameter("firstNumber")方法获得控件的值-->
    < mx:Model  id ="myModel" >
      
< root >
         
< firstNumber > {firstNumber.text} </ firstNumber >
         
< secondNumber > {secondNumber.text} </ secondNumber >
         
< operator > {operator.text} </ operator >
      
</ root >
   
</ mx:Model >
   
< mx:Script  source ="CheckTheInput.as" >
   
</ mx:Script >
   
< mx:Label  x ="11"  y ="97"  width ="424"  text =
    "Input two numbers ant then press equals button, you will get the result."
/>
   
< mx:TextInput  x ="42"  y ="142"  width ="90"  height ="21"  id ="firstNumber"  
    focusIn
="focusOnFirstNumber()"  keyDown ="enterClick(event)" />
   
< mx:ComboBox  x ="140"  y  ="142"  width ="44"  height ="21"  id ="operator"
    editable
="false"  tabEnabled ="false"  keyDown ="enterClick(event)" >
      
< mx:dataProvider >
         
< mx:Array >
            
< mx:String > + </ mx:String >
            
< mx:String > - </ mx:String >
            
< mx:String > * </ mx:String >
            
< mx:String > / </ mx:String >
         
</ mx:Array >
      
</ mx:dataProvider >
   
</ mx:ComboBox >
   
< mx:TextInput  x ="192"  y ="142"  width ="78"  height ="21"  id ="secondNumber"  
    focusIn
="focusOnSecondNumber()"  keyDown ="enterClick(event)" />
   
< mx:Button  x ="278"  y ="142"  label ="="  height ="21"  click ="submitForm();"  
    keyDown
="enterClick(event)" />
   
< mx:TextInput  x ="326"  y ="142"  width ="72"  height ="21"  id ="result"
    text
="{flex.lastResult.results.result}"  editable ="false"  
          backgroundColor
="#C0C0C0" />
   
< mx:Panel  x ="76"  y ="171"  width ="268"  height ="187"  layout ="absolute"  
       backgroundColor
="#FFFFFF"  title ="My Calculator" >
      
< mx:Button  x ="85"  y ="5"  label ="Clear"  width ="78"  click ="input(event);" />
      
< mx:Button  x ="168"  y ="5"  label ="BackSpace"  width ="78"  
       click
="input(event);" />
      
< mx:Button  x ="3"  y ="34"  label ="7"  width ="78"  click ="input(event);" />
      
< mx:Button  x ="85"  y ="34"  label ="8"  width ="78"  click ="input(event);" />
      
< mx:Button  x ="168"  y ="34"  label ="9"  width ="78"  click ="input(event);" />
      
< mx:Button  x ="3"  y ="64"  label ="4"  width ="78"  click ="input(event);" />
      
< mx:Button  x ="85"  y ="64"  label ="5"  width ="78"  click ="input(event);" />
      
< mx:Button  x ="168"  y ="64"  label ="6"  width ="78"  click ="input(event);" />
      
< mx:Button  x ="3"  y ="94"  label ="1"  width ="78"  click ="input(event);" />
      
< mx:Button  x ="85"  y ="94"  label ="2"  width ="78"  click ="input(event);" />
      
< mx:Button  x ="168"  y ="94"  label ="3"  width ="78"  click ="input(event);" />
      
< mx:Button  x ="3"  y ="124"  label ="0"  width ="78"  click ="input(event);" />
      
< mx:Button  x ="85"  y ="124"  label ="+/-"  width ="78"  click ="input(event);" />
      
< mx:Button  x ="168"  y ="124"  label ="."  width ="78"  click ="input(event);" />
      
< mx:Button  x ="3"  y ="5"  width ="78"  label ="E"  click ="input(event);" />
   
</ mx:Panel >
</ mx:Application >

界面如下图所示

对输入的正确性进行验证,以及对各个按钮进行响应,回车响应,还需要一个AS 文件,创建一个ActionScript文件,名字为checkTheInput.as

 

import mx.controls.Alert;
import mx.controls.Button;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;

//  flage foucs=1, focus on firstNumber, else focus on secondNumber
private  var  focus: int   =   1

private 
function  submitForm(): void  {
   flex.cancel();

   
//  if input correctly, send two numbers to servlet
    if (checkInput(firstNumber)  &&  checkInput(secondNumber)) {
      flex.send(myModel);
   }
}

private 
function  enterClick(event:KeyboardEvent): void  {
   
if (event.keyCode  ==   13 ) {
      submitForm();
   }
}

/* *
 * Set the focus on the first TextInput control.
 
*/
private 
function  initApp(): void  {
   focusManager.setFocus(firstNumber);
}

/*
 * Check the text of the TextInput control.
 * @param textInput TextInput control.
 * @return true if the text is a number, or false if not.
 
*/
private 
function  checkInput(textInput:TextInput):Boolean {
   
var  message:String;
   
var  number:Number  =  Number(textInput.text);
   
var  index: int   =  textInput.text.toLowerCase().indexOf( " e " );
   message 
=  (textInput  ==  firstNumber) ?   " The 1st number "  :  " The 2nd number " ;
   
   
//  can not be empty
    if (textInput.text  ==   "" ) {
      focusManager.setFocus(textInput);
      Alert.show(message 
+   "  can not be empty! " );

      
return   false ;
   }
   
   
if (index  >   0   &&  
      trim(textInput.text).substr(index 
+   1 , textInput.text.length)  ==   ""
   {
      focusManager.setFocus(textInput);
      Alert.show(message 
+   "  input error! " );
      textInput.text 
=   "" ;
      
      
return   false ;
   }
   
   
//  if the number is not a number, show error message
    if (isNaN(number)) {
      focusManager.setFocus(textInput);
      Alert.show(message 
+   "  input error! " );
      textInput.text 
=   "" ;
      
      
return   false ;
   }

   
//  divisor can not be 0
    if (textInput  ==  secondNumber  &&  operator.selectedIndex  ==   3   &&  number  ==   0 ) {
      focusManager.setFocus(textInput);
      Alert.show(
" Divisor can not be 0! " );
      textInput.text 
=   "" ;
      
      
return   false ;
   }
   
   
return   true ;
}

/* *
 * Get the input from the buttons on panel.
 
*/
private 
function  input(event:Event): void  {
   
var  str:String  =  (focus  ==   1 ) ?  firstNumber.text : secondNumber.text;
   
//  get label from button
    var  temp:String  =  event.target.label;
   
   
if (temp.charAt( 0 >=   ' 0 '   &&  temp.charAt( 0 <=   ' 9 ' ) {
      str 
=  str  +  temp;
   }
   
   
//  BackSpace button
    if (temp  ==   " BackSpace " ) {
      str 
=  str.substring( 0 , str.length  -   1 );
   }
   
   
//  Clear button
    if (temp  ==   " Clear " ) {
      firstNumber.text 
=   "" ;
      secondNumber.text 
=   "" ;
      focusManager.setFocus(firstNumber);
      
return  ;
   }
   
   
//  sign button
    if (temp  ==   " +/- " ) {
      
var  number:Number  =  Number(str);
      number 
=   -  number;
      str 
=   ""   +  number;
   }
   
   
//  dot button
    if (temp  ==   " . "   &&  str.indexOf(temp)  <   0 ) {
      str 
=  str  +  temp;
   }
   
   
if (temp  ==   " E "   &&  str.indexOf(temp)  <   0 ) {
      str 
=  str  +  temp;
   }
   
   
if (focus  ==   1 ) {
      firstNumber.text 
=  str;
      focusManager.setFocus(firstNumber);
      firstNumber.setSelection(firstNumber.text.length, firstNumber.text.length);
   }
   
else   if (focus  ==   2 ) {
      secondNumber.text 
=  str;
      focusManager.setFocus(secondNumber);
      secondNumber.setSelection(secondNumber.text.length, 
                                secondNumber.text.length);
   }
   
}

/* *
 * Set the focus on the first TextInput control.
 
*/
private 
function  focusOnFirstNumber(): void  {
   focus 
=   1 ;
}

/* *
 * Set the focus on the second TextInput control.
 
*/
private 
function  focusOnSecondNumber(): void  {
   focus 
=   2 ;
}

/* *
 * Trim the blanks of the string.
 * @param str the String need to be trimed.
 * @return string after be trimed.
 
*/
private 
function  trim(str:String):String {
   
while (str.charAt( 0 ==   '   '   &&  str.length  !=   0 ) {
      str 
=  str.substr( 1 , str.length);
   }

   
while (str.charAt(str.length  -   1 ==   '   '   &&  str.length  !=   0 ) {
      str 
=  str.substr( 0 , str.length  -   1 );
   }

   
return  str;
   
// return str.replace(/(^s*)|(s*$)/g, "");
}

///

以上是flex 端的,以下是后台处理的servlet 端

名字为flexCalculator.java

 

package  servlet;

import  java.io. * ;
import  javax.servlet.http. * ;
import  javax.servlet.ServletException;

/**
 * Servlet for computing, output the result by xml, flex will get the result
 * from the output.
 *
 * 
@author  InetSoft Technology Corp.
 * 
@version   1.0
 
*/
public   class  Calculator  extends  HttpServlet {

   
//  response to an  Post request from the flex
    public   void  doPost(HttpServletRequest request, HttpServletResponse response)
      
throws  ServletException, IOException
   {
      doGet(request, response);
   }

   
//  response to an GET request from the flex
    public   void  doGet(HttpServletRequest request, HttpServletResponse response)
      
throws  ServletException, IOException
   {
      response.setContentType(
" text/html " );
      PrintWriter out 
=  response.getWriter();
      
//  get the first number
      String number1  =  request.getParameter( " firstNumber " );
      
//  get the second number
      String number2  =  request.getParameter( " secondNumber " );
      
//  get the operator
      String operator  =  request.getParameter( " operator " );
      
//  compute the reslut
      String result;

      
if (checkInput(number1)  &&  checkInput(number2)) {
         result 
=  calculate(Double.valueOf(number1).doubleValue(),
                            Double.valueOf(number2).doubleValue(), operator);

         
//  the reslut is too large
          if (result.equals( " Infinity " ||  result.equals( " -Infinity " ) ) {
            result 
=   " Too large. " ;
         }

         
if (result.equals( " Choose an operator! " )) {
            result 
=   " Choose an operator! " ;
         }

         
if (result.equals( " Divisor can not be ! " )) {
            result 
=   " Divisor can not be ! " ;
         }
      }
      
else  {
         result 
=   " Input error! " ;
      }

      String outputStr 
=   " <?xml version="1.0" encoding="UTF-8"?> "   +
                         
" <results><result> "   +  result  +   " </result></results> " ;
      out.println(outputStr);
   }

   
/**
    * Calculate the result, and return result by string.
    *
    * 
@param  num1 is the first operand.
    * 
@param  num2 is the second operand.
    * 
@param  op is the operator.
    * 
@return  the result.
    
*/
   
private  String calculate( double  num1,  double  num2, String op) {
      
switch (op.charAt( 0 )) {
      
case   ' + ' :
         
return  Double.toString(num1  +  num2);
      
case   ' - ' :
         
return  Double.toString(num1  -  num2);
      
case   ' * ' :
         
return  Double.toString(num1  *  num2);
      
case   ' / ' :
         
if (num2  ==   0 ) {
            
return   " Divisor can not be ! " ;
         }
         
else  {
            
return  Double.toString(num1  /  num2);
         }
      
default :
         
return   " Choose an operator! " ;
      }
   }

   
/**
    * Check the str,make sure that the str can be changed to a number.
    *
    * 
@param  str need to be checked.
    * 
@return  the true if the str is a number, or false if not a number.
    
*/
   
private  Boolean checkInput(String str) {
      
try  {
         
new  Double(str);
      }
      
catch (NumberFormatException ex) {
         
return   false ;
      }

      
return   true ;
   }
}

servlet 端的web.XML文件代码

 

<? xml version="1.0" encoding="UTF-8" ?>
<! DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd"
>
< web-app >
  
< servlet >
    
< servlet-name > ShowResult </ servlet-name >
    
< servlet-class > servlet.Calculator </ servlet-class >
  
</ servlet >
  
< servlet-mapping >
    
< servlet-name > ShowResult </ servlet-name >
    
< url-pattern > /Calculate </ url-pattern >
  
</ servlet-mapping >
</ web-app >

把flexCalculaotr.java 放在D:/jakarta-tomcat-5.0.28/webapps/flexCalculator/WEB-INF/classes/servlet目录下(根据tomcat安装目录自行调整)

把web.XML放在D:/jakarta-tomcat-5.0.28/webapps/flexCalculator/WEB-INF目录下。

运行程序: 先运行tomcat,然后运行flex端。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值