分享

Ext与后台数据库交互...

 yfm10 2009-09-17

Ext与后台数据库交互

 

新建个user.js 里面放入一下内容:

Ext.onReady(function() {

 var record_start = 0;
 
 var num = function(v,p,Record,rowIndex){
  return record_start + rowIndex + 1;
 };
 
 function renderSex(value) {
  if (value == '1') {

   return "<span style='color:blue'>先生</span>";
  } else {

   return "<span style='color:orange'>女士</span>";
  }
 }
 
    var comboSex = [
        ['0','女'],
        ['1','男']
    ];
   
 var sm = new Ext.grid.CheckboxSelectionModel({
  handleMouseDown : Ext.emptyFn
 });                  // 创建复选框

 var cm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer({
  renderer : num
 }), // 创建自动行号
   sm, {
    header : '姓名',
    dataIndex : 'stuName',
    editor : new Ext.grid.GridEditor(new Ext.form.TextField({
     allowBlank : false
    })),
    sortable : true
   },  {
    header : '性别',
    dataIndex : 'stuSex',
    editor : new Ext.grid.GridEditor(new Ext.form.ComboBox({
     store : new Ext.data.SimpleStore({
      fields : ['value', 'text'],
      data : comboSex
     }),
     emptyText : '请选择',
     mode : 'local',
     triggerAction : 'all',
     valueField : 'value',
     displayField : 'text',
     readOnly : true
    })),
    renderer : renderSex,
    sortable : true
   }, {
    header : '年龄',
    dataIndex : 'stuAge',
    editor : new Ext.grid.GridEditor(new Ext.form.NumberField({
     allowBlank : false
    })),
    sortable : true
   }, {
    header : '住址',
    dataIndex : 'stuAddr',
    editor : new Ext.grid.GridEditor(new Ext.form.TextField({
     allowBlank : false
    })),
    sortable : true
   }, {
    header : '电话',
    dataIndex : 'stuTel',
    editor : new Ext.grid.GridEditor(new Ext.form.NumberField({
     allowBlank : false
    })),
    sortable : true
   }]);


 // 定义类型
 var Record = Ext.data.Record.create([{
  name : 'stuId',
  type : 'int'
 }, {
  name : 'clsId',
  type : 'int'
 }, {
  name : 'stuSex',
  type : 'int'
 }, {
  name : 'stuName',
  type : 'string'
 }, {
  name : 'stuAge',
  type : 'int'
 },{
  name : 'stuAddr',
  type : 'string'
 },{
  name : 'stuTel',
  type : 'String'
 }]);

 var store = new Ext.data.Store({

  proxy : new Ext.data.HttpProxy({
   url : 'servlet/Query'
  }),

  pruneModifiedRecords: true,
  
  reader : new Ext.data.JsonReader({

   totalProperty : 'totalProperty',
   root : 'root'
  }, [{
   name : 'stuId'
  }, {
   name : 'clsId'
  }, {
   name : 'stuSex'
  }, {
   name : 'stuName'
  }, {
   name : 'stuAge'
  }, {
   name : 'stuAddr'
  }, {
   name : 'stuTel'
  }])
 });

 // var grid = new Ext.grid.GridPanel({ // 不可编辑的grid

 var grid = new Ext.grid.EditorGridPanel({ // 可编辑的grid

  title : '学生信息管理',
  autoHeight : true,
  cm : cm,
  sm : sm,
  renderTo : 'grid',
  store : store,
  // 分页底端显示工具条
  bbar : new Ext.PagingToolbar({
   pageSize : 10,
   displayInfo : true,
   store : store,
   displayMsg : '显示第{0}条到{1}条记录,一共{2}条',
   emptyMsg : '没有记录',
   doLoad: function(start){
    record_start = start;
    var o = {},pn = this.paramNames;
    o[pn.start] = start;
    o[pn.limit] = this.pageSize;
    this.store.load({params:o});
   }
  }),

  // 添加与删除顶端显示工具条
  tbar : new Ext.Toolbar(['-', {

   text : '添加一行',
   handler : function() {

    var p = new Record({
     stuId : '',
     clsId: '1',
     stuSex : '',
     stuName : '',
     stuAge : '',
     stuAddr : '',
     stuTel: ''
    });
    grid.stopEditing();
    store.insert(0, p);
    grid.startEditing(0, 2);
   }
  }, '-', {
   text : '删除一行',
   handler : function() {
    Ext.Msg.confirm('信息', '确定要删除?', function(btn) {
     if (btn == 'yes') {
      var cells = sm.getSelections();
      var jsonArray = [];
      for (var i = 0; i < cells.length; i++) {
       
       jsonArray.push(cells[i].data);
//        store.remove(cells[i]);
      }
      Ext.lib.Ajax.request('POST', 'servlet/Del', {
       success : function(response) {
        Ext.Msg.alert('信息', response.responseText,
          function() {
           store.reload();
          });
       },
       failure : function() {
        Ext.Msg.alert("错误", "与后台联系的时候出现了问题");
       }
      }, 'data=' + encodeURIComponent(Ext.encode(jsonArray)));
     }
    });
   }
  }, '-', {
            text: '保存',
            handler: function(){
                var m = store.modified.slice(0);
                var jsonArray = [];
                Ext.each(m, function(item) {
                    jsonArray.push(item.data);
                });

                Ext.lib.Ajax.request(
                    'POST',
                    'servlet/Save',
                    {success: function(response){
                        Ext.Msg.alert('信息', response.responseText, function(){
                            store.reload();
                        });
                    },failure: function(){
                        Ext.Msg.alert("错误", "与后台联系的时候出现了问题");
                    }},
                    'data=' + encodeURIComponent(Ext.encode(jsonArray))
                );
            }
        }, '-']),

  viewConfig : {
   forceFit : true
  }

 });

 store.load({
  params : {
   start : 0,
   limit : 10
  }
 });
});

 

