一》 通过java与数据库交互读取数据,然后flex和java再进行交互,把java读取的数据放在flex前端显示出来。
1)首先建立数据库:
① 打开cmd终端:mysql -h localhost -u root -p
,按提示输入密码(我用的root)。
② 建立数据库:
create database user; use user;
③ 建立数据表userInfo:
SET FOREIGN_KEY_CHECKS=0; DROP TABLE IF EXISTS `userinfo`; CREATE TABLE `userinfo` ( `userId` int(10) unsigned zerofill NOT NULL auto_increment, `userName` varchar(30) NOT NULL, `userPasswd` varchar(16) NOT NULL, PRIMARY KEY (`userId`) ) DEFAULT CHARSET=utf8;
2)创建javaDao。
① 创建User类
public class User { private String name; public String getName(){ return name; } public void setName(String name){ this.name=name; } }
② 创建DAO类
UserDao.java import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; public class UserDao{ public static Connection getConnection(){ Connection onnection=null; try{ String driver="com.mysql.jdbc.Driver"; String url="jdbc:mysql://localhost:3306/user"; String username="root"; String password="root"; Class.forName(driver); onnection=DriverManager.getConnection(url,username,password); }catch(Exception e){ System.out.println(e.getMessage()); } return onnection; } public List getAllUser()throws SQLException{ Connection connection=getConnection(); Statement st=onnection.createStatement(); ResultSet rs=st.executeQuery("select * from userInfo"); ArrayList userList=new ArrayList<User>(); while(rs.next()){ User u=new User(); u.setName(rs.getString("name")); userList.add(u); } return userList; } }
3) flex代码
① User类
User.aspackage org.rjb.flex{ [RemoteClass(alias="java.User")] public class User{ private var _name:String; public function User(){} public function get name():String{ return this._name; } public function set name(name:String):void{ this._name=name; } } }
②user.mxml文件
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical"> <mx:RemoteObject id="ud" destination="UserDao" result="onResult(event)" fault="onFault()" /> <mx:DataGrid dataProvider="{users}"> <mx:columns> <mx:DataGridColumn dataField="name" headerText="name" /> </mx:columns> </mx:DataGrid> <mx:Label id="info" /> <mx:Button label="click" click="clickFun()" /> <mx:Script> <!--[CDATA[ import mx.collections.ArrayCollection; import mx.rpc.events.ResultEvent; [Bindable] public var users:ArrayCollection=new ArrayCollection(); public function clickFun():void{ ud.getAllUser(); } public function onResult(event:ResultEvent):void{ users=ArrayCollection(event.result); info.text="get data successfully"; } public function onFault():void{ info.text="Error"; } ]]--> </mx:Script> </mx:Application>
③配置remoting-config.xml,在里面加上如下配置文件:
<destination id="UserDao"> <properties> <source>UserDao</source> </properties> </destination>