I didn't understand how Flex was connected to the database when I first started to use flex1.5. Although I knew there were three methods, I still didn't understand it. This problem gave me a headache for a long time, then I finally realized it. Today, I wrote a tutorial on how to use remoteobject In Flex to connect to the database using Java objects. I don't need to read it for beginners.
First, make a note. Flex cannot directly connect to the database. You need to know that it can only indirectly connect to the database. Flex provides three methods: httpservice, WebService, and remoteobject. Httpservice can directly obtain data in XML, and read data in the database through JSP, ASP, and PHP. This is simple, and there are many examples on the Internet, so I will not talk about it much. I don't understand WebService. Please check your information. I have been using Java objects to connect to the database. I feel this is very convenient, and the J2EE technology is very mature. In today's tutorial, we will take Flex + Java + sqlserver to obtain database announcement information for an example to briefly describe how to use remoteobject.
Prerequisites
1. Make sure that you have installed the flex data service. This is free for a single cup unlimited app and can be downloaded from Adobe. If you only need to read the XML file, you need to connect to the database.
2. You have installed the flex builder or the flex SDK. I am using Flex Builder (IDE is convenient ).
3. the SQL Server database is installed.
4. jrun or tomcat or other J2EE containers are installed, because our program runs on the J2EE platform at the time of release.
5. JDK is installed.
JDK version Problems: I use JRun of flex data service, but jdk5.0 is not supported. Therefore, I use jdk1.4.2. You can check the version details.
Step 1: Create a database
Here we have an announcement table named bulletin. The structure is as follows:
Program code field Name field type description
ID: Automatic ID
Title nvarchar (100)
Date datatime date
Author of author nvarchar (20)
Contents ntext content
Create this table in the database. Save and go to the next step.
Step 2: write the code to get the announcement in Java
First, create an announcement class to save the obtained announcement information. The Code is as follows.
Noticeinfo. Java
Program code package net. zhuoqun. connectdb;
Import java. util. date;
Public class noticeinfo {
Private String title; // the title.
Private string author; // author
Private string content; // content
Private date dates; // time
Public String getauthor (){
Return author;
}
Public void setauthor (string author ){
This. Author = author;
}
.................. // Other get and set methods.
}
After this is created, we will create a Data Query Class: dataserviceimpl. Java to query the database and pass the query results to the flex program to be created. Since we do not know how many records there are, we can use the arraylist class in Java, which is located in the Java. util package. Create an arraylist first:
Program code arraylist noticelist = new arraylist (); // I do not use generics here, because I use jdk1.4.2.
After the database is queried, each record read is added to noticelist.
Program Code while (Rs. Next ()){
Noticeinfo temp = new noticeinfo ();
Temp. setauthor (Rs. getstring ("author "));
Temp. setcontent (Rs. getstring ("content "));
Temp. setdates (Rs. getdate ("date "));
Temp. settitle (Rs. getstring ("title "));
Noticelist. Add (temp );
}
After the query is complete, you can pass the noticelist back. You can also pass back a noticeinfo array:
Program code noticeinfo [] notices = new noticeinfo [noticelist. Size ()];
For (INT I = 0; I <noticelist. Size (); I ++ ){
Notices [I] = (noticeinfo) noticelist. Get (I );
}
Return notices;
Here I use the last method. If you directly pass the noticelist back, remember that the arraylist objects in Java will become arraycollection objects in flex.
Now the Java code is ready.
The full code of dataserviceimpl. Java is as follows:
Program code package net. zhuoqun. connectdb;
Import java. SQL .*;
Import java. util. arraylist;
Import java. util. date;
Public class dataserviceimpl {
Private connection conn = NULL;
Private statement stmt = NULL;
// The following are the database and driver information
Public final static string driver = "com. Microsoft. JDBC. sqlserver. sqlserverdriver ";
Public final static string conn_str_pre = "JDBC: Microsoft: sqlserver ://";
Public final static string host_name = "localhost: 1433 ;";
Public final static string database_name = "databasename = mydata ";
Public final static string username = "AAA ";
Public final static string Password = "AAA ";
Public dataserviceimpl (){
}
// Query the database
Private resultset executequery (string sqltext ){
Try {
Class. forname (driver );
} Catch (classnotfoundexception e ){
E. printstacktrace ();
}
Try {
Conn = drivermanager. getconnection (conn_str_pre + host_name + database_name, username, password );
Stmt = conn. createstatement ();
Resultset rs = stmt.exe cutequery (sqltext );
Return Rs;
} Catch (sqlexception e ){
E. printstacktrace ();
}
Return NULL;
}
// Query the announcement. This is the key code of this program.
Public noticeinfo [] getnotices (){
Arraylist noticelist = new arraylist ();
String sqltext = "select author, content, date, title from Bulletin ";
Resultset rs = executequery (sqltext );
Try {
While (Rs. Next ()){
Noticeinfo temp = new noticeinfo ();
Temp. setauthor (Rs. getstring ("author "));
Temp. setcontent (Rs. getstring ("content "));
Temp. setdates (Rs. getdate ("date "));
Temp. settitle (Rs. getstring ("title "));
Noticelist. Add (temp );
}
Noticeinfo [] notices = new noticeinfo [noticelist. Size ()];
For (INT I = 0; I <noticelist. Size (); I ++ ){
Notices [I] = (noticeinfo) noticelist. Get (I );
}
Return notices;
} Catch (sqlexception e ){
E. printstacktrace ();
Return NULL;
}
}
}
Step 3: configure the flex Data Service
1. Compile the written Java file. Open the FDS installation folder, copy the compiled file to the/jrun4/servers/default/flex/WEB-INF/classes folder, and configure the following.
2. Open the FDS installation folder. Go to the jrun4/servers/default/flex/WEB-INF/flex directory. There is a configuration file about flex data service. Here we only look at how to configure remoteobject. For other configuration information, see help. Now we open the remoting-config.xml file inside. Add the following information to it as a sub-tag of <service>:
Program code <destination ID = "dataservice">
<Properties>
<Source> net. zhuoqun. connectdb. dataserviceimpl </source>
</Properties>
</Destination>
When destination is set, you reference the information channel that can be used to connect the corresponding class ). Its ID must be unique in the file. The source attribute refers to the path of the compiled Java class in the classes folder. Because my dataserviceimpl class is in classes/NET/zhuoqun/connectdb, the source value is net. zhuoqun. connectdb. dataserviceimpl. Remember, do not write the. Class suffix. <Properties> the tag can also have a <scope> sub-tag, which I will not talk about here. You can read the relevant documentation by yourself (there are many things about FDS configuration, these are all in the help document. I will not talk about them here, but I can't talk about them anymore. Let's just look at them ).
Now we have configured the FDS in the background and completed most of the work of the entire program. Next we will call the frontend flex program.
Step 4: Create a flex Program
Open flex builder and create a new connectdb project. In the menu bar, choose file-> New-> flex project. A dialog box is displayed,
There are two compilation options: "compile locally in flex builder" (compile to SwF and put the HTML page to the server) and "compile again when the user browses the page ", you can select the first one as needed.
Next, set the root directory and path of the FDS Server:
Enter the project name and directory:
Click Next to set the class path and Output Folder:
After setting these settings, click Finish to create a flex project.
Step 5: access the database through remoteobject
Open the main file connectdb. mxml generated in the project and declare a remoteobject:
Program code <mx: remoteobject id = "getdata" Destination = "dataservice" result = "proccessresult (event. result) "fault =" alert. show (event. fault. faultstring, 'error') "/>
The value of destination is the destination we set When configuring FDS. Result indicates the action to be performed after the remoteobject is successfully returned. Here we call a method proccessresult () to process the returned data. Its Parameter event. result is the data obtained from the server segment. The data is transmitted as an object. Fault indicates the processing to be performed when the remoteobject request fails. An error message dialog box is displayed. Next, we need to declare a DataGrid Control to display the announcement title and Release Date:
Program code <mx: DataGrid id = "mydg">
<Mx: columns>
<Mx: datagridcolumn headertext = "title" datafield = "title"/>
<Mx: datagridcolumn headertext = "Release Date" datafield = "dates" labelfunction = "formatdate"/>
</MX: columns>
</MX: DataGrid>
Headertext is the header displayed on the top, and datafield indicates the data domain to be displayed. Why is the data domain title and dates? Because we return an array of noticeinfo objects, although it is passed back as an object, but the data structure is not changed, the names of those data domains are not changed, so we can set datafield according to the variables in noticeinfo. The labelfunction attribute is used to format the display, because the Greenwich Mean Time is returned, so we need to format it and display it. Note: Only two data domains are displayed, which does not mean that all other data fields are absent. They still exist, but are not displayed.
Next, write the proccessresult () method and the formatdate Method for formatting the date in the <mx: SCRIPT> label:
Program code private function proccessresult (Result: Object): void
{
Mydg. dataprovider = arrayutil. toarray (result );
}
Private function formatdate (item: object, column: datagridcolumn): String
{
Return DF. Format (item. Dates );
} // DF is a dateformatter, which is shown below. How to format the display of a DataGrid
// And dateformatter won't be discussed here, and the help is clearly written.
This function simply transmits the obtained data to the dataprovider of mydg. The result type is object, because data is transmitted as an object. The reason for calling the arrayutil. toarray () method is that only one record is returned, and the dataprovider of mydg may encounter errors when displaying a single object. Therefore, we should first convert it to an array for security reasons.
Finally, we compile a method to call remoteobject so that it can be called when the program starts.
Program code private function initapp (): void
{
Getdata. getnotices ();
}
Getdata is the ID of the remoteobject, and getnotices () is the method in dataserviceimpl. java. You can call it directly here. Of course, if dataserviceimpl. Java has other methods, you can call them directly in this way. Next, call the initapp () method when the component is created, and add a creationcomplete attribute in <mx: Application>:
Program code <mx: Application xmlns: MX = "http://www.adobe.com/2006/mxml" fontsize = "12"
Creationcomplete = "initapp ()">
........................
All code of connectdb. mxml:
Program code <? XML version = "1.0" encoding = "UTF-8"?>
<Mx: Application xmlns: MX = "http://www.adobe.com/2006/mxml" fontsize = "12"
Creationcomplete = "initapp ()">
<Mx: SCRIPT>
<! [CDATA [
Import MX. Controls. Alert;
Import MX. utils. arrayutil;
Private function initapp (): void
{
Getdata. getnotices ();
}
Private function proccessresult (Result: Object): void
{
Mydg. dataprovider = arrayutil. toarray (result );
}
Private function formatdate (item: object, column: datagridcolumn): String
{
Return DF. Format (item. Dates );
} // DF is a dateformatter, which is shown below. How to format the display of a DataGrid
// And dateformatter won't be discussed here, and the help is clearly written.
]>
</MX: SCRIPT>
<Mx: dateformatter id = "DF" formatstring = "YYYY-MM-DD"/>
<Mx: remoteobject id = "getdata" Destination = "dataservice" result = "proccessresult (event. result) "fault =" alert. show (event. fault. faultstring, 'error') "/>
<Mx: DataGrid id = "mydg">
<Mx: columns>
<Mx: datagridcolumn headertext = "title" datafield = "title"/>
<Mx: datagridcolumn headertext = "Release Date" datafield = "dates" labelfunction = "formatdate"/>
</MX: columns>
</MX: DataGrid>
</MX: Application>
The entire project is finally completed, start JRun, and run. Result:
Note:
1. Pay attention to your JRun or other container's support for the JDK version. If you are not careful, errors will occur.
2. At runtime if the console encountered an error that could not find the/messagebroker/AMF file, please refer to the solution I found previously: http://www.zhuoqun.net/article.asp? Id = 180
3. If an error occurs while obtaining data during running, the console usually prompts you a lot.
Summary
This simple tutorial serves as an entry for some flex beginners. I have limited technical skills and cannot write well. In addition, due to the limited length, I have not written many details. If I have any questions, I will go to the help document. It is the best textbook.