新建个index.jsp页面 放入以下内容:

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

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
   
    <title>ExtJsDemo</title>
  
 <link rel="stylesheet" type="text/css" href="ext/resources/css/ext-all.css">
 
 <script type="text/javascript" src="ext/adapter/ext/ext-base.js"></script>
 
 <script type="text/javascript" src="ext/ext-all-debug.js"></script>
 
 <script type="text/javascript" src="ext/ext-fun.js"></script>
 
 <script type="text/javascript" src="ext/PagingMemoryProxy.js"></script>
 
 <script type="text/javascript" src="js/user.js"></script>

  </head>
 
  <body>
    <div id="grid"></div>
  </body>
</html>

配置下web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
 xmlns="http://java./xml/ns/j2ee"
 xmlns:xsi="http://www./2001/XMLSchema-instance"
 xsi:schemaLocation="http://java./xml/ns/j2ee
 http://java./xml/ns/j2ee/web-app_2_4.xsd">
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>Query</servlet-name>
    <servlet-class>ext.servlet.Query</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>Save</servlet-name>
    <servlet-class>ext.servlet.Save</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>Del</servlet-name>
    <servlet-class>ext.servlet.Del</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>GetCls</servlet-name>
    <servlet-class>ext.servlet.GetCls</servlet-class>
  </servlet>

 


  <servlet-mapping>
    <servlet-name>Query</servlet-name>
    <url-pattern>/servlet/Query</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>Save</servlet-name>
    <url-pattern>/servlet/Save</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>Del</servlet-name>
    <url-pattern>/servlet/Del</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>GetCls</servlet-name>
    <url-pattern>/servlet/GetCls</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
上面的web.xml是自动生成的......

 

后台的实现:  dao

basedao:

