easyui Datagrid+searchbox 實現搜尋功能
阿新 • • 發佈:2019-02-03
說明:採用了ssh架構
這是搜尋前的介面:
這是根據使用者名稱搜尋後出現的搜尋結果:
1.前臺頁面:
2.strust.xml的配置<%@ page language="java" pageEncoding="utf-8" isELIgnored="false"%> <% String path = request.getContextPath(); %> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Basic DataGrid - jQuery EasyUI Demo</title> <script type="text/javascript" src="easyui/jquery.min.js"></script> <script type="text/javascript" src="easyui/jquery.easyui.min.js"></script> <script type="text/javascript" src="easyui/locale/easyui-lang-zh_CN.js"></script> <link rel="stylesheet" href="easyui/themes/default/easyui.css" type="text/css" charset="utf-8"></link> <link rel="stylesheet" href="easyui/themes/icon.css" type="text/css" charset="utf-8"></link> </head> <script type="text/javascript"> function doSearch(value,name){ //使用者輸入使用者名稱,點選搜素,觸發此函式 $("#tt").datagrid({ title:'searchBox', iconCls:'icon-ok', width:600, pageSize:10, pageList:[5,10,15,20], nowrap:true, striped:true, collapsible:true, toolbar:"#easyui_toolbar", url:'searchByUsernameAction.action?searchValue='+value, //觸發此action,帶上引數searcValue loadMsg:'資料載入中......', fitColumns:true,//允許表格自動縮放,以適應父容器 sortName:'userId', sortOrder:'asc', remoteSort:false, columns : [ [ { field : 'userId', width : 150, title : '使用者id' }, { field : 'name', width : 150, title : '使用者名稱' }, { field : 'password', width : 230, align : 'right', title : '密碼' } ] ], pagination : true, rownumbers : true }) } </script> <body> <div class="easyui-panel" title="DataGrid with searching box" icon="icon-save" style="width: 600px; height: 420px;" collapsible="true" minimizable="true" maximizable=true closable="true"> <div class="easyui-layout" fit="true" > <div id="easyui_toolbar" region="north" border="false" style="border-bottom: 1px solid #ddd; height: 32px; padding: 2px 5px; background: #fafafa;"> <div style="float: left;"> <a href="#" class="easyui-linkbutton" plain="true" icon="icon-add">新增</a> </div> <div class="datagrid-btn-separator"></div> <div style="float: left;"> <a href="#" class="easyui-linkbutton" plain="true" icon="icon-save">編輯</a> </div> <div class="datagrid-btn-separator"></div> <div style="float: left;"> <a href="#" class="easyui-linkbutton" plain="true" icon="icon-remove">刪除</a> </div> <div id="tb" style="float: right;"> <input id="ss" class="easyui-searchbox" searcher="doSearch" prompt="請輸入使用者名稱" style="width: 130px; vertical-align: middle;"></input> </div> </div> <div region="center" border="false"> <table id="tt"></table> </div> </div> </div> <script> $('#tt').datagrid({ title:'searchBox', iconCls:'icon-ok', width:600, pageSize:10, pageList:[5,10,15,20], nowrap:true, striped:true, collapsible:true, toolbar:"#easyui_toolbar", //url : './datagrid/userData.json', url:'getAllUserAction.action', //搜尋前,觸發此action請求所有使用者資訊 loadMsg:'資料載入中......', fitColumns:true,//允許表格自動縮放,以適應父容器 sortName:'userId', sortOrder:'asc', remoteSort:false, columns : [ [ { field : 'userId', width : 150, title : '使用者id' }, { field : 'name', width : 150, title : '使用者名稱' }, { field : 'password', width : 230, align : 'right', title : '密碼' } ] ], pagination : true, rownumbers : true }); </script> </body> </html>
<package name="easyui" extends="struts-default"> <action name="getAllUserAction" class="com.ssh.action.UserAction" method="getAllUser"> </action> <action name="userVerifyAction" class="com.ssh.action.UserAction" method="verify"> </action> <action name="delUserAction" class="com.ssh.action.UserAction" method="delUser"> </action> <action name="userAddAction" class="com.ssh.action.UserAction" method="add"> </action> <action name="searchByUsernameAction" class="com.ssh.action.UserAction" method="searchByUsername"> </action> </package>
3.action類
<span style="font-size:12px;">package com.ssh.action; import java.io.PrintWriter; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.ssh.bean.TUser; import com.ssh.service.UserService; import com.ssh.serviceImp.ViewLogServiceImp; import net.sf.json.JSONObject; import org.apache.struts2.ServletActionContext; @SuppressWarnings("serial") public class UserAction extends ActionSupport{ // static Logger log = Logger.getLogger(TUser.class); private JSONObject jsonObj; private String rows;// private String page; private TUser tuser; private String tableName; private String fieldName; private String parameter; private UserService userService; private String num;// 刪除時迴圈的次數; private String ids;//要刪除的使用者id號 private String searchValue; // private ViewLogServiceImp viewLogService; // 測試用的變數 String userId; String name; String password; // public void getAllUser() throws Exception { // log.info("查詢所有學生資訊!"); System.out.println("getAllUser方法" + "page=" + page + " rows=" + rows); List list = userService.getUserList(page, rows); for (int i = 0; i < list.size(); i++) { System.out.println(((TUser) list.get(i)).getName() + "*"); } int size = userService.getUserTotal(); System.out.println("UserAction:Total=" + size + ",page=" + list.size()); try { toBeJson(list, size); } catch (Exception e) { e.printStackTrace(); } } /* * public void add() throws Exception { tuser=new TUser(); * tuser.setUserId(15); tuser.setName("aaaaa"); tuser.setPassword("xxxx"); */ public void add(String userId, String name, String password) throws Exception { System.out .println("add方法: " + userId + " " + name + " " + password); userService.saveUser(userId, name, password); } public void add() throws Exception { System.out.println("不帶引數的add方法: " + tuser.getUserId() + " " + tuser.getName() + " " + tuser.getPassword()); userService.saveUser((tuser.getUserId()).toString(), tuser.getName(), tuser.getPassword()); TUser tu=getTUser(); userService.saveRecord(tu, "add user"); } // 新增時,驗證是否已經存在資料庫 public void verify() throws Exception { System.out.println("UserAction:verfiy: " + tableName + " " + fieldName + " " + parameter); String s = userService.queryByUnique(tableName, fieldName, parameter); // 將驗證結果返回到頁面,1代表已經存在資料庫中,0代表沒有 System.out.println("s=" + s); HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html;Charset=utf-8"); PrintWriter out = response.getWriter(); out.print(s); out.flush(); out.close(); } // 刪除 public void delUser(String ids) throws Exception { System.out.println("delUser方法: " + ids); userService.delUser(ids); TUser tu=getTUser(); userService.saveRecord(tu, "delete user"); } public void delUser()throws Exception{ System.out.println("不帶引數delUser方法: "+ids); userService.delUser(ids); } public void searchByUsername()throws Exception{ List list=userService.searchByUsername(page,rows,searchValue); int size=userService.getSearchByUsernameTotal(searchValue); toBeJson(list,size); } // 轉化WieJson格式 @SuppressWarnings({ "rawtypes", "unchecked" }) public void toBeJson(List list, int total) throws Exception { try { HttpServletResponse response = ServletActionContext.getResponse(); // ??????????????? // JSONObject jobj = new JSONObject(); // System.out.println("UserAction.toBeJson()4"); // jobj.accumulate("total", total);// total代表一共有多少資料 // System.out.println("UserAction.toBeJson()1"); // jobj.accumulate("rows", list);// rows是代表顯示的頁的資料 // System.out.println("UserAction.toBeJson()3"); // response.setCharacterEncoding("utf-8");// 指定為utf-8 // System.out.println("UserAction.toBeJson()2" + jobj.toString()); String sb = "{"; sb += "\"total\":" + total; sb += ",\"rows\":["; for (TUser po : (List<TUser>) list) { sb += "{"; sb += "\"name\":\"" + po.getName(); sb += "\",\"password\":\"" + po.getPassword(); sb += "\",\"userId\":" + po.getUserId(); sb += "},"; } if (sb.endsWith(",")) sb = sb.substring(0, sb.length() - 1); sb += "]}"; // System.out.println("UserAction.toBeJson()" + sb); response.getWriter().write(sb);// 轉化為JSON格式 // log.info(sb); } catch (Exception e) { e.printStackTrace(); } } //根據session來獲取當前使用者的資訊 @SuppressWarnings("rawtypes") public TUser getTUser() { ActionContext ctx=ActionContext.getContext(); Map session=ctx.getSession(); TUser tu=(TUser)session.get("LOGINED_USER"); System.out.println("UserAction中:getTUser方法:"+tu.getUserId()+" "+tu.getName()); return tu; } public JSONObject getJsonObj() { return jsonObj; } public void setJsonObj(JSONObject jsonObj) { this.jsonObj = jsonObj; } public String getRows() { return rows; } public void setRows(String rows) { this.rows = rows; } public String getPage() { return page; } public void setPage(String page) { this.page = page; } public TUser getTuser() { return tuser; } public void setTuser(TUser tuser) { this.tuser = tuser; } public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } public String getFieldName() { return fieldName; } public void setFieldName(String fieldName) { this.fieldName = fieldName; } public String getParameter() { return parameter; } public void setParameter(String parameter) { this.parameter = parameter; } public UserService getUserService() { return userService; } public void setUserService(UserService userService) { this.userService = userService; } public String getNum() { return num; } public void setNum(String num) { this.num = num; } public String getIds() { return ids; } public void setIds(String ids) { this.ids = ids; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public ViewLogServiceImp getViewLogService() { return viewLogService; } public void setViewLogService(ViewLogServiceImp viewLogService) { this.viewLogService = viewLogService; } public String getSearchValue() { return searchValue; } public void setSearchValue(String searchValue) { this.searchValue = searchValue; } }</span>
2.實現層,查詢資料庫
package com.ssh.serviceImp;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpSession;
//import org.hibernate.criterion.DetachedCriteria;
import org.apache.struts2.ServletActionContext;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.ssh.bean.TAdminLog;
import com.ssh.bean.TUser;
import com.ssh.service.UserService;
public class UserServiceImp implements UserService {
HibernateTemplate ht;
public HibernateTemplate getHt() {
return ht;
}
public void setHt(HibernateTemplate ht) {
this.ht = ht;
}
@SuppressWarnings("unchecked")
@Override
public List<TUser> getTUser(String username, String password) {
// TODO Auto-generated method stub
StringBuffer sql = new StringBuffer("from TUser where name='");
sql.append(username + "' and password='" + password + "'");
return ht.find(sql.toString());
}
//
@SuppressWarnings("rawtypes")
public List getUserList(String page, String rows) {
int currentPage = Integer
.parseInt((page == null) || (page == "0") ? "1" : page);
int pageSize = Integer.parseInt((rows == null) || rows == "0" ? "1"
: rows);
System.out.println("currentPage=" + currentPage + " pageSize="
+ pageSize);
/*
* DetachedCriteria criteria=DetachedCriteria.forClass(TUser.class);
* List list=ht.findByCriteria(criteria, currentPage*pageSize,
* pageSize);
*/
StringBuffer sql = new StringBuffer("from TUser where userId>=");
sql.append((currentPage - 1) * pageSize + 1);
sql.append(" and userId <=");
sql.append(currentPage * pageSize);
List list = ht.find(sql.toString());
return list;
}
@SuppressWarnings("rawtypes")
public int getUserTotal() throws Exception {
List list = ht.find("from TUser");
return list.size();
}
// 新增使用者資訊
public void saveUser(String userId, String name, String password)
throws Exception {
System.out.println("UserServiceImp:" + name);
TUser tuser = new TUser();
tuser.setUserId(Integer.parseInt(userId));
tuser.setName(name);
tuser.setPassword(password);
ht.save(tuser);
HttpSession session = ServletActionContext.getRequest().getSession();
TUser tu = new TUser();
String uid = (String) session.getAttribute("userId");
String na = (String) session.getAttribute("username");
String ps = (String) session.getAttribute("password");
tu.setUserId(Integer.parseInt(uid));
tu.setName(na);
tu.setPassword(ps);
saveRecord(tu, "save user");
}
// 刪除使用者
@SuppressWarnings("rawtypes")
public void delUser(String ids) throws Exception {
int id = Integer.parseInt(ids);
StringBuffer sql = new StringBuffer(
"delete TUer user where user.userId = ");
sql.append(id);
System.out.println(sql);
// ht.delete(sql);
// TUser tuser = (TUser) (ht.find("from TUser where userId = " + ids));
TUser tuser = new TUser();
List list = ht.find("from TUser where userId = " + ids);
if (list.size() > 0) {
tuser = (TUser) list.get(0);
}
System.out.println("***" + tuser.getName());
ht.delete(tuser);
HttpSession session = ServletActionContext.getRequest().getSession();
TUser tu = new TUser();
String uid = (String) session.getAttribute("userId");
String na = (String) session.getAttribute("username");
String ps = (String) session.getAttribute("password");
tu.setUserId(Integer.parseInt(uid));
tu.setName(na);
tu.setPassword(ps);
System.out.println("delUser:userId:");
System.out.println(uid);
saveRecord(tu, "delUser user");
}
// 判斷是否具有唯一性
@SuppressWarnings("rawtypes")
public String queryByUnique(String tableName, String fieldName,
String parameter) throws Exception {
System.out.println("tableName:" + tableName + " fieldName:" + fieldName
+ " parameter:" + parameter);
StringBuffer sql = new StringBuffer("from " + tableName + " where "
+ fieldName + " = " + parameter);
System.out.println(sql.toString());
List list = null;
try {
list = ht.find(sql.toString());
if (list != null) {
System.out.println("***1" + list.toString());
// System.out.println(((TUser) list.get(0)).getName());
} else {
System.out.println("***2");
}
} catch (Exception e) {
e.printStackTrace();
}
/*
* if (list != null) { //System.out.println(((TUser)
* list.get(0)).getName());
*
* } else { System.out.println("***"); }
*/
if (list == null || list.size() != 0) {
return "1";
} else {
return "0";// 代表資料庫裡沒有這條資料;
}
}
@Override
public void saveRecord(TUser tuser, String record) throws Exception {
// TODO Auto-generated method stub
TAdminLog tAdminLog = new TAdminLog(tuser, record);
ht.save(tAdminLog);
}
@Override
public List searchByUsername(String page, String rows, String searchValue)
throws Exception {
// TODO Auto-generated method stub
System.out.println("page="+page);
System.out.println("rows="+rows);
System.out.println("searchValue="+searchValue);
StringBuffer sql = new StringBuffer("from TUser t where t.name ='");
sql.append(searchValue);
sql.append("'");//注意要加單引號
System.out.println("searchByUsername:"+sql);
List list = ht.find(sql.toString());
int currentPage = Integer
.parseInt((page == null) || (page == "0") ? "1" : page);
int currentRows = Integer
.parseInt((rows == null) || (rows == "0") ? "1" : rows);
int number = (currentPage - 1) * currentRows;
List li = new ArrayList();
for (int i = number; i < (number + currentRows)
&& i < (list.size()); i++) {
li.add(list.get(i));
}
return li;
}
@Override
public int getSearchByUsernameTotal(String searchValue) throws Exception {
// TODO Auto-generated method stub
StringBuffer sql = new StringBuffer("from TUser t where t.name ='");
sql.append(searchValue);
sql.append("'");
List list = ht.find(sql.toString());
if (list.size() == 0) {
return 0;
} else {
return list.size();
}
}
}
資料庫截圖:
注:全部的原始碼,我壓縮後傳到csdn資源上myf工程,感興趣的朋友可以看一下,剛入門,原始碼寫的比較菜,歡迎大家提出意見和建議,有問題發我扣扣訊息,2513822561