说明:采用了ssh架构
这是搜索前的界面:
这是根据用户名搜索后出现的搜索结果:
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();
}
}
}
数据库截图:
注:全部的源码,我压缩后传到csdn资源上myf工程,感兴趣的朋友可以看一下,刚入门,源码写的比较菜,欢迎大家提出意见和建议,有问题发我扣扣消息,2513822561