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
- 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, HttpServletResponse response)
- throws ServletException, 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屬性相對應。
結果圖