easyui Datagrid+searchbox 实现搜索功能

1.前台页面

  1. <%@ page language="java" pageEncoding="utf-8" isELIgnored="false"%>  
  2. <%  
  3.     String path = request.getContextPath();  
  4. %>  
  5. <%@ taglib prefix="s" uri="/struts-tags"%>  
  6.   
  7. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  8. <html>  
  9. <head>  
  10. <title>Basic DataGrid - jQuery EasyUI Demo</title>  
  11. <script type="text/javascript" src="easyui/jquery.min.js"></script>  
  12. <script type="text/javascript" src="easyui/jquery.easyui.min.js"></script>  
  13. <script type="text/javascript" src="easyui/locale/easyui-lang-zh_CN.js"></script>  
  14. <link rel="stylesheet" href="easyui/themes/default/easyui.css"  
  15.     type="text/css" charset="utf-8"></link>  
  16. <link rel="stylesheet" href="easyui/themes/icon.css" type="text/css"  
  17.     charset="utf-8"></link>  
  18. </head>  
  19. <script type="text/javascript">  
  20.     function doSearch(value,name){ //用户输入用户名,点击搜素,触发此函数  
  21.         $("#tt").datagrid({  
  22.             title:'searchBox',  
  23.             iconCls:'icon-ok',  
  24.             600,  
  25.             pageSize:10,  
  26.             pageList:[5,10,15,20],  
  27.             nowrap:true,  
  28.             striped:true,  
  29.             collapsible:true,  
  30.             toolbar:"#easyui_toolbar",  
  31.             url:'searchByUsernameAction.action?searchValue='+value, //触发此action,带上参数searcValue  
  32.             loadMsg:'数据加载中......',  
  33.             fitColumns:true,//允许表格自动缩放,以适应父容器  
  34.             sortName:'userId',  
  35.             sortOrder:'asc',  
  36.             remoteSort:false,  
  37.             columns : [ [ {  
  38.                 field : 'userId',  
  39.                 width : 150,  
  40.                 title : '用户id'  
  41.             }, {  
  42.                 field : 'name',  
  43.                 width : 150,  
  44.                 title : '用户名'  
  45.             }, {  
  46.                 field : 'password',  
  47.                 width : 230,  
  48.                 align : 'right',  
  49.                 title : '密码'  
  50.             } ] ],  
  51.             pagination : true,  
  52.             rownumbers : true  
  53.         })  
  54.     }  
  55.       
  56. </script>  
  57. <body>  
  58.     <div class="easyui-panel" title="DataGrid with searching box"  
  59.         icon="icon-save" style=" 600px; height: 420px;"  
  60.         collapsible="true" minimizable="true" maximizable=true closable="true">  
  61.   
  62.         <div class="easyui-layout" fit="true"  >  
  63.             <div  id="easyui_toolbar" region="north" border="false"  
  64.                 style="border-bottom: 1px solid #ddd; height: 32px; padding: 2px 5px; background: #fafafa;">  
  65.                 <div style="float: left;">  
  66.                     <href="#" class="easyui-linkbutton" plain="true" icon="icon-add">新增</a>  
  67.                 </div>  
  68.   
  69.                 <div class="datagrid-btn-separator"></div>  
  70.   
  71.                 <div style="float: left;">  
  72.                     <href="#" class="easyui-linkbutton" plain="true" icon="icon-save">编辑</a>  
  73.                 </div>  
  74.   
  75.                 <div class="datagrid-btn-separator"></div>  
  76.   
  77.                 <div style="float: left;">  
  78.                     <href="#" class="easyui-linkbutton" plain="true"  
  79.                         icon="icon-remove">删除</a>  
  80.                 </div>  
  81.   
  82.                 <div id="tb" style="float: right;">  
  83.                     <input id="ss" class="easyui-searchbox"  
  84.                         searcher="doSearch" prompt="请输入用户名"  
  85.                         style=" 130px; vertical-align: middle;"></input>   
  86.                 </div>  
  87.   
  88.             </div>  
  89.             <div region="center" border="false">  
  90.                 <table id="tt"></table>  
  91.             </div>  
  92.   
  93.         </div>  
  94.     </div>  
  95.     <script>  
  96.         $('#tt').datagrid({  
  97.             title:'searchBox',  
  98.             iconCls:'icon-ok',  
  99.             600,  
  100.             pageSize:10,  
  101.             pageList:[5,10,15,20],  
  102.             nowrap:true,  
  103.             striped:true,  
  104.             collapsible:true,  
  105.             toolbar:"#easyui_toolbar",  
  106.             //url : './datagrid/userData.json',  
  107.             url:'getAllUserAction.action', //搜索前,触发此action请求所有用户信息  
  108.             loadMsg:'数据加载中......',  
  109.             fitColumns:true,//允许表格自动缩放,以适应父容器  
  110.             sortName:'userId',  
  111.             sortOrder:'asc',  
  112.             remoteSort:false,  
  113.             columns : [ [ {  
  114.                 field : 'userId',  
  115.                 width : 150,  
  116.                 title : '用户id'  
  117.             }, {  
  118.                 field : 'name',  
  119.                 width : 150,  
  120.                 title : '用户名'  
  121.             }, {  
  122.                 field : 'password',  
  123.                 width : 230,  
  124.                 align : 'right',  
  125.                 title : '密码'  
  126.             } ] ],  
  127.             pagination : true,  
  128.             rownumbers : true  
  129.         });  
  130.     </script>  
  131.   
  132. </body>  
  133. </html>  

