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的通讯方式。
建立数据库
写服务器端Java代码
Servlet
- package servlet;
-
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.util.List;
-
- import javax.servlet.servletexception;
- 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 GetProductServlet() {
- 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.
- *
- * @param 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 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 (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() + "</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 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 doPost(HttpServletRequest request, IOException {
-
- this.doGet(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.servletexception;
- 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 GetProductServlet() {
- 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.
- *
- * @param 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 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 (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() + "</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 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 doPost(HttpServletRequest request, IOException {
- this.doGet(request, response);
- }
- /**
- * Initialization of the servlet. <br>
- *
- * @throws servletexception
- * if an error occurs
- */
- public void init() throws servletexception {
- // Put your code here
- }
- }
数据库连接
- public class MyConnection {
- public Connection conn = null;
- public MyConnection() {
- 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://127.0.0.1:3306/flex",
- "root", "root");
- } catch (sqlException ex) {
- System.err.println("conn:" + ex.getMessage());
- }
- }
- public Connection getDbConnection() {
- return conn;
- }
- }
DAO
- 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
- 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.getString("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;
- }
- }
- }
Podo
- public class Product {
- private String name;
- private String type;
- private double price;
- private int num;
- public Product(String name, String type, double price, int num) {
- this.name = name;
- this.type = type;
- this.price = price;
- this.num = num;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getType() {
- return type;
- }
- public void setType(String type) {
- 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;
- }
- }
部署TOMCAT
这一部分略过,如果觉得手动部署比较麻烦,我们可以使用MyEclipse插件。值得注意的是web.xml文件的配置,一定要正确配置servlet,下面我给出正确示例
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
- 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">
- <display-name>Benson</display-name>
- <servlet>
- <description>This is the description </description>
- <display-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>/servlet/GetProductServlet</url-pattern>
- </servlet-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- <login-config>
- <auth-method>BASIC</auth-method>
- </login-config>
- </web-app>
编写FLEX MXML
- <?xml version="1.0" encoding="utf-8"?>
- <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="send()">
- <mx:HTTPService id="service" url="http://localhost:8080/servlet/servlet/GetProductServlet" method="GET" />
- <mx:Script>
- <!--[CDATA[
- private function send():void{
- //发送请求
- service.send();
- }
- ]]-->
- </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.lastResult.products.product}" fontFamily="Times New Roman" fontSize="16">
- <mx:columns>
- <mx:DataGridColumn headerText="商品名称" datafield="name"/>
- <mx:DataGridColumn headerText="商品类别" datafield="type"/>
- <mx:DataGridColumn headerText="商品价格" datafield="price"/>
- <mx:DataGridColumn headerText="剩余数量" datafield="num"/>
- </mx:columns>
- </mx:DataGrid>
- <mx:ApplicationControlBar x="0" y="0" height="70" width="676">
- </mx:ApplicationControlBar>
- </mx:Canvas>
- </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属性相对应。