FLex调用servlet连接数据库_第1页
FLex调用servlet连接数据库_第2页
FLex调用servlet连接数据库_第3页
FLex调用servlet连接数据库_第4页
FLex调用servlet连接数据库_第5页
免费预览已结束,剩余8页可下载查看

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、FLex调用servlet连接数据库前言Flex 最重要的部分之一就是和服务器以及数据库的通讯。Flex 提供了三个类来与服务器通讯: HTTPService,RemoteObject 以及WebService。HTTPService 类提供了使用超文本传输协议(HTTP)与服务器通讯的方式。一个Flex 应用程序可以使用GET 或者POST 请求来发送数据到一个服务器并且处理这个请求返回的 XML 或者字符串。使用HTTPService 类,你可以与PHP 页面,ColdFusion 页面,JavaServe页面( jsp),Java servlet, Ruby onRails, 以及ASP

2、 动态网页通讯。与Java Servlet通讯由于本人是Java出身,所以这里就来讨论一下与Servlet的通讯方式。建立数据库这里选用MySql数据库,首先建立如下的数据库表写服务器端Java代码Servletview plaincopy to clipboardprint?package servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.

3、HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import PODO.Product; import db.ProductDao; public class GetProductServlet extends HttpServlet List result; /* * Constructor of the object. */ public GetProductServlet() super(); /* * Destruction

4、 of the servlet. <br> */ public void destroy() super.destroy(); / Just puts "destroy" string in log / Put your code here /* * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * param request * the request send

5、 by the client to the server * param response * the response send by the server to the client * throws ServletException * if an error occurred * throws IOException * if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOExcepti

6、on result = new ProductDao().getProduct(); String xmlContent = "<?xml version='1.0' encoding='utf-8'?><products>" response.setContentType("text/xml;charset=utf-8"); PrintWriter out = response.getWriter(); if (result != null) for (int i = 0; i < resu

7、lt.size(); i+) Product p = (Product) result.get(i); xmlContent += "<product><name>" + p.getName() + "</name><type>" + p.getType() + "</type><price>" + p.getPrice() + "</price><num>" + p.getNum() + "</num&

8、gt;</product>" xmlContent += "</products>" out.print(xmlContent); out.flush(); out.close(); /* * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to * post. * * param request * the request send by the client

9、 to the server * param response * the response send by the server to the client * throws ServletException * if an error occurred * throws IOException * if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException this.doGet

10、(request, response); /* * Initialization of the servlet. <br> * * throws ServletException * if an error occurs */ public void init() throws ServletException / Put your code here package servlet;import java.io.IOException;import java.io.PrintWriter;import java.util.List;import javax.servlet.Ser

11、vletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import PODO.Product;import db.ProductDao;public class GetProductServlet extends HttpServlet List result;/* * Constructor of the object. */public GetProductSe

12、rvlet() super();/* * Destruction of the servlet. <br> */public void destroy() super.destroy(); / Just puts "destroy" string in log/ Put your code here/* * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * par

13、am request * the request send by the client to the server * param response * the response send by the server to the client * throws ServletException * if an error occurred * throws IOException * if an error occurred */public void doGet(HttpServletRequest request, HttpServletResponse response)throws

14、ServletException, IOException result = new ProductDao().getProduct();String xmlContent = "<?xml version='1.0' encoding='utf-8'?><products>"response.setContentType("text/xml;charset=utf-8");PrintWriter out = response.getWriter();if (result != null) for

15、(int i = 0; i < result.size(); i+) Product p = (Product) result.get(i);xmlContent += "<product><name>" + p.getName() + "</name><type>"+ p.getType() + "</type><price>" + p.getPrice()+ "</price><num>" + p.getNum

16、() + "</num></product>"xmlContent += "</products>"out.print(xmlContent);out.flush();out.close();/* * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to * post. * * param request * the request sen

17、d by the client to the server * param response * the response send by the server to the client * throws ServletException * if an error occurred * throws IOException * if an error occurred */public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOExcepti

18、on this.doGet(request, response);/* * Initialization of the servlet. <br> * * throws ServletException * if an error occurs */public void init() throws ServletException / Put your code here 数据库连接view plaincopy to clipboardprint?public class MyConnection public Connection conn = null; public MyC

