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

[c-sharp] view plain copy print ?
  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属性相对应。

结果图

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值