package ext.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BaseDao {

 public final String url = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8";

 public final String user = "root";

 public final String pwd = "root";

 private Connection conn = null;

 private ResultSet rs = null;

 public PreparedStatement pstm = null;

 public BaseDao() {
  try {
   Class.forName("com.mysql.jdbc.Driver");
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  }

 }

 /**
  *
  * @Function getConnection()
  * @return Connection
  */
 public Connection getConnection() {

  try {
   conn = DriverManager.getConnection(url, user, pwd);
   return conn;
  } catch (SQLException e) {

   e.printStackTrace();
   return null;
  }
 }

 /**
  *
  * @Function closePreparedStatement()
  */
 public void closePreparedStatement() {
  try {
   this.pstm.close();
  } catch (SQLException e) {

   e.printStackTrace();
  }
 }

 /**
  *
  * @Function closeConnection()
  */
 public void closeConnection() {
  try {
   this.conn.close();
  } catch (SQLException e) {

   e.printStackTrace();
  }
 }

 /**
  *
  * @Function exectueQuery()
  * @param sql
  * @return ResultSet
  */
 public ResultSet exectueQuery(String sql) {

  conn = this.getConnection();
  try {
//   pstm = conn.prepareStatement(sql);
   rs = pstm.executeQuery();
  } catch (SQLException e) {

   e.printStackTrace();
  }
  return rs;
 }

 /**
  *
  * @Function executeUpdate()
  * @throws SQLException
  */
 public void executeUpdate() throws SQLException {

  pstm.executeUpdate();

  this.closePreparedStatement();

  this.closeConnection();
 }

 /**
  *
  * @Function executeDelete()
  * @throws SQLException
  */
 public void executeDelete() throws SQLException {

  pstm.executeUpdate();

  this.closePreparedStatement();

  this.closeConnection();
 }

 /**
  *
  * @Function executeInsert()
  * @throws SQLException
  */
 public void executeInsert() throws SQLException {

  pstm.executeUpdate();

  this.closePreparedStatement();

  this.closeConnection();
 }

 /**
  *
  * @Function preparedStatement()
  * @param sql
  * @throws SQLException
  */
 public void preparedStatement(String sql) throws SQLException {

  conn = this.getConnection();

  pstm = conn.prepareStatement(sql);
 }
}

userdao:

package ext.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import ext.po.Clasz;
import ext.po.User;

public class UserDao extends BaseDao {
 public UserDao() {
 }

 /**
  *
  * @Function getUser()
  * @return List<User>
  * @throws SQLException
  */
 public List<User> getUser(int start, int limit) {

  String sql = "select * from student LIMIT ?,?";

  try {
   this.preparedStatement(sql);

   pstm.setInt(1, start);

   pstm.setInt(2, limit);
  } catch (SQLException e1) {
   e1.printStackTrace();
  }

  List<User> list = new ArrayList<User>();

  User user = null;

  ResultSet rs = this.exectueQuery(sql);

  try {
   while (rs.next()) {

    user = new User();

    user.setStuId(rs.getInt("stu_id"));
    user.setClsId(rs.getInt("cls_id"));
    user.setStuName(rs.getString("stu_name"));
    user.setStuSex(rs.getInt("stu_sex"));
    user.setStuAge(rs.getInt("stu_age"));
    user.setStuAddr(rs.getString("stu_addr"));
    user.setStuTel(rs.getString("stu_tel"));

    list.add(user);
   }
  } catch (SQLException e) {
   e.printStackTrace();
  }
  this.closePreparedStatement();

  this.closeConnection();

  return list;

 }

 /**
  *
  * @return
  */
 public int getCount() {

  String sql = "select count(*) from student";

  try {
   this.preparedStatement(sql);

   ResultSet rs = this.exectueQuery(sql);

   while (rs.next()) {

    return rs.getInt(1);
   }
  } catch (SQLException e) {
   e.printStackTrace();
  }

  return 0;
 }

 /**
  *
  * @Function addUser()
  * @param user
  * @throws SQLException
  */
 public void addUser(User user) throws SQLException {

  String sql = "insert into student(cls_id,stu_name,stu_sex,stu_age,stu_addr,stu_tel) values(?,?,?,?,?,?)";

  this.preparedStatement(sql);

  pstm.setInt(1, user.getClsId());
  pstm.setString(2, user.getStuName());
  pstm.setInt(3, user.getStuSex());
  pstm.setInt(4, user.getStuAge());
  pstm.setString(5, user.getStuAddr());
  pstm.setString(6, user.getStuTel());

  this.executeInsert();
 }

