ITeye博客

Ajax json 实现 异步交互获取数据库数据

ztfjava · 2010-09-13 20:15 · Java · Web前端 · Markdown

这个例子主要 实现了数据的迁移 能在选择了数据库后能自动的将数据库中中的表名在页面上展示

运用了 Ajax动态交互

1.界面:其中的重点为javaScript 的部分主要实现了 异步交互

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

2.dao层取得数据后封装成 json 后返回到客户端 重点是 其中将数据转换成json字符串返回的操作

package com.ztf.dao;

import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.List;

import org.jdom.Element;

import com.url.ajax.json.JSONObject; import com.ztf.Idao.ITableDao; import com.ztf.util.GetConnection;

public class GetOracleTableName implements ITableDao {

public String getAllTableName(String table) {

String sql="select * from tab"; Connection conn = null; Statement st = null; ResultSet rs = null; conn = GetConnection.getconn(); List<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>(); HashMap<String,Object> result = new HashMap<String,Object>(); try { st = conn.createStatement(); rs = st.executeQuery(sql); while(rs.next()){ HashMap<String,String> map = new HashMap<String,String>(); map.put("TABLE", rs.getString(1)); list.add(map); } result.put("TABLES", list); } catch (SQLException e) { e.printStackTrace(); }finally{ try { rs.close(); st.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } } JSONObject jsonObject = new JSONObject(result); String json = jsonObject.toString(); return json; } }

3.请求的 servlet的代码为:

package com.ztf.model;

import java.io.IOException; import java.io.PrintWriter;

import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

import org.jdom.Element;

import com.ztf.dao.GetOracleTableName; import com.ztf.dao.GetSqlTableName;

public class GetTableNameModel extends HttpServlet { public GetTableNameModel() { super(); }

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String name = request.getParameter("typeDb"); if(name.equals("Oracle10g")){ GetOracleTableName getName = new GetOracleTableName(); String json = getName.getAllTableName(""); out.print(json);

}else if(name.equals("SQL2005")){ GetSqlTableName getName = new GetSqlTableName(); String json = getName.getAllTableName(""); out.print(json); } }

}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。