easyui與ssh(struts1)的整合實現增刪改查、分頁

來源:互聯網
上載者:User

整理了下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><thdata-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" onclick="create()">新增</a><a href="#" class="easyui-linkbutton" iconCls="icon-edit"plain="true" onclick="edit()">編輯</a><a href="#" class="easyui-linkbutton" iconCls="icon-remove"plain="true" onclick="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"onclick="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 messagetitle: '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"onclick="save()">儲存</a><a href="#" class="easyui-linkbutton" iconCls="icon-cancel"onclick="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;}}


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.