 /**
  *
  * @Function editUser()
  * @param user
  * @throws SQLException
  */
 public void editUser(User user) throws SQLException {

  String sql = "update student set stu_name=?," + "stu_sex=?," + "stu_age=?," + "stu_addr=?," + "stu_tel=? "
    + "where stu_id=?";

  this.preparedStatement(sql);

  pstm.setString(1, user.getStuName());
  pstm.setInt(2, user.getStuSex());
  pstm.setInt(3, user.getStuAge());
  pstm.setString(4, user.getStuAddr());
  pstm.setString(5, user.getStuTel());
  pstm.setInt(6, user.getStuId());

  this.executeUpdate();
 }

 /**
  *
  * @Function deleteUser()
  * @param user
  * @throws SQLException
  */
 public void deleteUser(Integer id) throws SQLException {

  String sql = "delete  from student where stu_id=?";

  this.preparedStatement(sql);

  pstm.setInt(1, id);

  this.executeDelete();
 }

 /**
  *
  * function : 获取班级列表
  *
  * @return
  *
  * @author wxl Jul 17, 2009
  */
 public List<Clasz> getClassList() {

  List<Clasz> list = new ArrayList<Clasz>();

  String sql = "select * from class order by cls_cdate desc";

  try {

   this.preparedStatement(sql);

   ResultSet rs = this.exectueQuery(sql);

   while (rs.next()) {

    Clasz cls = new Clasz();

    cls.setClsId(rs.getInt("cls_id"));
    cls.setClsName(rs.getString("cls_name"));

    list.add(cls);
   }

  } catch (Exception ex) {

  }

  return list;
 }
}

 

bo实现:

 

package ext.bo;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;

import ext.dao.UserDao;
import ext.po.Clasz;
import ext.po.User;

public class UserBo {

 /**
  *
  * function : 从数据库获取数据并转化成json数据
  *
  * @param start
  *            开始位置
  * @param limit
  *            每页条数
  * @return
  *
  * @author wxl Jul 16, 2009
  */
 public String getJsonData(int start, int limit) {

  UserDao uDao = new UserDao();

  List<User> list = uDao.getUser(start, limit);

  StringBuffer sb = new StringBuffer();

  int count = uDao.getCount();

  sb.append("{totalProperty:");

  sb.append(count);

  sb.append(",root:[");

  for (User user : list) {
   sb.append("{");
   sb.append("stuId:" + user.getStuId() + ",");
   sb.append("clsId:" + user.getClsId() + ",");
   sb.append("stuSex:" + user.getStuSex() + ",");
   sb.append("stuName:'" + user.getStuName() + "',");
   sb.append("stuAge:" + user.getStuAge() + ",");
   sb.append("stuAddr:'" + user.getStuAddr() + "',");
   sb.append("stuTel:'" + user.getStuTel() + "'");
   sb.append("},");
  }
  sb.append("]}");

  return sb.substring(0, sb.lastIndexOf(",")) + sb.substring(sb.lastIndexOf(",") + 1);
 }

 /**
  *
  * function : 保存或修改数据
  *
  * @param data
  *
  * @author wxl Jul 17, 2009
  */
 public void saveOrUpdate(String jsonData) {

  UserDao uDao = new UserDao();

  List<User> list = this.getUserFromJson(jsonData);
  try {
   if (list != null && list.size() > 0) {

    for (User user : list) {

     if (user.getStuId() != null && !"".equals(user.getStuId())) {

      uDao.editUser(user);

     } else {
      uDao.addUser(user);
     }
    }
   }
  } catch (SQLException e) {
   e.printStackTrace();
  }
 }

