MiniUi使用Struts2的增删查改
使用Struts2框架实现MIniUI框架
MIniUi框架地址:http://www.miniui.com
1.增删改功能:
增删查功能都是通过JSP ajax传值
function saveData() { var data = grid.getChanges(); var json = mini.encode(data); grid.loading("保存中,请稍后......"); $.ajax({ url: "${pageContext.request.contextPath}/test/myCurd_save",
//Action路径 需要跳转到的后台 data: { data: json }, type: "post", success: function (text) { grid.reload(); }, error: function (jqXHR, textStatus, errorThrown) { alert(jqXHR.responseText); } }); }
后台Actionpublic class CRUDAction {
private String data; //使用成员变量提供SET GET方法 获取到前台的参数 public String save() throws Exception{ System.out.println("data:"+data); ArrayList rows = (ArrayList)JSON.Decode(data);
//通过MiniUiDemo中的自带的JSON类把前台传入的参数转换成数组
for(int i=0;i<rows.size();i++){
HashMap<String,Object> map = (HashMap)rows.get(i);
//获取到list 用Map数组切割
String state = (String)map.get("_state");
//state是获取到操作的类型 System.out.println("用户操作:"+state);
if(state.equals("added")){
//添加 new TestDB().InsertEmployee(map); }else if(state.equals("removed")){
//删除 int userid = Integer.parseInt(map.get("user_id").toString());
//获取到ID确定删除哪个用户
System.out.println("用户ID:"+userid); new TestDB().DeleteEmployee(userid);
}else if(state.equals("modified")){
//修改 new TestDB().UpdateDepartment(map); } } return "ok"; } public String getData() { return data; } public void setData(String data) { this.data = data; } }
TestDB 操作数据库
public class TestDB { //mysql 配置链接数据库的4大属性 public static String driver = "com.mysql.jdbc.Driver"; public static String url = "jdbc:mysql://127.0.0.1/crud?useUnicode=true&characterEncoding=GBK"; public static String user = "root"; public static String pwd = "123456";
//添加用户
public String InsertEmployee(HashMap user) throws Exception
{
String id = (user.get("id") == null || user.get("id").toString().equals(""))? UUID.randomUUID().toString() : user.get("id").toString();
user.put("id", id);
if (user.get("name") == null) user.put("name", "");
if (StringUtil.isNullOrEmpty(user.get("gender"))) user.put("gender", 0);
Connection conn = getConn();
String sql = "insert into user(user_name, pass_word, gender)"
+ " values(?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, ToString(user.get("user_name")));
stmt.setString(2, ToString(user.get("pass_word")));
stmt.setString(3, ToString(user.get("gender")));
stmt.executeUpdate();
stmt.close();
conn.close();
return id;
}
//删除用户
public void DeleteEmployee(int userId) throws Exception
{
Connection conn = getConn();
Statement stmt = conn.createStatement();
String sql = "delete from user where user_id = \""+userId+"\"";
stmt.executeUpdate(sql);
stmt.close();
conn.close();
}
//修改用户
public void UpdateDepartment(HashMap d) throws Exception
{
HashMap db_d = GetDepartment(d.get("user_id").toString());
Iterator iter = d.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
Object key = entry.getKey();
Object val = entry.getValue();
db_d.put(key, val);
}
String sql =
"update user "
+ " set "
+ " user_name = ?, "
+ " pass_word = ?, "
+ " gender = ? "
+" where user_id = ?";
Connection conn = getConn();
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, ToString(db_d.get("user_name")));
stmt.setString(2, ToString(db_d.get("pass_word")));
stmt.setString(3, ToString(db_d.get("gender")));
stmt.setString(4, ToString(db_d.get("user_id")));
stmt.executeUpdate();
stmt.close();
conn.close();
}
2.查功能
JSP页面查功能
function search() { var key = mini.get("key").getValue(); //通过输入框的KEY获取到要查询的值 grid.load({ key: key }); }
查询Action类
public class fenyeAction { private int pageIndex; //查询起始位置
private int pageSize; //一次查询几条
private String sortField; //排序字段 private String SortOrder; //排序顺序 private String key;//用户输入的值 public String fenye() throws Exception{ HashMap result = new TestDB().SearchEmployees(key,pageIndex,pageSize, sortField, SortOrder);
//从数据库查询到数据存入Map数组 PrintWriter out = ServletActionContext.getResponse().getWriter(); String json = JSON.Encode(result); out.print(json); out.flush(); out.close(); return "fenye"; } public int getPageIndex() { return pageIndex; } public void setPageIndex(int pageIndex) { this.pageIndex = pageIndex; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public String getSortField() { return sortField; } public void setSortField(String sortField) { this.sortField = sortField; } public String getSortOrder() { return SortOrder; } public void setSortOrder(String sortOrder) { SortOrder = sortOrder; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } }
查询方法
public HashMap SearchEmployees(String key, int index, int size, String sortField, String sortOrder) throws Exception { //System.Threading.Thread.Sleep(300); if(key == null) key = ""; String sql = "select *from user where user_name like '%" + key + "%' \n"; if (StringUtil.isNullOrEmpty(sortField) == false) { if ("desc".equals(sortOrder) == false) sortOrder = "asc"; sql += " order by " + sortField + " " + sortOrder; } else { sql += " order by user_id desc"; } ArrayList dataAll = DBSelect(sql); ArrayList data = new ArrayList(); int start = index * size, end = start + size; for (int i = 0, l = dataAll.size(); i < l; i++) { HashMap record = (HashMap)dataAll.get(i); if (record == null) continue; if (start <= i && i < end) { data.add(record); } //record.put("createtime", new Timestamp(100,10,10,1,1,1,1)); } HashMap result = new HashMap(); result.put("data", data); result.put("total", dataAll.size()); //minAge, maxAge, avgAge ArrayList ages = DBSelect("select min(user_id) as minAge, max(user_id) as maxAge, avg(user_id) as avgAge from user"); HashMap ageInfo = (HashMap)ages.get(0); result.put("minAge", ageInfo.get("minAge")); result.put("maxAge", ageInfo.get("maxAge")); result.put("avgAge", ageInfo.get("avgAge")); return result; }