2.strust.xml的配置

[html] view plain copy
 
  1. <package name="easyui" extends="struts-default">  
  2.     <action name="getAllUserAction" class="com.ssh.action.UserAction"  
  3.         method="getAllUser">  
  4.     </action>  
  5.     <action name="userVerifyAction" class="com.ssh.action.UserAction"  
  6.         method="verify">  
  7.     </action>  
  8.     <action name="delUserAction" class="com.ssh.action.UserAction"  
  9.         method="delUser">  
  10.     </action>  
  11.     <action name="userAddAction" class="com.ssh.action.UserAction"  
  12.         method="add">  
  13.     </action>  
  14.     <action name="searchByUsernameAction" class="com.ssh.action.UserAction"  
  15.             method="searchByUsername">  
  16.     </action>  
  17. </package>  

3.action类

[java] view plain copy
 
  1. <span style="font-size:12px;">package com.ssh.action;  
  2.   
  3. import java.io.PrintWriter;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6. import javax.servlet.http.HttpServletResponse;  
  7. import com.opensymphony.xwork2.ActionContext;  
  8. import com.opensymphony.xwork2.ActionSupport;  
  9. import com.ssh.bean.TUser;  
  10. import com.ssh.service.UserService;  
  11. import com.ssh.serviceImp.ViewLogServiceImp;  
  12. import net.sf.json.JSONObject;  
  13. import org.apache.struts2.ServletActionContext;  
  14.   
  15. @SuppressWarnings("serial")  
  16. public class UserAction extends ActionSupport{  
  17.     // static Logger log = Logger.getLogger(TUser.class);  
  18.   
  19.     private JSONObject jsonObj;  
  20.     private String rows;//  
  21.     private String page;  
  22.       
  23.     private TUser tuser;  
  24.     private String tableName;  
  25.     private String fieldName;  
  26.     private String parameter;  
  27.     private UserService userService;  
  28.     private String num;// 删除时循环的次数;  
  29.     private String ids;//要删除的用户id号  
  30.     private String searchValue;  
  31.   
  32.     //  
  33.     private ViewLogServiceImp viewLogService;  
  34.       
  35.     // 测试用的变量  
  36.     String userId;  
  37.     String name;  
  38.     String password;  
  39.       
  40.   
  41.     //  
  42.   
  43.     public void getAllUser() throws Exception {  
  44.         // log.info("查询所有学生信息!");  
  45.         System.out.println("getAllUser方法" + "page=" + page + "  rows=" + rows);  
  46.   
  47.         List list = userService.getUserList(page, rows);  
  48.         for (int i = 0; i < list.size(); i++) {  
  49.             System.out.println(((TUser) list.get(i)).getName() + "*");  
  50.         }  
  51.         int size = userService.getUserTotal();  
  52.         System.out.println("UserAction:Total=" + size + ",page=" + list.size());  
  53.         try {  
  54.             toBeJson(list, size);  
  55.         } catch (Exception e) {  
  56.             e.printStackTrace();  
  57.         }  
  58.     }  
  59.   
  60.     /* 
  61.      * public void add() throws Exception { tuser=new TUser(); 
  62.      * tuser.setUserId(15); tuser.setName("aaaaa"); tuser.setPassword("xxxx"); 
  63.      */  
  64.     public void add(String userId, String name, String password)  
  65.             throws Exception {  
  66.         System.out  
  67.                 .println("add方法:   " + userId + "  " + name + "  " + password);  
  68.         userService.saveUser(userId, name, password);  
  69.           
  70.     }  
  71.   
  72.     public void add() throws Exception {  
  73.         System.out.println("不带参数的add方法:   " + tuser.getUserId() + "  "  
  74.                 + tuser.getName() + "  " + tuser.getPassword());  
  75.         userService.saveUser((tuser.getUserId()).toString(), tuser.getName(),  
  76.                 tuser.getPassword());  
  77.          TUser tu=getTUser();  
  78.         userService.saveRecord(tu, "add user");  
  79.           
  80.     }  
  81.   
  82.     // 添加时,验证是否已经存在数据库  
  83.     public void verify() throws Exception {  
  84.         System.out.println("UserAction:verfiy: " + tableName + " " + fieldName  
  85.                 + "  " + parameter);  
  86.         String s = userService.queryByUnique(tableName, fieldName, parameter);  
  87.         // 将验证结果返回到页面,1代表已经存在数据库中,0代表没有  
  88.         System.out.println("s=" + s);  
  89.   
  90.         HttpServletResponse response = ServletActionContext.getResponse();  
  91.         response.setContentType("text/html;Charset=utf-8");  
  92.         PrintWriter out = response.getWriter();  
  93.         out.print(s);  
  94.         out.flush();  
  95.         out.close();  
  96.     }  
  97.   
  98.     // 删除  
  99.     public void delUser(String ids) throws Exception {  
  100.         System.out.println("delUser方法:   " + ids);  
  101.         userService.delUser(ids);  
  102.         TUser tu=getTUser();  
  103.         userService.saveRecord(tu, "delete user");  
  104.           
  105.     }  
  106.     public void delUser()throws Exception{  
  107.         System.out.println("不带参数delUser方法: "+ids);  
  108.         userService.delUser(ids);  
  109.     }  
  110.     public void searchByUsername()throws Exception{  
  111.         List list=userService.searchByUsername(page,rows,searchValue);  
  112.         int size=userService.getSearchByUsernameTotal(searchValue);  
  113.         toBeJson(list,size);  
  114.     }  
  115.     // 转化WieJson格式  
  116.     @SuppressWarnings({ "rawtypes", "unchecked" })  
  117.     public void toBeJson(List list, int total) throws Exception {  
  118.         try {  
  119.             HttpServletResponse response = ServletActionContext.getResponse();  
  120.             // ???????????????  
  121.             // JSONObject jobj = new JSONObject();  
  122.             // System.out.println("UserAction.toBeJson()4");  
  123.             // jobj.accumulate("total", total);// total代表一共有多少数据  
  124.             // System.out.println("UserAction.toBeJson()1");  
  125.             // jobj.accumulate("rows", list);// rows是代表显示的页的数据  
  126.             // System.out.println("UserAction.toBeJson()3");  
  127.             // response.setCharacterEncoding("utf-8");// 指定为utf-8  
  128.             // System.out.println("UserAction.toBeJson()2" + jobj.toString());  
  129.   
  130.             String sb = "{";  
  131.             sb += ""total":" + total;  
  132.             sb += ","rows":[";  
  133.             for (TUser po : (List<TUser>) list) {  
  134.                 sb += "{";  
  135.                 sb += ""name":"" + po.getName();  
  136.                 sb += "","password":"" + po.getPassword();  
  137.                 sb += "","userId":" + po.getUserId();  
  138.                 sb += "},";  
  139.             }  
  140.             if (sb.endsWith(","))  
  141.                 sb = sb.substring(0, sb.length() - 1);  
  142.             sb += "]}";  
  143.             // System.out.println("UserAction.toBeJson()" + sb);  
  144.             response.getWriter().write(sb);// 转化为JSON格式  
  145.             // log.info(sb);  
  146.         } catch (Exception e) {  
  147.             e.printStackTrace();  
  148.         }  
  149.     }  
  150.       
  151.     //根据session来获取当前用户的信息  
  152.     @SuppressWarnings("rawtypes")  
  153.     public TUser getTUser()  
  154.     {  
  155.         ActionContext ctx=ActionContext.getContext();  
  156.         Map session=ctx.getSession();  
  157.         TUser tu=(TUser)session.get("LOGINED_USER");  
  158.         System.out.println("UserAction中:getTUser方法:"+tu.getUserId()+"  "+tu.getName());  
  159.         return tu;  
  160.     }  
  161.   
  162.     public JSONObject getJsonObj() {  
  163.         return jsonObj;  
  164.     }  
  165.   
  166.     public void setJsonObj(JSONObject jsonObj) {  
  167.         this.jsonObj = jsonObj;  
  168.     }  
  169.   
  170.     public String getRows() {  
  171.         return rows;  
  172.     }  
  173.   
  174.     public void setRows(String rows) {  
  175.         this.rows = rows;  
  176.     }  
  177.   
  178.     public String getPage() {  
  179.         return page;  
  180.     }  
  181.   
  182.     public void setPage(String page) {  
  183.         this.page = page;  
  184.     }  
  185.   
  186.     public TUser getTuser() {  
  187.         return tuser;  
  188.     }  
  189.   
  190.     public void setTuser(TUser tuser) {  
  191.         this.tuser = tuser;  
  192.     }  
  193.   
  194.     public String getTableName() {  
  195.         return tableName;  
  196.     }  
  197.   
  198.     public void setTableName(String tableName) {  
  199.         this.tableName = tableName;  
  200.     }  
  201.   
  202.     public String getFieldName() {  
  203.         return fieldName;  
  204.     }  
  205.   
  206.     public void setFieldName(String fieldName) {  
  207.         this.fieldName = fieldName;  
  208.     }  
  209.   
  210.     public String getParameter() {  
  211.         return parameter;  
  212.     }  
  213.   
  214.     public void setParameter(String parameter) {  
  215.         this.parameter = parameter;  
  216.     }  
  217.   
  218.     public UserService getUserService() {  
  219.         return userService;  
  220.     }  
  221.   
  222.     public void setUserService(UserService userService) {  
  223.         this.userService = userService;  
  224.     }  
  225.   
  226.     public String getNum() {  
  227.         return num;  
  228.     }  
  229.   
  230.     public void setNum(String num) {  
  231.         this.num = num;  
  232.     }  
  233.   
  234.     public String getIds() {  
  235.         return ids;  
  236.     }  
  237.   
  238.     public void setIds(String ids) {  
  239.         this.ids = ids;  
  240.     }  
  241.   
  242.     public String getUserId() {  
  243.         return userId;  
  244.     }  
  245.   
  246.     public void setUserId(String userId) {  
  247.         this.userId = userId;  
  248.     }  
  249.   
  250.     public String getName() {  
  251.         return name;  
  252.     }  
  253.   
  254.     public void setName(String name) {  
  255.         this.name = name;  
  256.     }  
  257.   
  258.     public String getPassword() {  
  259.         return password;  
  260.     }  
  261.   
  262.     public void setPassword(String password) {  
  263.         this.password = password;  
  264.     }  
  265.   
  266.     public ViewLogServiceImp getViewLogService() {  
  267.         return viewLogService;  
  268.     }  
  269.   
  270.     public void setViewLogService(ViewLogServiceImp viewLogService) {  
  271.         this.viewLogService = viewLogService;  
  272.     }  
  273.   
  274.     public String getSearchValue() {  
  275.         return searchValue;  
  276.     }  
  277.   
  278.     public void setSearchValue(String searchValue) {  
  279.         this.searchValue = searchValue;  
  280.     }  
  281.       
  282.   
  283. }</span>  