 /**
  *
  * function : 把Json数据转化成List
  *
  * @param jsonData
  * @return
  *
  * @author wxl Jul 17, 2009
  */
 private List<User> getUserFromJson(String jsonData) {

  List<User> list = new ArrayList<User>();

  try {
   org.json.JSONArray array = new JSONArray(jsonData);

   for (int i = 0; i < array.length(); i++) {

    org.json.JSONObject jo = new org.json.JSONObject(array.get(i).toString());

    User uPo = new User();

    // 班级id
    uPo.setClsId(Integer.parseInt(jo.getString("clsId")));

    // 住址
    uPo.setStuAddr(jo.getString("stuAddr"));

    // 年龄
    String stuAge = jo.getString("stuAge");
    if (stuAge != null && !"".equals(stuAge)) {
     uPo.setStuAge(Integer.parseInt(stuAge));
    } else {
     uPo.setStuAge(0);
    }

    // 姓名
    uPo.setStuName(jo.getString("stuName"));

    // 性别
    String stuSex = jo.getString("stuSex");
    if (stuSex != null && !"".equals(stuSex)) {
     uPo.setStuSex(Integer.parseInt(stuSex));
    } else {
     uPo.setStuSex(0);
    }

    // 电话
    uPo.setStuTel(jo.getString("stuTel"));

    // 学生id
    String stuId = jo.getString("stuId");
    if (stuId != null && !"".equals(stuId)) {

     uPo.setStuId(Integer.parseInt(stuId));

    }
    list.add(uPo);
   }

  } catch (JSONException e) {
   e.printStackTrace();
  }
  return list;
 }

 /**
  *
  * function : 删除数据
  *
  * @param jsonData
  *
  * @author wxl Jul 17, 2009
  */
 public void delUser(String jsonData) {

  UserDao uDao = new UserDao();

  List<User> list = this.getUserFromJson(jsonData);
  try {
   if (list != null && list.size() > 0) {

    for (User user : list) {

     if (user.getStuId() != null && !"".equals(user.getStuId())) {

      uDao.deleteUser(user.getStuId());
     }
    }
   }
  } catch (Exception ex) {
   ex.printStackTrace();
  }
 }

 /**
  *
  *function: 获取班级的json数据
  *
  * @return
  *
  *@author wxl Jul 17, 2009
  */
 public String getClsJsonData() {

  UserDao uDao = new UserDao();

  List<Clasz> list = uDao.getClassList();

  StringBuffer sb = new StringBuffer();

  sb.append("[");

  if (list != null && list.size() > 0) {

   for (Clasz clasz : list) {
    sb.append("['");
    sb.append(clasz.getClsId() + "','");
    sb.append(clasz.getClsName() + "'");
    sb.append("],");
   }

  }
  sb.append("]");
  return sb.substring(0, sb.lastIndexOf(",")) + sb.substring(sb.lastIndexOf(",") + 1);
 }
}

 

formbean::实现

package ext.po;

public class User {

 private Integer stuId;
 
 private Integer clsId;
 
 private String stuName;
 
 private Integer stuSex;
 
 private Integer stuAge;
 
 private String stuAddr;
 
 private String stuTel;

 public Integer getStuId() {
  return stuId;
 }

 public void setStuId(Integer stuId) {
  this.stuId = stuId;
 }

 public Integer getClsId() {
  return clsId;
 }

 public void setClsId(Integer clsId) {
  this.clsId = clsId;
 }

 public String getStuName() {
  return stuName;
 }

 public void setStuName(String stuName) {
  this.stuName = stuName;
 }

 public Integer getStuSex() {
  return stuSex;
 }

 public void setStuSex(Integer stuSex) {
  this.stuSex = stuSex;
 }

 public Integer getStuAge() {
  return stuAge;
 }

 public void setStuAge(Integer stuAge) {
  this.stuAge = stuAge;
 }

 public String getStuAddr() {
  return stuAddr;
 }

 public void setStuAddr(String stuAddr) {
  this.stuAddr = stuAddr;
 }

 public String getStuTel() {
  return stuTel;
 }

