easyui Datagrid+searchbox 实现搜索功能
1.前台页面
- <%@ 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>
2.strust.xml的配置
- <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();
- }
- }
- }
easyui Datagrid+searchbox 实现搜索功能的更多相关文章
- JS实现EasyUI ,Datagrid,合并单元格功能
为了实现datagrid的合并单元格效果,datagrid的数据加载方式肯定是要写在JS文件内部的. 一:在JS内部添加Datagrid数据加载方法如下: $("#id").dat ...
- easyui datagrid toolbar 添加搜索框
最近用到了就研究了下,效果 把列名稍加转换放入menubtton,对于单项搜索来说还是非常方便的 var fields = $('#tt').datagrid('getColumnFields') ...
- easyUI分页实现加搜索功能
前台页面: js代码: ps:pagination为true时会在table下面加上easyUI的分页. load函数会将查询值传给datagrid并传给后台重新加载. DAO.xml为: 后台代码实 ...
- 关于EasyUI datagrid editor combogrid搜索框的实现
首先需要datagrid editor对combogrid的扩展,这个是别人实现的: $.extend($.fn.datagrid.defaults.editors, { combogrid: { i ...
- Easyui DataGrid DateRange Filter 漂亮实用的日期区间段筛选功能
自定义扩展Jquery easyui datagrid filter组件实现对日期类型区间段的筛选功能.显示效果如一下 是不是非常实用 引用的jquery 组件是 Date Range Picker ...
- 第二百一十节,jQuery EasyUI,SearchBox(搜索框)组件
jQuery EasyUI,SearchBox(搜索框)组件 学习要点: 1.加载方式 2.属性列表 3.方法列表 本节课重点了解 EasyUI 中 SearchBox(搜索框)组件的使用方法,这个组 ...
- easyui datagrid client搜索、分页、排序
easyui datagrid的排序默认是server端排序.能够用sorter实现client排序[2].client分页可用filter实现[3].client搜索相同能够用filter实现. 不 ...
- 完美实现保存和加载easyui datagrid自定义调整列宽位置隐藏属性功能
需求&场景 例表查询是业务系统中使用最多也是最基础功能,但也是调整最平凡,不同的用户对数据的要求也不一样,所以在系统正式使用后,做为开发恨不得坐在业务边上,根据他们的要求进行调整,需要调整最多 ...
- EasyUI DataGrid 实现单行/多行编辑功能
要实现 EasyUI DataGrid 的可编辑很简单,在需要编辑的列添加 editor [编辑器]就可以了. 单行编辑 // 初始化数据列表 function initDatagrid() { $( ...
随机推荐
- Python学习笔记——与爬虫相关的网络知识
1 关于URL URL(Uniform / Universal Resource Locator):统一资源定位符,用于完整地描述Internet上网页和其他资源的地址的一种标识方法 URL是爬虫的入 ...
- AP_应付模组在月结的处理
2014-06-04 Created By BaoXinjian 1. 完成所有交易及检查Interface (1). Invoice and Credits (2). Prepa ...
- AP_建立银行信息总行、分行、账户(设定)
2014-06-04 Created By BaoXinjian
- mysql 再查询结果的基础上查询(子查询)
SELECT A.wx_name, A.wx_litpic, B . * FROM ( SELECT uid, COUNT( * ) AS daticishu FROM statements , ) ...
- MySQL索引经验
在数据库表中,使用索引可以大大提高查询速度. 假如我们创建了一个testIndex表:create TABLE testIndex(i_testID INT NOT NULL,vc_Name VARC ...
- 【转】sql server存储过程中SELECT 与 SET 对变量赋值的区别
转自:http://www.cnblogs.com/micheng11/archive/2008/07/08/1237905.html SQL Server 中对已经定义的变量赋值的方式用两种,分别是 ...
- 《ZedBoard各种资料网址备份记录》
转载来自于:http://http//www.eefocus.com/crazybingo/blog/2013-02/289101_ab4c8.html 1. Xilinx FPGA相关连接 1) X ...
- MSSQLid清零
truncate table [cellphone2016].[dbo].[tp_phone_9]
- cocos2d-x 父节点和子节点执行不同动作
Test6::Test6() { CCSprite* sp1 = CCSprite::create(s_pPathSister1); CCSprite* sp11 = CCSprite::create ...
- 五、String在Java中是传“引用”
这个是Java的经典问题.许多类似的问题在stackoverflow被提问,有很多不正确或不完备的答案.如果不想太多你会认为这个问题比较简单.( The question is simple if y ...