FLex調用servlet連接數據庫

本文轉帖自:http://blog.csdn.net/pengpeng2395/article/details/4157421#comments 

FLex調用servlet連接數據庫

前言

Flex 最重要的部分之一就是和服務器以及數據庫的通訊。Flex 提供了三個類來與服務器通訊: HTTPService,RemoteObject 以及WebService。

HTTPService 類提供了使用超文本傳輸協議(HTTP)與服務器通訊的方式。一個Flex 應用程序可以使用GET 或者POST 請求來發送數據到一個服務器並且處理這個請求返回的 XML 或者字符串。使用HTTPService 類,你可以與PHP 頁面,ColdFusion 頁面,JavaServe頁面( jsp),Java servlet, Ruby onRails, 以及ASP 動態網頁通訊。

與Java Servlet通訊

由於本人是Java出身,所以這裏就來討論一下與Servlet的通訊方式。

建立數據庫

這裏選用MySql數據庫,首先建立如下的數據庫表

寫服務器端Java代碼

Servlet

  1. package servlet;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5. import java.util.List;  
  6.   
  7. import javax.servlet.ServletException;  
  8. import javax.servlet.http.HttpServlet;  
  9. import javax.servlet.http.HttpServletRequest;  
  10. import javax.servlet.http.HttpServletResponse;  
  11.   
  12. import PODO.Product;  
  13. import db.ProductDao;  
  14.   
  15. public class GetProductServlet extends HttpServlet {  
  16.     List result;  
  17.   
  18.     /** 
  19.      * Constructor of the object. 
  20.      */  
  21.     public GetProductServlet() {  
  22.         super();  
  23.     }  
  24.   
  25.     /** 
  26.      * Destruction of the servlet. <br> 
  27.      */  
  28.     public void destroy() {  
  29.         super.destroy(); // Just puts "destroy" string in log   
  30.         // Put your code here   
  31.     }  
  32.   
  33.     /** 
  34.      * The doGet method of the servlet. <br> 
  35.      *  
  36.      * This method is called when a form has its tag value method equals to get. 
  37.      *  
  38.      * @param request 
  39.      *            the request send by the client to the server 
  40.      * @param response 
  41.      *            the response send by the server to the client 
  42.      * @throws ServletException 
  43.      *             if an error occurred 
  44.      * @throws IOException 
  45.      *             if an error occurred 
  46.      */  
  47.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  48.             throws ServletException, IOException {  
  49.         result = new ProductDao().getProduct();  
  50.         String xmlContent = "<?xml version='1.0' encoding='utf-8'?><products>";  
  51.         response.setContentType("text/xml;charset=utf-8");  
  52.         PrintWriter out = response.getWriter();  
  53.         if (result != null) {  
  54.             for (int i = 0; i < result.size(); i++) {  
  55.                 Product p = (Product) result.get(i);  
  56.                 xmlContent += "<product><name>" + p.getName() + "</name><type>"  
  57.                         + p.getType() + "</type><price>" + p.getPrice()  
  58.                         + "</price><num>" + p.getNum() + "</num></product>";  
  59.             }  
  60.             xmlContent += "</products>";  
  61.             out.print(xmlContent);  
  62.             out.flush();  
  63.             out.close();  
  64.         }  
  65.   
  66.     }  
  67.   
  68.     /** 
  69.      * The doPost method of the servlet. <br> 
  70.      *  
  71.      * This method is called when a form has its tag value method equals to 
  72.      * post. 
  73.      *  
  74.      * @param request 
  75.      *            the request send by the client to the server 
  76.      * @param response 
  77.      *            the response send by the server to the client 
  78.      * @throws ServletException 
  79.      *             if an error occurred 
  80.      * @throws IOException 
  81.      *             if an error occurred 
  82.      */  
  83.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  84.             throws ServletException, IOException {  
  85.   
  86.         this.doGet(request, response);  
  87.     }  
  88.   
  89.     /** 
  90.      * Initialization of the servlet. <br> 
  91.      *  
  92.      * @throws ServletException 
  93.      *             if an error occurs 
  94.      */  
  95.     public void init() throws ServletException {  
  96.         // Put your code here   
  97.     }  
  98. }  

數據庫連接

  1. public class MyConnection {  
  2.     public Connection conn = null;  
  3.   
  4.     public MyConnection() {  
  5.         try {  
  6.             // 註冊數據庫驅動程序爲MYSQL驅動   
  7.             Class.forName("com.mysql.jdbc.Driver");  
  8.         } catch (java.lang.ClassNotFoundException e) {  
  9.               
  10.             System.err.println("mydb(): " + e.getMessage());  
  11.         }  
  12.   
  13.         try {  
  14.             conn = DriverManager.getConnection(  
  15.                     "jdbc:mysql://127.0.0.1:3306/flex",  
  16.                     "root", "root");  
  17.         } catch (SQLException ex) {  
  18.             System.err.println("conn:" + ex.getMessage());  
  19.         }  
  20.     }  
  21.   
  22.     public Connection getDbConnection() {  
  23.         return conn;  
  24.     }  
  25. }  

 