 public void setStuTel(String stuTel) {
  this.stuTel = stuTel;

另外个formbean:

package ext.po;

public class Clasz {

 private Integer clsId;
 
 private String clsName;

 public Integer getClsId() {
  return clsId;
 }

 public void setClsId(Integer clsId) {
  this.clsId = clsId;
 }

 public String getClsName() {
  return clsName;
 }

 public void setClsName(String clsName) {
  this.clsName = clsName;
 }
}

 }
}

util实现:

package ext.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JsonUtil {

   /** *//**
    * 从一个JSON 对象字符格式中得到一个java对象
    *
    * @param jsonString
    * @param pojoCalss
    * @return
    */
    public static Object getObject4JsonString(String jsonString,Class pojoCalss) {
        Object pojo;
        JSONObject jsonObject = JSONObject.fromObject( jsonString ); 
        pojo = JSONObject.toBean(jsonObject,pojoCalss);
        return pojo;
    }
   
   
   
    /** *//**
    * 从json HASH表达式中获取一个map,改map支持嵌套功能
    *
    * @param jsonString
    * @return
    */
    public static Map getMap4Json(String jsonString) {
        JSONObject jsonObject = JSONObject.fromObject( jsonString ); 
        Iterator  keyIter = jsonObject.keys();
        String key;
        Object value;
        Map valueMap = new HashMap();

        while( keyIter.hasNext())
         {
            key = (String)keyIter.next();
            value = jsonObject.get(key);
            valueMap.put(key, value);
        }
       
        return valueMap;
    }
   
   
    /** *//**
    * 从json数组中得到相应java数组
    *
    * @param jsonString
    * @return
    */
    public static Object[] getObjectArray4Json(String jsonString) {
        JSONArray jsonArray = JSONArray.fromObject(jsonString);
        return jsonArray.toArray();
       
    }
   
   
    /** *//**
    * 从json对象集合表达式中得到一个java对象列表
    *
    * @param jsonString
    * @param pojoClass
    * @return
    */
    public static List getList4Json(String jsonString, Class pojoClass) {
       
        JSONArray jsonArray = JSONArray.fromObject(jsonString);
        JSONObject jsonObject;
        Object pojoValue;
       
        List list = new ArrayList();
        for ( int i = 0 ; i<jsonArray.size(); i++) {
           
            jsonObject = jsonArray.getJSONObject(i);
            pojoValue = JSONObject.toBean(jsonObject,pojoClass);
            list.add(pojoValue);
           
        }
        return list;

    }
   
    /** *//**
    * 从json数组中解析出java字符串数组
    *
    * @param jsonString
    * @return
    */
    public static String[] getStringArray4Json(String jsonString) {
       
        JSONArray jsonArray = JSONArray.fromObject(jsonString);
        String[] stringArray = new String[jsonArray.size()];
        for( int i = 0 ; i<jsonArray.size() ; i++ ) {
            stringArray[i] = jsonArray.getString(i);
           
        }
       
        return stringArray;
    }
   
    /** *//**
    * 从json数组中解析出javaLong型对象数组
    *
    * @param jsonString
    * @return
    */
    public static Long[] getLongArray4Json(String jsonString){
       
        JSONArray jsonArray = JSONArray.fromObject(jsonString);
        Long[] longArray = new Long[jsonArray.size()];
        for( int i = 0 ; i<jsonArray.size() ; i++ ) {
            longArray[i] = jsonArray.getLong(i);
           
        }
        return longArray;
    }
   
    /** *//**
    * 从json数组中解析出java Integer型对象数组
    *
    * @param jsonString
    * @return
    */
    public static Integer[] getIntegerArray4Json(String jsonString) {
       
        JSONArray jsonArray = JSONArray.fromObject(jsonString);
        Integer[] integerArray = new Integer[jsonArray.size()];
        for( int i = 0 ; i<jsonArray.size() ; i++ ) {
            integerArray[i] = jsonArray.getInt(i);
           
        }
        return integerArray;
    }
   
    /** *//**
    * 从json数组中解析出java Date 型对象数组,使用本方法必须保证
    *
    * @param jsonString
    * @return
    */
//    public static Date[] getDateArray4Json(String jsonString,String DataFormat) {
//       
//        JSONArray jsonArray = JSONArray.fromObject(jsonString);
//        Date[] dateArray = new Date[jsonArray.size()];
//        String dateString;
//        Date date;
//       
//        for( int i = 0 ; i<jsonArray.size() ; i++ ) {
//            dateString = jsonArray.getString(i);
//            date = DateUtil.stringToDate(dateString, DataFormat);
//            dateArray[i] = date;
//           
//        }
//        return dateArray;
//    }
   
    /** *//**
    * 从json数组中解析出java Integer型对象数组
    *
    * @param jsonString
    * @return
    */
//    public static Double[] getDoubleArray4Json(String jsonString) {
//       
//        JSONArray jsonArray = JSONArray.fromObject(jsonString);
//        Double[] doubleArray = new Double[jsonArray.size()];
//        for( int i = 0 ; i<jsonArray.size() ; i++ ) {
//            doubleArray[i] = jsonArray.getDouble(i);
//           
//        }
//        return doubleArray;
//    }
   
   
    /** *//**
    * 将java对象转换成json字符串
    *
    * @param javaObj
    * @return
    */
    public static String getJsonString4JavaPOJO(Object javaObj) {
       
        JSONObject json;
        json = JSONObject.fromObject(javaObj);
        return json.toString();
       
    }
   
   
   
   
    /** *//**
    * 将java对象转换成json字符串,并设定日期格式
    *
    * @param javaObj
    * @param dataFormat
    * @return
    */
//    public static String getJsonString4JavaPOJO(Object javaObj , String dataFormat) {
//       
//        JSONObject json;
//        JsonConfig jsonConfig = new JsonConfig(dataFormat);
//        json = JSONObject.fromObject(javaObj,jsonConfig);
//        return json.toString();
//       
//       
//    }
}

