easyui Datagrid+searchbox 实现搜索功能

说明:采用了ssh架构


这是搜索前的界面:

easyui Datagrid+searchbox 实现搜索功能_第1张图片

这是根据用户名搜索后出现的搜索结果:

easyui Datagrid+searchbox 实现搜索功能_第2张图片

1.前台页面:

<%@ page language="java" pageEncoding="utf-8" isELIgnored="false"%>
<%
	String path = request.getContextPath();
%>
<%@ taglib prefix="s" uri="/struts-tags"%>




Basic DataGrid - jQuery EasyUI Demo








	
	


2.strust.xml的配置

	
		
		
		
		
		
		
		
		
		
		
	

3.action类

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) 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;
	}
	

}

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 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 实现搜索功能_第3张图片

注:全部的源码,我压缩后传到csdn资源上myf工程,感兴趣的朋友可以看一下,刚入门,源码写的比较菜,欢迎大家提出意见和建议,有问题发我扣扣消息,2513822561


你可能感兴趣的:(Java,Web,easyUI学习笔记)