2.实现层,查询数据库

[java] view plain copy
 
  1. package com.ssh.serviceImp;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import javax.servlet.http.HttpSession;  
  7.   
  8. //import org.hibernate.criterion.DetachedCriteria;  
  9. import org.apache.struts2.ServletActionContext;  
  10. import org.springframework.orm.hibernate3.HibernateTemplate;  
  11.   
  12. import com.ssh.bean.TAdminLog;  
  13. import com.ssh.bean.TUser;  
  14. import com.ssh.service.UserService;  
  15.   
  16. public class UserServiceImp implements UserService {  
  17.     HibernateTemplate ht;  
  18.   
  19.     public HibernateTemplate getHt() {  
  20.         return ht;  
  21.     }  
  22.   
  23.     public void setHt(HibernateTemplate ht) {  
  24.         this.ht = ht;  
  25.     }  
  26.   
  27.     @SuppressWarnings("unchecked")  
  28.     @Override  
  29.     public List<TUser> getTUser(String username, String password) {  
  30.         // TODO Auto-generated method stub  
  31.         StringBuffer sql = new StringBuffer("from TUser where name='");  
  32.         sql.append(username + "' and password='" + password + "'");  
  33.         return ht.find(sql.toString());  
  34.     }  
  35.   
  36.     //  
  37.     @SuppressWarnings("rawtypes")  
  38.     public List getUserList(String page, String rows) {  
  39.   
  40.         int currentPage = Integer  
  41.                 .parseInt((page == null) || (page == "0") ? "1" : page);  
  42.         int pageSize = Integer.parseInt((rows == null) || rows == "0" ? "1"  
  43.                 : rows);  
  44.         System.out.println("currentPage=" + currentPage + "  pageSize="  
  45.                 + pageSize);  
  46.   
  47.         /* 
  48.          * DetachedCriteria criteria=DetachedCriteria.forClass(TUser.class); 
  49.          * List list=ht.findByCriteria(criteria, currentPage*pageSize, 
  50.          * pageSize); 
  51.          */  
  52.         StringBuffer sql = new StringBuffer("from TUser where userId>=");  
  53.         sql.append((currentPage - 1) * pageSize + 1);  
  54.         sql.append(" and userId <=");  
  55.         sql.append(currentPage * pageSize);  
  56.         List list = ht.find(sql.toString());  
  57.         return list;  
  58.     }  
  59.   
  60.     @SuppressWarnings("rawtypes")  
  61.     public int getUserTotal() throws Exception {  
  62.         List list = ht.find("from TUser");  
  63.         return list.size();  
  64.     }  
  65.   
  66.     // 新增用户信息  
  67.     public void saveUser(String userId, String name, String password)  
  68.             throws Exception {  
  69.         System.out.println("UserServiceImp:" + name);  
  70.         TUser tuser = new TUser();  
  71.         tuser.setUserId(Integer.parseInt(userId));  
  72.         tuser.setName(name);  
  73.         tuser.setPassword(password);  
  74.         ht.save(tuser);  
  75.   
  76.         HttpSession session = ServletActionContext.getRequest().getSession();  
  77.         TUser tu = new TUser();  
  78.         String uid = (String) session.getAttribute("userId");  
  79.         String na = (String) session.getAttribute("username");  
  80.         String ps = (String) session.getAttribute("password");  
  81.         tu.setUserId(Integer.parseInt(uid));  
  82.         tu.setName(na);  
  83.         tu.setPassword(ps);  
  84.         saveRecord(tu, "save user");  
  85.     }  
  86.   
  87.     // 删除用户  
  88.     @SuppressWarnings("rawtypes")  
  89.     public void delUser(String ids) throws Exception {  
  90.         int id = Integer.parseInt(ids);  
  91.         StringBuffer sql = new StringBuffer(  
  92.                 "delete TUer user where user.userId = ");  
  93.         sql.append(id);  
  94.         System.out.println(sql);  
  95.         // ht.delete(sql);  
  96.         // TUser tuser = (TUser) (ht.find("from TUser where userId = " + ids));  
  97.         TUser tuser = new TUser();  
  98.         List list = ht.find("from TUser where userId = " + ids);  
  99.         if (list.size() > 0) {  
  100.             tuser = (TUser) list.get(0);  
  101.         }  
  102.         System.out.println("***" + tuser.getName());  
  103.         ht.delete(tuser);  
  104.   
  105.         HttpSession session = ServletActionContext.getRequest().getSession();  
  106.         TUser tu = new TUser();  
  107.         String uid = (String) session.getAttribute("userId");  
  108.         String na = (String) session.getAttribute("username");  
  109.         String ps = (String) session.getAttribute("password");  
  110.   
  111.         tu.setUserId(Integer.parseInt(uid));  
  112.         tu.setName(na);  
  113.         tu.setPassword(ps);  
  114.         System.out.println("delUser:userId:");  
  115.         System.out.println(uid);  
  116.   
  117.         saveRecord(tu, "delUser user");  
  118.     }  
  119.   
  120.     // 判断是否具有唯一性  
  121.     @SuppressWarnings("rawtypes")  
  122.     public String queryByUnique(String tableName, String fieldName,  
  123.             String parameter) throws Exception {  
  124.         System.out.println("tableName:" + tableName + " fieldName:" + fieldName  
  125.                 + " parameter:" + parameter);  
  126.   
  127.         StringBuffer sql = new StringBuffer("from " + tableName + " where "  
  128.                 + fieldName + " = " + parameter);  
  129.   
  130.         System.out.println(sql.toString());  
  131.   
  132.         List list = null;  
  133.         try {  
  134.             list = ht.find(sql.toString());  
  135.             if (list != null) {  
  136.                 System.out.println("***1" + list.toString());  
  137.   
  138.                 // System.out.println(((TUser) list.get(0)).getName());  
  139.   
  140.             } else {  
  141.                 System.out.println("***2");  
  142.             }  
  143.   
  144.         } catch (Exception e) {  
  145.             e.printStackTrace();  
  146.         }  
  147.   
  148.         /* 
  149.          * if (list != null) { //System.out.println(((TUser) 
  150.          * list.get(0)).getName()); 
  151.          *  
  152.          * } else { System.out.println("***"); } 
  153.          */  
  154.   
  155.         if (list == null || list.size() != 0) {  
  156.             return "1";  
  157.         } else {  
  158.             return "0";// 代表数据库里没有这条数据;  
  159.         }  
  160.     }  
  161.   
  162.     @Override  
  163.     public void saveRecord(TUser tuser, String record) throws Exception {  
  164.         // TODO Auto-generated method stub  
  165.         TAdminLog tAdminLog = new TAdminLog(tuser, record);  
  166.         ht.save(tAdminLog);  
  167.     }  
  168.   
  169.     @Override  
  170.     public List searchByUsername(String page, String rows, String searchValue)  
  171.             throws Exception {  
  172.         // TODO Auto-generated method stub  
  173.         System.out.println("page="+page);  
  174.         System.out.println("rows="+rows);  
  175.         System.out.println("searchValue="+searchValue);  
  176.         StringBuffer sql = new StringBuffer("from TUser t where t.name ='");  
  177.         sql.append(searchValue);  
  178.         sql.append("'");//注意要加单引号  
  179.         System.out.println("searchByUsername:"+sql);  
  180.         List list = ht.find(sql.toString());  
  181.         int currentPage = Integer  
  182.                 .parseInt((page == null) || (page == "0") ? "1" : page);  
  183.         int currentRows = Integer  
  184.                 .parseInt((rows == null) || (rows == "0") ? "1" : rows);  
  185.         int number = (currentPage - 1) * currentRows;  
  186.         List li = new ArrayList();  
  187.         for (int i = number; i < (number + currentRows)  
  188.                 && i < (list.size()); i++) {  
  189.             li.add(list.get(i));  
  190.         }  
  191.         return li;  
  192.     }  
  193.   
  194.     @Override  
  195.     public int getSearchByUsernameTotal(String searchValue) throws Exception {  
  196.         // TODO Auto-generated method stub  
  197.         StringBuffer sql = new StringBuffer("from TUser t where t.name ='");  
  198.         sql.append(searchValue);  
  199.         sql.append("'");  
  200.         List list = ht.find(sql.toString());  
  201.         if (list.size() == 0) {  
  202.             return 0;  
  203.         } else {  
  204.             return list.size();  
  205.         }  
  206.     }  
  207.   
  208. }  



原文地址:https://www.cnblogs.com/huangf714/p/5864243.html