`
liyanhui
  • 浏览: 349663 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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.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">
  <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与后台数据库交互 - ㄛ緣べ戀ㄋ - 茶园天地

分享到:
评论

相关推荐

    EXT与数据库交互的事例

    EXT与数据库交互,主要是通过AJAX(Asynchronous JavaScript and XML)技术来实现的,尽管在实际应用中XML可能不再是最常用的交换数据格式,现在更多的是JSON。 EXT中的AJAX交互通常涉及到以下几个关键知识点: 1....

    ext前后台交互实例

    在"ext前后台交互实例"中,JSON扮演着至关重要的角色,作为数据载体,在前端展示层与后端逻辑层之间架起了一座桥梁。 ### JSP页面与JSON的交互 JSP(JavaServer Pages)是一种用于生成动态网页的技术,它允许将...

    extjs和数据库的后台交互

    在ExtJS中,与后台数据库进行交互通常涉及到Ajax技术、JSON格式数据以及服务器端的数据处理。 1. **Ajax技术**:Ajax(Asynchronous JavaScript and XML)允许在不刷新整个页面的情况下与服务器进行数据交换。在...

    Ext4tree与后台交互

    在"Ext4 tree与后台交互"这个主题中,我们将深入探讨如何使用Ext4的TreePanel与后端进行数据交换,以及如何处理json数据。 首先,`TreeNode.java`可能是Java后端用于表示树节点的数据类。在Java中,树节点通常包含...

    ext后台管理

    在"EXT后台管理"系统中,EXT主要负责前端的展示和交互,通过AJAX技术与后端PHP进行通信,实现数据的动态加载和更新。PHP作为服务器端语言,处理HTTP请求,执行业务逻辑,如数据的增删改查、验证、权限控制等。PHP还...

    Ext2.0 与后台数据的交互

    在EXT2.0框架下,前端与后台数据的交互是应用程序中的关键环节,尤其是在登录模块。EXT2.0是一款强大的JavaScript库,它提供了一整套的组件和工具,用于构建富客户端应用程序。在这个例子中,我们将深入探讨EXT2.0...

    简单ext jsp数据库操作例子

    总结来说,"简单ext jsp数据库操作例子"是一个涵盖了EXT JSP与数据库交互基本原理和实践的应用案例,通过学习这个项目,开发者可以掌握EXT JSP在实际Web应用中的使用,以及如何有效地处理数据库操作,为构建更复杂的...

    Ext简单后台交互(struts2+ibatis2+mysql5.5)

    标题中的“Ext简单后台交互(struts2+ibatis2+mysql5.5)”指的是一个基于Web开发的示例项目,它使用了以下技术栈: 1. **Struts2**:Struts2是一个用于Java Web应用的开源MVC框架,它提供了模型-视图-控制器(MVC...

    Ext+struts学生管理系统

    "Ext与后台交互"和"Ext与数据库交互"再次强调了前端与后端之间的通信机制以及数据存储和检索的核心功能。 【压缩包子文件的文件名称列表】中的"Gird"很可能是指ExtJS中的Grid组件,这是一个表格展示控件,常用于...

    Ext 操作数据库,对数据的增删改查,包括数据库,Ajax请求和store请求的设置

    通过实际操作,你可以理解前端与后台的交互机制,以及Ext是如何封装和简化这些过程的。 在登录功能方面,Ext提供了丰富的组件和布局,如FormPanel、TextField、Button等,可以轻松实现用户界面。主页面的显示则可能...

    ext后台模板

    6. **API接口集成**:EXT后台模板通常需要与后端服务器进行交互,实现数据的获取和提交。EXTJS 提供了AJAX和Store组件来处理与服务器的JSON或XML数据交换,这需要开发者理解RESTful API的设计和使用。 7. **主题和...

    ext后台经典实例

    "EXT后台经典实例"指的是使用EXT与后端服务器进行交互的典型应用场景,通常涉及到Ajax通信、数据模型、Store和Grid等核心概念。 在EXT中,数据通常是通过Store来管理的。Store连接到后端服务器,负责加载、保存和...

    Ext.net后台分页增删改

    在"Ext.NET后台分页增删改"这个主题中,我们将探讨如何利用Ext.NET实现数据库后台分页、树形视图操作以及Grid面板的CRUD(创建、读取、更新和删除)功能。 首先,让我们深入了解一下后台分页。在Ext.NET中,为了...

    自己写的一个动态从后台数据库加载Ext.tree的json数据工具类

    在IT行业中,动态地从后台数据库加载数据到前端界面是一种常见的需求,特别是在构建富客户端应用时。本话题涉及的是一个自定义的工具类,用于处理ExtJS库中的Ext.tree组件,该组件通常用来展示层级结构的数据,比如...

    ASP.NET与EXT实现动感后台管理界面

    在"ASP.NET与EXT实现动感后台管理界面"的主题中,我们可以学习到如何结合这两者的优势,构建一个高效的管理界面。首先,开发者需要在ASP.NET中设计后端服务,如API接口,用于处理数据请求和业务逻辑。这些接口可以...

    一步一步使用Ext JS MVC与Asp.Net MVC 3开发简单的CMS后台管理系统之数据库文件

    在本教程中,我们将深入探讨如何使用Ext JS MVC框架与Asp.Net MVC 3来构建一个简单的CMS(内容管理系统)的后台。这个系统的基石是数据库,由两个文件组成:SimpleCMS_log.ldf和SimpleCMS.mdf。这两个文件是SQL ...

    Ext后台图书管理系统(源码)

    Hibernate是一个对象关系映射(ORM)框架,它简化了数据库操作,使开发者能用Java对象进行数据库交互。Struts是MVC(Model-View-Controller)架构的一个实现,用于组织和控制应用程序的业务逻辑和视图。此外,描述中...

    ext 实现的webQQ 源码、应用、含数据库

    2. **数据绑定**:EXT支持双向数据绑定,这意味着UI元素可以直接与后台数据模型关联,当数据改变时,界面会自动更新,反之亦然,这简化了前端与后端的数据同步。 3. **Ajax通信**:EXT提供了异步通信的接口,WebQQ...

    一个以strut2+ext为结构的后台模板

    4. **EXT UI组件**: 在前端,使用EXT创建各种交互式的用户界面,如数据网格、表单、菜单等,与后台进行数据交互。 5. **Model**: 用于定义数据模型,可以是Java对象,与数据库中的表对应,用于封装和传递数据。 6. *...

Global site tag (gtag.js) - Google Analytics