19、onnection() try / 注册数据库驱动程序为MYSQL驱动 Class.forName("com.mysql.jdbc.Driver"); catch (java.lang.ClassNotFoundException e) System.err.println("mydb(): " + e.getMessage(); try conn = DriverManager.getConnection( "jdbc:mysql:/:3306/flex", "root", "root

20、"); catch (SQLException ex) System.err.println("conn:" + ex.getMessage(); public Connection getDbConnection() return conn; public class MyConnection public Connection conn = null;public MyConnection() try / 注册数据库驱动程序为MYSQL驱动Class.forName("com.mysql.jdbc.Driver"); catch (java

21、.lang.ClassNotFoundException e) System.err.println("mydb(): " + e.getMessage();try conn = DriverManager.getConnection("jdbc:mysql:/:3306/flex","root", "root"); catch (SQLException ex) System.err.println("conn:" + ex.getMessage();public Conne

22、ction getDbConnection() return conn; DAOview plaincopy to clipboardprint?public class ProductDao Connection conn; ResultSet rs; Statement stmt; public ProductDao() conn = new MyConnection().getDbConnection(); try stmt = conn.createStatement(); catch (SQLException e) / TODO Auto-generated catch block

23、 e.printStackTrace(); public List getProduct() List list = new ArrayList(); try String sql = "select * from product" rs = stmt.executeQuery(sql); while (rs.next() String name=rs.getString("name"); String type=rs.getString("type"); double price=Double.parseDouble(rs.getS

24、tring("price"); int num=Integer.parseInt(rs.getString("num"); Product p=new Product(name,type,price,num); list.add(p); rs.close(); stmt.close(); conn.close(); catch (SQLException e) / TODO Auto-generated catch block e.printStackTrace(); finally return list; public class ProductDa

25、o Connection conn;ResultSet rs;Statement stmt;public ProductDao() conn = new MyConnection().getDbConnection();try stmt = conn.createStatement(); catch (SQLException e) / TODO Auto-generated catch blocke.printStackTrace();public List getProduct() List list = new ArrayList();try String sql = "sel

26、ect * from product"rs = stmt.executeQuery(sql);while (rs.next() String name=rs.getString("name");String type=rs.getString("type");double price=Double.parseDouble(rs.getString("price");int num=Integer.parseInt(rs.getString("num");Product p=new Product(name

27、,type,price,num);list.add(p); rs.close(); stmt.close(); conn.close(); catch (SQLException e) / TODO Auto-generated catch blocke.printStackTrace(); finally return list; PODOview plaincopy to clipboardprint?public class Product private String name; private String type; private double price; private in

28、t num; public Product(String name, String type, double price, int num) = name; this.type = type; this.price = price; this.num = num; public String getName() return name; public void setName(String name) = name; public String getType() return type; public void setType(String type)

29、 this.type = type; public double getPrice() return price; public void setPrice(double price) this.price = price; public int getNum() return num; public void setNum(int num) this.num = num; public class Product private String name;private String type;private double price;private int num;public Produc

30、t(String name, String type, double price, int num) = name;this.type = type;this.price = price;this.num = num;public String getName() return name;public void setName(String name) = name;public String getType() return type;public void setType(String type) this.type = type;public do

31、uble getPrice() return price;public void setPrice(double price) this.price = price;public int getNum() return num;public void setNum(int num) this.num = num; 部署TOMCAT这一部分略过,如果觉得手动部署比较麻烦,我们可以使用MyEclipse插件。值得注意的是web.xml文件的配置,一定要正确配置servlet,下面我给出正确示例view plaincopy to clipboardprint?<?xml version=&qu

32、ot;1.0" encoding="UTF-8"?> <web-app version="2.4" xmlns="" xmlns:xsi="" xsi:schemaLocation=" "> <display-name>Benson</display-name> <servlet> <description>This is the description </description> <display-

33、name>This is the display name </display-name> <servlet-name>GetProductServlet</servlet-name> <servlet-class>servlet.GetProductServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>GetProductServlet</servlet-name> <url-pattern&g

34、t;/servlet/GetProductServlet</url-pattern> </servlet-mapping> <welcome-> <welcome-</welcome-file> </welcome-> <login-config> <auth-method>BASIC</auth-method> </login-config> </web-app> <?xml version="1.0" encoding="UTF-

35、8"?><web-app version="2.4" xmlns="" xmlns:xsi="" xsi:schemaLocation=" "> <display-name>Benson</display-name> <servlet> <description>This is the description </description> <display-name>This is the display name

36、</display-name> <servlet-name>GetProductServlet</servlet-name> <servlet-class>servlet.GetProductServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>GetProductServlet</servlet-name> <url-pattern>/servlet/GetProductServlet</

37、url-pattern> </servlet-mapping> <welcome-> <welcome-</welcome-file> </welcome-> <login-config> <auth-method>BASIC</auth-method> </login-config></web-app> 编写FLEX MXMLview plaincopy to clipboardprint?<?xml version="1.0" encoding=

38、"utf-8"?> <mx:Application xmlns:mx="" layout="absolute" creationComplete="send()"> <mx:HTTPService id="service" url="" method="GET" /> <mx:Script> <!-CDATA private function send():void /发送请求 service.send();

39、 -> </mx:Script> <mx:Canvas x="0" y="0" width="100%" height="100%"> <mx:DataGrid x="0" y="68" width="676" height="383" id="productdata" dataProvider="service.lastRduct&q

40、uot; fontFamily="Times New Roman" fontSize="16"> <mx:columns> <mx:DataGridColumn headerText="商品名称" dataField="name"/> <mx:DataGridColumn headerText="商品类别" dataField="type"/> <mx:DataGridColumn headerText="商品价格&q

41、uot; dataField="price"/> <mx:DataGridColumn headerText="剩余数量" dataField="num"/> </mx:columns> </mx:DataGrid> <mx:ApplicationControlBar x="0" y="0" height="70" width="676"> </mx:ApplicationControlBar&g

42、t; </mx:Canvas> </mx:Application> <?xml version="1.0" encoding="utf-8"?><mx:Application xmlns:mx="" layout="absolute" creationComplete="send()"><mx:HTTPService id="service" url="" method="GET" /> <mx:Script> <!-CDATA private function send():void /发送请求 service.send(); -> </mx:Script> <

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论