Analysis on interaction between Flex and Java Servlet

Source: Internet
Author: User

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

 
 
  1. <? XmlVersion="1.0" Encoding=UTF-8"? >
  2. <Mx: ApplicationXmlns: mx=Http://www.adobe.com/2006/mxml" Layout="Absolute">
  3. <Mx: ModelSource=& Quot; http: // localhost: 8080/flex/first & quot" Id="Model">
  4. </Mx: Model>
  5. <Mx: PanelTitle="User information" Width="776" Height="281" FontSize="18">
  6. <Mx: DataGridDataProvider="{Model. user }" Width="748" Height="231">
  7. <Mx: columns>
  8. <Mx: DataGridColumnDataField="Name" HeaderText="User">
  9. </Mx: DataGridColumn>
  10. <Mx: DataGridColumnDataField="Pwd" HeaderText="Password">
  11. </Mx: DataGridColumn>
  12. <Mx: DataGridColumnDataField="School" HeaderText="Current School">
  13. </Mx: DataGridColumn>
  14. </Mx: columns>
  15. </Mx: DataGrid>
  16. </Mx: Panel>
  17. </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

 
 
  1. Try {
  2. Xml. init ();
  3. Class. forName ("com. microsoft. jdbc. sqlserver. SQLServerDriver ");
  4. // ********** Create a database named flex *************//
  5. StringUrl="Jdbc: microsoft: sqlserver: // localhost: 1433; DatabaseName = flex";
  6. // *********** Change your username and password information ************//
  7. Con=DriverManager. GetConnection (url, "sa", "135780 ");
  8. Stmt=Con. CreateStatement ();
  9. // Create a table named USERS in ********** for details about the SQL statement, see Attachment download **********//
  10. Result=Stmt. ExecuteQuery ("select * from USERS ");
  11. } Catch (Exception e ){
  12. E. printStackTrace ();
  13. }
  14. // Important: Set the response format to XML.
  15. Response. setContentType ("text/xml ");
  16. Response. setCharacterEncoding ("UTF-8 ");
  17. 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

 
 
  1. While (result. next ()){
  2. String []Strs=NewString [3];
  3. Strs [0] = result. getString ("name ");
  4. Strs [1] = result. getString ("pwd ");
  5. Strs [2] = result. getString ("school ");
  6. // ***** Create XMLdocument *******//
  7. Xml. create (strs );
  8. }
  9. Result. close ();
  10. Stmt. close ();
  11. Con. close ();
  12. // ******* Write the XML file to the client ********//
  13. 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

 
 
  1. /**
  2. * Write the XML document to the output stream
  3. *
  4. * @ Param out
  5. * ---- Specified output stream
  6. * @ Throws Exception
  7. *
  8. * Prepared by: Wang jinghui Hunan Agricultural University & Hunan airuijie Investment Management Company
  9. */
  10. Public void output (Writer writer) throws Exception {
  11. TransformerTrans=TransformerFactory. NewInstance (). newTransformer ();
  12. Trans. setOutputProperty (OutputKeys. ENCODING, "UTF-8 ");
  13. SourceSource=NewDOMSource (document );
  14. ResultResult=NewStreamResult (writer );
  15. Trans. transform (source, result );
  16. Writer. flush ();
  17. Writer. close ();
  18. }

Java code

 
 
  1. /**
  2. * Create an XML document
  3. *
  4. * @ Param strs
  5. * ------- Transmitted name and password and school Parameters
  6. *
  7. * Prepared by: Wang jinghui Hunan Agricultural University & Hunan airuijie Investment Management Company
  8. */
  9. Public void create (String [] strs ){
  10. // ****** Level 1 subnode ******//
  11. ElementFirst=Document. CreateElement ("user ");
  12. Root. appendChild (first );
  13. For (intI=0; I <strs. length; I ++ ){
  14. If (I= 0 ){
  15. // ******* Level 2 subnode ******//
  16. ElementName=Document. CreateElement ("name ");
  17. Name. appendChild (document. createTextNode (strs [I]);
  18. First. appendChild (name );
  19. } If (I= 1 ){
  20. ElementPwd=Document. CreateElement ("pwd ");
  21. Pwd. appendChild (document. createTextNode (strs [I]);
  22. First. appendChild (pwd );
  23. } If (I= 2 ){
  24. ElementSchool=Document. CreateElement ("school ");
  25. School. appendChild (document. createTextNode (strs [I]);
  26. First. appendChild (school );
  27. }
  28. }
  29. }

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?

  1. What are servlets and common Servlet APIs?
  2. Analysis on the working principle of JSP + JavaBean + Servlet Structure
  3. At the beginning of JSP Servlet Development
  4. Java Servlet API documentation
  5. Configuration of JSP, Servlet, and Bean in Tomcat

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.