整理了下easyui与ssh(struts1)的整合实现增删改查、分页,现在将部分源码附上,struts、hibernate、spring配置及实现省略。
1.页面部分
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Row Editing in DataGrid - jQuery EasyUI Demo</title>
<link rel="stylesheet" type="text/css"
href="../../easyui/themes/gray/easyui.css">
<link rel="stylesheet" type="text/css"
href="../..//easyui/themes/icon.css">
<link rel="stylesheet" type="text/css" href="../../easyui/demo.css">
<script type="text/javascript"
src="../../easyui/jquery-1.8.0.min.js"></script>
<script type="text/javascript"
src="../../easyui/jquery.easyui.min.js"></script>
<style type="text/css">
#fm {
margin: 0;
padding: 10px 30px;
}
.ftitle {
font-size: 14px;
font-weight: bold;
color: #666;
padding: 5px 0;
margin-bottom: 10px;
border-bottom: 1px solid #ccc;
}
.fitem {
margin-bottom: 5px;
}
.fitem label {
display: inline-block;
width: 80px;
}
</style>
</head>
<body>
<h2>
专题信息浏览
</h2>
<div class="demo-info">
<div class="demo-tip icon-tip"></div>
<div>
Click the row to start editing.
</div>
</div>
<div style="margin: 10px 0;"></div>
<table id="dg" class="easyui-datagrid" pagination="true"
title="Row Editing in DataGrid" style="width: 880px; height: auto"
data-options="
iconCls: 'icon-edit',
singleSelect:true,//复选框单选还是多选
toolbar: '#tb',
url: '../../sys/news.do?method=findByTopic',
method: 'get',
frozenColumns:[[
{field:'ck',title:'ID',checkbox:'true'} ,
{field:'id',title:'ID',width:40,sortable:'true'}
]]
">
<thead>
<tr>
<th
data-options="field:'title',width:200,editor:'text',sortable:'true'">
标题
</th>
<th formatter="formatTime"
data-options="field:'pubTime',width:100,align:'right',sortable:'true'">
时间
</th>
<th data-options="field:'URL',width:380,align:'left'">
URL
</th>
<th data-options="field:'topicid',width:80,align:'center'">
topicid
</th>
</tr>
</thead>
</table>
<div id="tb" style="height: auto">
<a href="javascript:void(0)" class="easyui-linkbutton"
data-options="iconCls:'icon-add',plain:true" οnclick="create()">新增</a>
<a href="#" class="easyui-linkbutton" iconCls="icon-edit"
plain="true" οnclick="edit()">编辑</a>
<a href="#" class="easyui-linkbutton" iconCls="icon-remove"
plain="true" οnclick="remove()">删除</a>
| 时间 从:
<input id="starttime" name="starttime" class="easyui-datebox"
style="width: 100px"
data-options="formatter:myformatter,parser:myparser"></input>
到:
<input id="endtime" class="easyui-datebox" style="width: 100px"
data-options="formatter:myformatter,parser:myparser"></input>
关键词:
<input type="text" id="key" class="easyui-input" panelHeight="auto"
style="width: 100px" />
<a href="#" class="easyui-linkbutton" iconCls="icon-search"
οnclick="doSearch()">Search</a>
</div>
<script type="text/javascript">
var url;
/**新增*/
function create(){
$('#dlg').dialog('open').dialog('setTitle','嫌憎');
$('#fm').form('clear');
url = '../../sys/news.do?method=create';
}
/**编辑*/
function edit(){
var row = $('#dg').datagrid('getSelected');
if (row){
$('#dlg').dialog('open').dialog('setTitle','编辑');
$('#fm').form('load',row);
url = '../../sys/news.do?method=update&id='+row.id+'&s=1';
}
}
/**保存*/
function save(){
$('#fm').form('submit',{
url: url,
onSubmit: function(){
return $(this).form('validate');
},
success: function(result){
var result = eval('('+result+')');
if (result.success){
$('#dlg').dialog('close'); // close the dialog
$('#dg').datagrid('reload'); // reload the user data
} else {
$.messager.show({
title: 'Error',
msg: result.msg
});
}
}
});
}
/**删除*/
function remove(){
var row = $('#dg').datagrid('getSelected');
if (row){
$.messager.confirm('Confirm','你确定要删除吗?',function(r){
if (r){
$.post('../../sys/news.do?method=delete&id='+row.id,{},function(result){
if (result.success){
$('#dg').datagrid('reload'); // reload the user data
} else {
$.messager.show({ // show error message
title: 'Error',
msg: result.msg
});
}
},'json');
}
});
}
}
/**格式化数据*/
function formatTime(val,row){
if (val == '2013-09-24 08:58'){
return '<span style="color:red;">'+val+'</span>';
} else {
return val;
}
}
/**日历控件*/
function myformatter(date){
var y = date.getFullYear();
var m = date.getMonth()+1;
var d = date.getDate();
return y+'-'+(m<10?('0'+m):m)+'-'+(d<10?('0'+d):d);
}
function myparser(s){
if (!s) return new Date();
var ss = (s.split('-'));
var y = parseInt(ss[0],10);
var m = parseInt(ss[1],10);
var d = parseInt(ss[2],10);
if (!isNaN(y) && !isNaN(m) && !isNaN(d)){
return new Date(y,m-1,d);
} else {
return new Date();
}
}
/**查询*/
function doSearch(){
//alert($('#key').val());
//alert($('#endtime').datebox('getValue'));
$('#dg').datagrid('load',{
starttime: $('#starttime').datebox('getValue'),
endtime: $('#endtime').datebox('getValue'),
key: $('#key').val()
});
}
</script>
<div id="dlg" class="easyui-dialog"
style="width: 400px; height: 280px; padding: 10px 20px" closed="true"
buttons="#dlg-buttons">
<div class="ftitle">
新事件
</div>
<form id="fm" method="post" novalidate>
<div class="fitem">
<label>
标题:
</label>
<input name="title" class="easyui-validatebox" required="true">
</div>
<div class="fitem">
<label>
URL:
</label>
<input name="URL" class="easyui-validatebox" required="true">
</div>
<div class="fitem">
<label>
时间:
</label>
<input name="pubTime" class="easyui-datebox" style="width: 100px"
data-options="formatter:myformatter,parser:myparser">
</div>
</form>
</div>
<div id="dlg-buttons">
<a href="#" class="easyui-linkbutton" iconCls="icon-ok"
οnclick="save()">保存</a>
<a href="#" class="easyui-linkbutton" iconCls="icon-cancel"
οnclick="javascript:$('#dlg').dialog('close')">取消</a>
</div>
</body>
</html>
2.action部分源码
package com.demo.action;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.demo.domain.Demo;
import com.demo.domain.NewsBean;
import com.demo.domain.Topics;
import com.demo.service.DemoService;
import com.demo.service.ServiceFacade;
public class NewsAction extends BaseAction {
//private Log logger = LogFactory.getLog(this.getClass());
private ServiceFacade serviceFacade;
public void setServiceFacade(ServiceFacade serviceFacade) {
this.serviceFacade = serviceFacade;
}
public ActionForward create(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
NewsBean obj = new NewsBean();
obj.setTitle(request.getParameter("title"));
obj.setURL(request.getParameter("URL"));
obj.setPubTime(request.getParameter("pubTime"));
obj.setTopicid(Long.valueOf("4"));
//System.out.println(obj.getTitle()+obj.getURL()+obj.getPubTime());
serviceFacade.create(obj);
//用ajaxForm,必须以html格式返回json数据. 也就是 response.setContentType("text/html; charset=utf-8"); 这样返回的数据才能被设置到回调函数里面
response.setContentType("text/html;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
PrintWriter out = response.getWriter();
Map<String, Object> m = new HashMap<String, Object>();
m.put("success", "true");
//m.put("success", "true");//m.put("msg", "Some errors occured")
JSONArray jsonArray = JSONArray.fromObject(m);
int start =jsonArray.toString().indexOf("[");
int end = jsonArray.toString().lastIndexOf("}");
out.print(jsonArray.toString().substring(start+1, end+1));
out.flush();
out.close();
return null;
}
public ActionForward delete(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
NewsBean obj = serviceFacade.findNewsBeanById(Long.valueOf(request.getParameter("id")));
serviceFacade.delete(obj);
response.setContentType("text/html;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
PrintWriter out = response.getWriter();
Map<String, Object> m = new HashMap<String, Object>();
m.put("success", "true");
//m.put("success", "true");//m.put("msg", "Some errors occured")
JSONArray jsonArray = JSONArray.fromObject(m);
int start =jsonArray.toString().indexOf("[");
int end = jsonArray.toString().lastIndexOf("}");
out.print(jsonArray.toString().substring(start+1, end+1));
out.flush();
out.close();
return null;
}
public ActionForward update(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
NewsBean obj = serviceFacade.findNewsBeanById(Long.valueOf(request.getParameter("id")));
obj.setTitle(request.getParameter("title"));
obj.setURL(request.getParameter("URL"));
obj.setPubTime(request.getParameter("pubTime"));
serviceFacade.update(obj);
response.setContentType("text/html;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
PrintWriter out = response.getWriter();
Map<String, Object> m = new HashMap<String, Object>();
m.put("success", "true");
//m.put("success", "true");//m.put("msg", "Some errors occured")
JSONArray jsonArray = JSONArray.fromObject(m);
int start =jsonArray.toString().indexOf("[");
int end = jsonArray.toString().lastIndexOf("}");
out.print(jsonArray.toString().substring(start+1, end+1));
out.flush();
out.close();
return null;
}
public ActionForward toFindByTopic(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
return mapping.findForward("list1");
}
public ActionForward findByTopic(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String page = request.getParameter("page");
String rows = request.getParameter("rows");
String sort = request.getParameter("sort");
String order = request.getParameter("order");
//分页
int intPage = Integer.parseInt((page == null || page == "0") ? "1":page);
int number = Integer.parseInt((rows == null || rows == "0") ? "10":rows);
//排序
sort = (sort == null || "".equals(sort)) ? "id":sort; //排序字段
order = (order == null || "".equals(order)) ? "DESC":order; //排序默认DESC
//查询(可用)
// String key = request.getParameter("key");
// String starttime = request.getParameter("starttime");
// String endtime = request.getParameter("endtime");
// if(key!=null) System.out.println("key"+key);
// if(starttime!=null) System.out.println("starttime"+starttime);
// if(endtime!=null) System.out.println("endtime"+endtime);
//修改
//删除
//每页显示条数
// System.out.println(serviceFacade.getNewsCounts());
List<NewsBean> newslist = serviceFacade.findNews(intPage, number,sort,order);
//转换为json数据
Map<String, Object> m = new HashMap<String, Object>();
m.put("total", serviceFacade.getNewsCounts());
m.put("rows", newslist);
JSONArray jsonArray = JSONArray.fromObject(m);
int start =jsonArray.toString().indexOf("[");
int end = jsonArray.toString().lastIndexOf("}");
response.setContentType("application/json;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
PrintWriter out = response.getWriter();
out.print(jsonArray.toString().substring(start+1, end+1));
out.flush();
out.close();
newslist = null;
newslist = null;
jsonArray = null;
return null;
}
}