This is an example of using Flex to interact with the backend Servlet. I hope it will be helpful to some new users who have just learned Flex. To understand how Flex communicates with the backend, I did nothing five days before I started learning Flex. The purpose of this article is to avoid detours for beginners.
Interaction principle: the three letters --------- XML, the client receives XML data sent from the server.
In this example, the client is a DataGrid component to display the data transmitted by the server. The corresponding mxml file is as follows:
XML Code
- <? XmlVersion="1.0" Encoding=UTF-8"? >
- <Mx: ApplicationXmlns: mx=Http://www.adobe.com/2006/mxml" Layout="Absolute">
- <Mx: ModelSource=& Quot; http: // localhost: 8080/flex/first & quot" Id="Model">
- </Mx: Model>
- <Mx: PanelTitle="User information" Width="776" Height="281" FontSize="18">
- <Mx: DataGridDataProvider="{Model. user }" Width="748" Height="231">
- <Mx: columns>
- <Mx: DataGridColumnDataField="Name" HeaderText="User">
- </Mx: DataGridColumn>
- <Mx: DataGridColumnDataField="Pwd" HeaderText="Password">
- </Mx: DataGridColumn>
- <Mx: DataGridColumnDataField="School" HeaderText="Current School">
- </Mx: DataGridColumn>
- </Mx: columns>
- </Mx: DataGrid>
- </Mx: Panel>
- </Mx: Application>
Note the <mx: Model> label. The source attribute specifies a servlet ing. The servlet uses response to write XML to the client.
Read database data and generate an XML file consisting of two classes: FirstServlet. java, one is XML. java, the former is a common servlet used to write XML files, and the latter is used to generate XML files, completed by Java xml api operations. Take a look at the code first.
FirstServlet code Abstract:
Java code
- Try {
- Xml. init ();
- Class. forName ("com. microsoft. jdbc. sqlserver. SQLServerDriver ");
- // ********** Create a database named flex *************//
- StringUrl="Jdbc: microsoft: sqlserver: // localhost: 1433; DatabaseName = flex";
- // *********** Change your username and password information ************//
- Con=DriverManager. GetConnection (url, "sa", "135780 ");
- Stmt=Con. CreateStatement ();
- // Create a table named USERS in ********** for details about the SQL statement, see Attachment download **********//
- Result=Stmt. ExecuteQuery ("select * from USERS ");
- } Catch (Exception e ){
- E. printStackTrace ();
- }
- // Important: Set the response format to XML.
- Response. setContentType ("text/xml ");
- Response. setCharacterEncoding ("UTF-8 ");
- PrintWriterOut=Response. GetWriter ();
The above code connects the servlet to the database and sets the response format. below is the key code for writing the XML file:
Java code
- While (result. next ()){
- String []Strs=NewString [3];
- Strs [0] = result. getString ("name ");
- Strs [1] = result. getString ("pwd ");
- Strs [2] = result. getString ("school ");
- // ***** Create XMLdocument *******//
- Xml. create (strs );
- }
- Result. close ();
- Stmt. close ();
- Con. close ();
- // ******* Write the XML file to the client ********//
- Xml. output (out );
The xml of the last line is an example of XML. java. Some important methods of XML are as follows:
Java code
- /**
- * Write the XML document to the output stream
- *
- * @ Param out
- * ---- Specified output stream
- * @ Throws Exception
- *
- * Prepared by: Wang jinghui Hunan Agricultural University & Hunan airuijie Investment Management Company
- */
- Public void output (Writer writer) throws Exception {
- TransformerTrans=TransformerFactory. NewInstance (). newTransformer ();
- Trans. setOutputProperty (OutputKeys. ENCODING, "UTF-8 ");
- SourceSource=NewDOMSource (document );
- ResultResult=NewStreamResult (writer );
- Trans. transform (source, result );
- Writer. flush ();
- Writer. close ();
- }
Java code
- /**
- * Create an XML document
- *
- * @ Param strs
- * ------- Transmitted name and password and school Parameters
- *
- * Prepared by: Wang jinghui Hunan Agricultural University & Hunan airuijie Investment Management Company
- */
- Public void create (String [] strs ){
- // ****** Level 1 subnode ******//
- ElementFirst=Document. CreateElement ("user ");
- Root. appendChild (first );
- For (intI=0; I <strs. length; I ++ ){
- If (I= 0 ){
- // ******* Level 2 subnode ******//
- ElementName=Document. CreateElement ("name ");
- Name. appendChild (document. createTextNode (strs [I]);
- First. appendChild (name );
- } If (I= 1 ){
- ElementPwd=Document. CreateElement ("pwd ");
- Pwd. appendChild (document. createTextNode (strs [I]);
- First. appendChild (pwd );
- } If (I= 2 ){
- ElementSchool=Document. CreateElement ("school ");
- School. appendChild (document. createTextNode (strs [I]);
- First. appendChild (school );
- }
- }
- }
In fact, there is no mystery in this example. Remember that XML is the medium for data exchange between Flex and the backend. No matter how the backend data changes, this is the one to export. In this experiment, you can write XML directly in the servlet without querying the database.
If you have any questions, please leave a message. I am also a beginner. Let's make progress together...
Running method:
Step 1: Create a database flex in SQLServer2000, import the SQL statement. SQL in the attachment in the query analyzer, and generate the required table
Step 2: Set flex in the FlexDataService installation directory. war decompress to such as D: \ a), and then copy the flex directory under D: \ a \ web-inf to the WEB-INF of the WEB program, put D: copy the jar package under the \ a \ web-inf \ lib directory to the lib directory under the corresponding WEB program.
Step 4: copy the project file to your MyEclipse Project
Because Flex will involve a lot of files to communicate with Java. If you deploy it before, it would be better. Generally, the deployment is successful based on the preceding steps.
The analysis of the interaction between Flex and Java Servlet has come to an end. I don't know how you feel?
- What are servlets and common Servlet APIs?
- Analysis on the working principle of JSP + JavaBean + Servlet Structure
- At the beginning of JSP Servlet Development
- Java Servlet API documentation
- Configuration of JSP, Servlet, and Bean in Tomcat