删除的servlet:

package ext.servlet;

import java.io.IOException;

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

import ext.bo.UserBo;

public class Del extends HttpServlet {

 /**
  * 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 {

  doPost(request, response);
 }

 /**
  * 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 {

  request.setCharacterEncoding("UTF-8");
  response.setCharacterEncoding("UTF-8");

  String jsonData = request.getParameter("data");
  
  UserBo uBo = new UserBo();
  
  uBo.delUser(jsonData);
  
  response.getWriter().print("删除成功!");
 }

}

查询班级的serlvet:

package ext.servlet;

import java.io.IOException;

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

import ext.bo.UserBo;

public class GetCls extends HttpServlet {

 /**
  * 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 {

  doPost(request, response);
 }

 /**
  * 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 {

  request.setCharacterEncoding("utf-8");
  
  response.setCharacterEncoding("utf-8");
  
  UserBo uBo = new UserBo();
  
  String jsonData = uBo.getClsJsonData();
  
  response.getWriter().write(jsonData);
  
  response.getWriter().flush();
 }

}

查询用户的servlet:

package ext.servlet;

import java.io.IOException;

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

import ext.bo.UserBo;

public class Query extends HttpServlet {

 /**
  * 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 {

  doPost(request, response);
 }

 /**
  * 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 {

  request.setCharacterEncoding("utf-8");
  
  response.setCharacterEncoding("utf-8");
  
  String start = request.getParameter("start");
  
  String limit = request.getParameter("limit");
  
  UserBo uBo = new UserBo();
  
  String json = uBo.getJsonData(Integer.parseInt(start), Integer.parseInt(limit));
  
  response.getWriter().write(json);
  
  response.getWriter().flush();
 }

}

 

保存用户servlet:

package ext.servlet;

import java.io.IOException;

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

import ext.bo.UserBo;

public class Save extends HttpServlet {

 /**
  * 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 {

  doPost(request, response);
 }

 /**
  * 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 {

  request.setCharacterEncoding("UTF-8");
  response.setCharacterEncoding("UTF-8");

  String data = request.getParameter("data");

  UserBo uBo = new UserBo();

  uBo.saveOrUpdate(data);

  response.getWriter().print("保存或修改成功!");
 }

}

相关的数据库的创建:

创建数据表:

/*==============================================================*/
/* DBMS name:      MySQL 5.0                                    */
/* Created on:     2009-7-13 19:08:37                           */
/*==============================================================*/


drop table if exists class;

drop table if exists student;

/*==============================================================*/
/* Table: class                                                 */
/*==============================================================*/
create table class
(
   cls_id               int not null auto_increment,
   cls_name             varchar(20),
   cls_cdate            varchar(10),
   primary key (cls_id)
);

/*==============================================================*/
/* Table: student                                               */
/*==============================================================*/
create table student
(
   stu_id               int not null auto_increment,
   cls_id               int,
   stu_name             varchar(20),
   stu_sex              int,
   stu_age              int,
   stu_addr             text,
   stu_tel              varchar(20),
   primary key (stu_id)
);

alter table student add constraint FK_Relationship_1 foreign key (cls_id)
      references class (cls_id) on delete restrict on update restrict;

 

 

添加数据表:

insert into class values(null,'A班','2007-12-01');
insert into class values(null,'A班','2007-12-01');

insert into student values(null,1,'学生A',1,20,'福州','1111111');
insert into student values(null,2,'学生B',0,21,'福州','2222222');
insert into student values(null,1,'学生C',1,22,'福州','3333333');
insert into student values(null,2,'学生D',0,23,'福州','4444444');
insert into student values(null,1,'学生E',1,24,'福州','5555555');
insert into student values(null,2,'学生F',0,25,'福州','6666666');
insert into student values(null,1,'学生G',0,26,'福州','7777777');
insert into student values(null,2,'学生H',0,27,'福州','55055342555');
insert into student values(null,1,'学生I',0,18,'福州','55055333555');
insert into student values(null,1,'学生J',0,19,'福州','55055222555');
insert into student values(null,2,'学生K',0,19,'福州','55005551155');
insert into student values(null,2,'学生L',0,20,'福州','5055555555');
insert into student values(null,2,'学生M',1,21,'福州','5500055500055');
insert into student values(null,2,'学生N',1,23,'福州','55555523445');
insert into student values(null,2,'学生O',1,24,'福州','55530455555');
insert into student values(null,1,'学生P',1,25,'福州','55212055555');
insert into student values(null,1,'学生Q',1,24,'福州','5554450555');
insert into student values(null,1,'学生R',1,23,'福州','11111110');
insert into student values(null,2,'学生S',0,21,'福州','2222222');
insert into student values(null,1,'学生T',1,20,'福州','3333333');
insert into student values(null,1,'学生U',0,23,'福州','44444345404');
insert into student values(null,1,'学生V',1,24,'福州','5555555');
insert into student values(null,1,'学生W',1,19,'福州','5555565755');
insert into student values(null,1,'学生X',1,24,'福州','555553255');
insert into student values(null,2,'学生Y',1,22,'福州','555555634555');
insert into student values(null,2,'学生Z',1,22,'福州','5555522255');
insert into student values(null,2,'学生AA',1,18,'福州','55552342555');
insert into student values(null,1,'学生BB',1,17,'福州','5555523455');
insert into student values(null,1,'学生CC',0,24,'福州','5859404');
insert into student values(null,1,'学生DD',0,16,'福州','5553493');
insert into student values(null,1,'学生EE',0,16,'福州','5555555');
insert into student values(null,2,'学生FF',0,18,'福州','5553453');
insert into student values(null,2,'学生GG',1,17,'福州','5555533455');
insert into student values(null,1,'学生HH',1,18,'福州','5555234555');

 

 

运行的结果如下:::

Ext与后台数据库交互 - ㄛ緣べ戀ㄋ - 茶园天地

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多