DAO

  1. public class ProductDao {  
  2.     Connection conn;  
  3.     ResultSet rs;  
  4.     Statement stmt;  
  5.   
  6.     public ProductDao() {  
  7.         conn = new MyConnection().getDbConnection();  
  8.         try {  
  9.             stmt = conn.createStatement();  
  10.         } catch (SQLException e) {  
  11.             // TODO Auto-generated catch block   
  12.             e.printStackTrace();  
  13.         }  
  14.     }  
  15.   
  16.     public List getProduct() {  
  17.         List list = new ArrayList();  
  18.         try {  
  19.             String sql = "select * from product";  
  20.             rs = stmt.executeQuery(sql);  
  21.             while (rs.next()) {  
  22.                 String name=rs.getString("name");  
  23.                 String type=rs.getString("type");  
  24.                 double price=Double.parseDouble(rs.getString("price"));  
  25.                 int num=Integer.parseInt(rs.getString("num"));  
  26.                 Product p=new Product(name,type,price,num);  
  27.                 list.add(p);  
  28.             }  
  29.               rs.close();  
  30.               stmt.close();  
  31.               conn.close();  
  32.               
  33.         } catch (SQLException e) {  
  34.             // TODO Auto-generated catch block   
  35.             e.printStackTrace();  
  36.         } finally {  
  37.             return list;  
  38.         }  
  39.   
  40.     }  
  41.   
  42. }  

 

PODO

  1. public class Product {  
  2.     private String name;  
  3.     private String type;  
  4.     private double price;  
  5.     private int num;  
  6.   
  7.     public Product(String name, String type, double price, int num) {  
  8.         this.name = name;  
  9.         this.type = type;  
  10.         this.price = price;  
  11.         this.num = num;  
  12.     }  
  13.   
  14.     public String getName() {  
  15.         return name;  
  16.     }  
  17.   
  18.     public void setName(String name) {  
  19.         this.name = name;  
  20.     }  
  21.   
  22.     public String getType() {  
  23.         return type;  
  24.     }  
  25.   
  26.     public void setType(String type) {  
  27.         this.type = type;  
  28.     }  
  29.   
  30.     public double getPrice() {  
  31.         return price;  
  32.     }  
  33.   
  34.     public void setPrice(double price) {  
  35.         this.price = price;  
  36.     }  
  37.   
  38.     public int getNum() {  
  39.         return num;  
  40.     }  
  41.   
  42.     public void setNum(int num) {  
  43.         this.num = num;  
  44.     }  
  45.   
  46. }  

 

部署TOMCAT

這一部分略過,如果覺得手動部署比較麻煩,我們可以使用MyEclipse插件。值得注意的是web.xml文件的配置,一定要正確配置servlet,下面我給出正確示例

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"  
  3.  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
  4.  <display-name>Benson</display-name>  
  5.    <servlet>  
  6.     <description>This is the description </description>  
  7.     <display-name>This is the display name </display-name>  
  8.     <servlet-name>GetProductServlet</servlet-name>  
  9.     <servlet-class>servlet.GetProductServlet</servlet-class>  
  10.   </servlet>  
  11.   
  12.   <servlet-mapping>  
  13.     <servlet-name>GetProductServlet</servlet-name>  
  14.     <url-pattern>/servlet/GetProductServlet</url-pattern>  
  15.   </servlet-mapping>  
  16.  <welcome-file-list>  
  17.   <welcome-file>index.jsp</welcome-file>  
  18.  </welcome-file-list>  
  19.  <login-config>  
  20.   <auth-method>BASIC</auth-method>  
  21.  </login-config>  
  22. </web-app>  

編寫FLEX MXML

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="send()">  
  3.     <mx:HTTPService id="service" url="http://localhost:8080/servlet/servlet/GetProductServlet" method="GET" />   
  4.      <mx:Script>    
  5.           <!--[CDATA[   
  6.               private function send():void{   
  7.                   //發送請求   
  8.                   service.send();   
  9.               }   
  10.           ]]-->    
  11.       </mx:Script>    
  12.      <mx:Canvas x="0" y="0" width="100%" height="100%">  
  13.          <mx:DataGrid x="0" y="68" width="676" height="383" id="productdata" dataProvider="{service.lastResult.products.product}" fontFamily="Times New Roman" fontSize="16">  
  14.              <mx:columns>  
  15.                  <mx:DataGridColumn headerText="商品名稱" dataField="name"/>  
  16.                  <mx:DataGridColumn headerText="商品類別" dataField="type"/>  
  17.                  <mx:DataGridColumn headerText="商品價格" dataField="price"/>  
  18.                  <mx:DataGridColumn headerText="剩餘數量" dataField="num"/>  
  19.              </mx:columns>  
  20.          </mx:DataGrid>  
  21.          <mx:ApplicationControlBar x="0" y="0" height="70" width="676">  
  22.          </mx:ApplicationControlBar>  
  23.      </mx:Canvas>  
  24. </mx:Application>  

 

代碼重點解釋

1.       creationComplete="send()"

表明當這個Flex應用創建完成時,就發送這個HttpServer請求給Servlet

2.     url=http://localhost:8080/servlet/servlet/GetProductServlet

第一個servlet是我們服務器端的工程名

第二個servelt是servlet所在包名

GetProductServlet使我們真正的servlet名稱

3.       dataProvider="{service.lastResult.products.product}"

a. lastResult:在做了一個呼叫到一個HTTPService 之後,數據會從服務返回,並被放置到服務組件所包含的lastResult 對象。

b. 由於我們返回的是一個XML數據,所以service.lastResult.products.product就代表返回XML中products標籤下的所有product標籤內容。

c.  Product子標籤和Flex中<mx:columns>的dataField屬性相對應。

結果圖

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章