ExtJs实现EditGrid中的增删改查操作(2)
1.本例要实现的效果为,如下图所示的窗口信息
双击某条信息,将会出现一个工具条可以对其进行操作,如下
2.本例是在ExtJs官方提供的examples里面的基础上改进的,使用的是SSH框架的方式,当窗口启动时发送查询请求并返回json格式的数据,然后更新到窗口中区。当对其进行操作时,也是利用异步请求的方式发送数据,并在操作成功后更新窗口数据。
4.在jsp页面上新建一个快捷方式的dt,如下
<dt id="tool-memo-shortcut">
<a href="#">
<img src="<%=path%>/image/desktop/s.gif"/>
<div>便利贴</div>
</a>
</dt>
5.然后在css文件中做如下配置,使其显示一个图标。
/*桌面天气预报的快捷方式*/
#tool-clock-shortcut img{
width : 48px;
height : 48px;
background-image: url(/ipurse/image/desktop/add/weather48x48.png);
filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/ipurse/image/desktop/add/weather48x48.png', sizingMethod='scale');
}
6.此时,部署网站后就可以在桌面上看到我们的图标了。
7.下面写窗口的点击初始化函数。首先声明一个窗口函数,如下
8.下面具体实现其功能
/*
* by:rush date:2011年3月28日 22:28:40
* 功能:用于显示便签的窗口
* */
var memoEditor = null;//声明一个行编辑控件的实例
var memoGrid = null;
var memoStore = null;
MyDesktop.MemoWindow = Ext.extend(Ext.app.Module,{
id : 'tool-memo',
init : function(){
this.launcher = {
text: '便签',
iconCls:'icon-grid',
handler : this.createWindow,//这句表明其创建窗口的句柄
scope: this,
windowId:'tool-memo' //窗口的id
}
},
createWindow : function(src){
var desktop = this.app.getDesktop();//取得桌面句柄
var win = desktop.getWindow('tool-memo');//取得桌面快捷方式对应的窗口句柄
////////////////
//////////////////////////////////////////
Ext.QuickTips.init(); //初始化快速提示功能
//建立一个数据记录的对象
var Memo = new Ext.data.Record.create([
{ name : 'title' , type : 'string'},
{name : 'saveDate', type : 'date',dateFormat:'Y-m-d'},
{name : 'lateDate' , type : 'date',dateFormat:'Y-m-d'},
{name : 'detail', type : 'string'}
]);
//声明一个行编辑控件的实例
memoEditor = new Ext.ux.grid.RowEditor({
saveText: '更新',
cancelText : '取消',
deleteText : '删除'
});
////声明一个writer,来将信息写入到后台
var memoWriter = new Ext.data.JsonWriter({
encode: true,
writeAllFields: false // 写入所有字段,而不仅仅是那些发生变化的字段
});
//声明一个数据存储仓库,使用json的方式获取远程数据
memoStore = new Ext.data.GroupingStore({
autoSave : false,//设置不自动保存
writer : memoWriter,
reader: new Ext.data.JsonReader({
id : 'id',
totalProperty : 'totalProperty',
root : 'memoList'},
[
{name : 'id' , type: 'int'},
{name: 'title', type:'string'},
{name: 'saveDate', type: 'date',dateFormat:'Y-m-d'},
{name: 'lateDate', type: 'date',dateFormat:'Y-m-d'},
{name: 'detail', type: 'string'}
]),
proxy: new Ext.data.HttpProxy({
url : '/ipurse/easyMemo.do?method=loadMemo',
method:"post"
}),
sortInfo: {field: 'title', direction: 'DESC'}
});
/////////////
//////////
if(!win){
win = desktop.createWindow({
id : 'tool-memo',
title : '便签(双击编辑信息)',
shim:false,
animCollapse:false,
constrainHeader:true,
width : 800,
height : 600,
layout : 'fit',
labelWidth : 80,
labelAlign : 'right',
buttonAlign : 'center',
items :
memoGrid = new Ext.grid.GridPanel({
store : memoStore,
width : 800,
region:'center',
margins: '0 5 5 5',
loadMask: {msg:'正在加载数据,请稍侯……'},
plugins: [memoEditor],
view: new Ext.grid.GroupingView({
markDirty: false
}),
columns: [
new Ext.grid.RowNumberer() ,//显示行号
{
id : 'title',
header: "事情提要",
align : 'center' ,
width: 200,
sortable: true,
dataIndex: 'title',
editor: { ////这句话是关键,有了这句话就可以实现编辑功能
xtype: 'textfield',
allowBlank: false
}
},
{
xtype : 'datecolumn', //此处为日期类型
format : 'Y-m-d',
id : 'saveDate',
header: "保存时间",
align : 'center' ,
width: 100,
sortable: true,
dataIndex: 'saveDate',
editor: {////这句话是关键,有了这句话就可以实现编辑功能
xtype: 'datefield',
format : 'Y-m-d',
allowBlank: false,
minValue: '1999-01-01',
minText: '将来的事情不能发生在过去呀,难道你穿越了?oh my god!'
// maxValue: (new Date()).format('Y-m-d')
}
},
{
xtype : 'datecolumn', //此处为日期类型
format : 'Y-m-d',
id : 'lateDate',
header: "到期时间",
align : 'center' ,
width: 100,
sortable: true,
dataIndex: 'lateDate',
groupRenderer: Ext.util.Format.dateRenderer('Y-m-d'),
editor: {////这句话是关键,有了这句话就可以实现编辑功能
xtype: 'datefield',
format : 'Y-m-d',
allowBlank: false,
minValue: '1999-01-01',
minText: '将来的事情不能发生在过去呀,难道你穿越了?oh my god!'
// maxValue: (new Date()).format('Y-m-d')
}
},
{
id : 'detail',
header: "详细内容",
align : 'center' ,
width: 350,
sortable: true,
dataIndex: 'detail',
editor: { ////这句话是关键,有了这句话就可以实现编辑功能
xtype: 'textarea',
atuoHeight : true,
allowBlank: false
}
}
],
tbar:
[
{
text : '添加新便利贴',
tooltip : '添加一个新的便利贴',
iconCls : 'add',
handler : function(){
//判断是不是正在修改信息
if(memoEditor.isVisible()){
Ext.Msg.show({
title : 'xxx网提示',
msg : '您有内容正在编辑中,请保存后再添加数据!',
icon : Ext.MessageBox.WARNING,
buttons : Ext.Msg.OK
}); ///这里需要修改
return;
}
//设置save的标题为保存
memoEditor.saveText = '保存';
//取得默认的时间日期
var d = new Date();
var y = d.getYear();
var m = d.getMonth();
if(m < 10){
m++;
}
if(m < 10){
m = '0' + m;
}
var n = d.getDate();
if(n < 10){
n = '0' + n ;
}
var memo = new Memo({
title : '新建便签',
saveDate : y+"-"+m+"-"+n,
lateDate : y+"-"+m+"-"+n,
detail : '在这里输入详细描述'
});
memoEditor.stopEditing();//停止编辑
memoStore.insert(0,memo);//向第0行插入数据
memoGrid.getView().refresh();//刷新表格
memoGrid.getSelectionModel().selectRow(0);//选中第一行
memoEditor.startEditing(0);//开始编辑第一行
}
}
],
bbar:new Ext.PagingToolbar(
{
buttonAlign : 'center',
nextText : '下一页',
prevText : '前一页',
refreshText : '刷新数据',
firstText : '第一页',
lastText : '最后一页',
pageSize:20,
store:memoStore,
displayInfo:true,
displayMsg:'显示第 {0} 条到 {1} 条记录,一共 {2} 条',
emptyMsg:'没有记录'
}
)
})
});
}
win.show();
memoGrid.render();
memoStore.load({params:{start:0,limit:20 }});
}
});
9.为了防止有的同鞋找不到RowEditor.js文件,在这里直接贴出来吧
/*!
* Ext JS Library 3.3.1
* Copyright(c) 2006-2010 Sencha Inc.
* licensing@sencha.com
* http://www.sencha.com/license
*/
Ext.ns('Ext.ux.grid');
/**
* @class Ext.ux.grid.RowEditor
* @extends Ext.Panel
* Plugin (ptype = 'roweditor') that adds the ability to rapidly edit full rows in a grid.
* A validation mode may be enabled which uses AnchorTips to notify the user of all
* validation errors at once.
*
* @ptype roweditor
*/
Ext.ux.grid.RowEditor = Ext.extend(Ext.Panel, {
floating: true,
shadow: false,
layout: 'hbox',
cls: 'x-small-editor',
buttonAlign: 'center',
baseCls: 'x-row-editor',
elements: 'header,footer,body',
frameWidth: 20,//5
buttonPad: 13,//3
clicksToEdit: 'auto',
monitorValid: true,
focusDelay: 250,
errorSummary: true,
saveText: 'Save',
cancelText: 'Cancel',
deleteText : 'Delete',
commitChangesText: 'You need to commit or cancel your changes',
errorText: 'Errors',
bodyStyle : 'background-color:#C8D99E;',//body color
defaults: {
normalWidth: true
},
initComponent: function(){
Ext.ux.grid.RowEditor.superclass.initComponent.call(this);
this.addEvents(
/**
* @event beforeedit
* Fired before the row editor is activated.
* If the listener returns <tt>false</tt> the editor will not be activated.
* @param {Ext.ux.grid.RowEditor} roweditor This object
* @param {Number} rowIndex The rowIndex of the row just edited
*/
'beforeedit',
/**
* @event canceledit
* Fired when the editor is cancelled.
* @param {Ext.ux.grid.RowEditor} roweditor This object
* @param {Boolean} forced True if the cancel button is pressed, false is the editor was invalid.
*/
'canceledit',
/**
* @event validateedit
* Fired after a row is edited and passes validation.
* If the listener returns <tt>false</tt> changes to the record will not be set.
* @param {Ext.ux.grid.RowEditor} roweditor This object
* @param {Object} changes Object with changes made to the record.
* @param {Ext.data.Record} r The Record that was edited.
* @param {Number} rowIndex The rowIndex of the row just edited
*/
'validateedit',
/**
* @event afteredit
* Fired after a row is edited and passes validation. This event is fired
* after the store's update event is fired with this edit.
* @param {Ext.ux.grid.RowEditor} roweditor This object
* @param {Object} changes Object with changes made to the record.
* @param {Ext.data.Record} r The Record that was edited.
* @param {Number} rowIndex The rowIndex of the row just edited
*/
'afteredit'
);
},
init: function(grid){
this.grid = grid;
this.ownerCt = grid;
if(this.clicksToEdit === 2){
grid.on('rowdblclick', this.onRowDblClick, this);
}else{
grid.on('rowclick', this.onRowClick, this);
if(Ext.isIE){
grid.on('rowdblclick', this.onRowDblClick, this);
}
}
// stopEditing without saving when a record is removed from Store.
grid.getStore().on('remove', function() {
this.stopEditing(false);
},this);
grid.on({
scope: this,
keydown: this.onGridKey,
columnresize: this.verifyLayout,
columnmove: this.refreshFields,
reconfigure: this.refreshFields,
beforedestroy : this.beforedestroy,
destroy : this.destroy,
bodyscroll: {
buffer: 250,
fn: this.positionButtons
}
});
grid.getColumnModel().on('hiddenchange', this.verifyLayout, this, {delay:1});
grid.getView().on('refresh', this.stopEditing.createDelegate(this, []));
},
beforedestroy: function() {
this.stopMonitoring();
this.grid.getStore().un('remove', this.onStoreRemove, this);
this.stopEditing(false);
Ext.destroy(this.btns, this.tooltip);
},
refreshFields: function(){
this.initFields();
this.verifyLayout();
},
isDirty: function(){
var dirty;
this.items.each(function(f){
if(String(this.values[f.id]) !== String(f.getValue())){
dirty = true;
return false;
}
}, this);
return dirty;
},
startEditing: function(rowIndex, doFocus){
if(this.editing && this.isDirty()){
this.showTooltip(this.commitChangesText);
return;
}
if(Ext.isObject(rowIndex)){
rowIndex = this.grid.getStore().indexOf(rowIndex);
}
if(this.fireEvent('beforeedit', this, rowIndex) !== false){
this.editing = true;
var g = this.grid, view = g.getView(),
row = view.getRow(rowIndex),
record = g.store.getAt(rowIndex);
this.record = record;
this.rowIndex = rowIndex;
this.values = {};
if(!this.rendered){
this.render(view.getEditorParent());
}
var w = Ext.fly(row).getWidth();
this.setSize(w);
if(!this.initialized){
this.initFields();
}
var cm = g.getColumnModel(), fields = this.items.items, f, val;
for(var i = 0, len = cm.getColumnCount(); i < len; i++){
val = this.preEditValue(record, cm.getDataIndex(i));
f = fields[i];
f.setValue(val);
this.values[f.id] = Ext.isEmpty(val) ? '' : val;
}
this.verifyLayout(true);
if(!this.isVisible()){
this.setPagePosition(Ext.fly(row).getXY());
} else{
this.el.setXY(Ext.fly(row).getXY(), {duration:0.15});
}
if(!this.isVisible()){
this.show().doLayout();
}
if(doFocus !== false){
this.doFocus.defer(this.focusDelay, this);
}
}
},
stopEditing : function(saveChanges){
this.editing = false;
if(!this.isVisible()){
return;
}
if(saveChanges === false || !this.isValid()){
this.hide();
this.fireEvent('canceledit', this, saveChanges === false);
return;
}
var changes = {},
r = this.record,
hasChange = false,
cm = this.grid.colModel,
fields = this.items.items;
for(var i = 0, len = cm.getColumnCount(); i < len; i++){
if(!cm.isHidden(i)){
var dindex = cm.getDataIndex(i);
if(!Ext.isEmpty(dindex)){
var oldValue = r.data[dindex],
value = this.postEditValue(fields[i].getValue(), oldValue, r, dindex);
if(String(oldValue) !== String(value)){
changes[dindex] = value;
hasChange = true;
}
}
}
}
if(hasChange && this.fireEvent('validateedit', this, changes, r, this.rowIndex) !== false){
r.beginEdit();
Ext.iterate(changes, function(name, value){
r.set(name, value);
});
r.endEdit();
this.fireEvent('afteredit', this, changes, r, this.rowIndex);
}
this.hide();
},
verifyLayout: function(force){
if(this.el && (this.isVisible() || force === true)){
var row = this.grid.getView().getRow(this.rowIndex);
this.setSize(Ext.fly(row).getWidth(), Ext.isIE ? Ext.fly(row).getHeight() + 9 : undefined);
var cm = this.grid.colModel, fields = this.items.items;
for(var i = 0, len = cm.getColumnCount(); i < len; i++){
if(!cm.isHidden(i)){
var adjust = 0;
if(i === (len - 1)){
adjust += 3; // outer padding
} else{
adjust += 1;
}
fields[i].show();
fields[i].setWidth(cm.getColumnWidth(i) - adjust);
} else{
fields[i].hide();
}
}
this.doLayout();
this.positionButtons();
}
},
slideHide : function(){
this.hide();
},
initFields: function(){
var cm = this.grid.getColumnModel(), pm = Ext.layout.ContainerLayout.prototype.parseMargins;
this.removeAll(false);
for(var i = 0, len = cm.getColumnCount(); i < len; i++){
var c = cm.getColumnAt(i),
ed = c.getEditor();
if(!ed){
ed = c.displayEditor || new Ext.form.DisplayField();
}
if(i == 0){
ed.margins = pm('0 1 2 1');
} else if(i == len - 1){
ed.margins = pm('0 0 2 1');
} else{
if (Ext.isIE) {
ed.margins = pm('0 0 2 0');
}
else {
ed.margins = pm('0 1 2 0');
}
}
ed.setWidth(cm.getColumnWidth(i));
ed.column = c;
if(ed.ownerCt !== this){
ed.on('focus', this.ensureVisible, this);
ed.on('specialkey', this.onKey, this);
}
this.insert(i, ed);
}
this.initialized = true;
},
onKey: function(f, e){
if(e.getKey() === e.ENTER){
this.stopEditing(true);
e.stopPropagation();
}
},
onGridKey: function(e){
if(e.getKey() === e.ENTER && !this.isVisible()){
var r = this.grid.getSelectionModel().getSelected();
if(r){
var index = this.grid.store.indexOf(r);
this.startEditing(index);
e.stopPropagation();
}
}
},
ensureVisible: function(editor){
if(this.isVisible()){
this.grid.getView().ensureVisible(this.rowIndex, this.grid.colModel.getIndexById(editor.column.id), true);
}
},
onRowClick: function(g, rowIndex, e){
if(this.clicksToEdit == 'auto'){
var li = this.lastClickIndex;
this.lastClickIndex = rowIndex;
if(li != rowIndex && !this.isVisible()){
return;
}
}
this.startEditing(rowIndex, false);
this.doFocus.defer(this.focusDelay, this, [e.getPoint()]);
},
onRowDblClick: function(g, rowIndex, e){
this.startEditing(rowIndex, false);
this.doFocus.defer(this.focusDelay, this, [e.getPoint()]);
},
onRender: function(){
Ext.ux.grid.RowEditor.superclass.onRender.apply(this, arguments);
this.el.swallowEvent(['keydown', 'keyup', 'keypress']);
this.btns = new Ext.Panel({
baseCls: 'x-plain',
cls: 'x-btns',
elements:'body',
layout: 'table',
width: (this.minButtonWidth * 2) + (this.frameWidth * 2) + (this.buttonPad * 4), // width must be specified for IE
items: [{
ref: 'saveBtn',
itemId: 'saveBtn',
xtype: 'button',
text: this.saveText,
width: this.minButtonWidth,
// handler: this.stopEditing.createDelegate(this, [true])
handler : saveOrUpdateMemo
},
{//add by Rush 添加了一个删除按钮
xtype : 'button',
itemId : 'deleteBtn',
id : 'deleteBtn',
text : this.deleteText,
width : this.minButtonWidth,
handler : deleteMemo
}
, {
xtype: 'button',
text: this.cancelText,
width: this.minButtonWidth,
handler: this.stopEditing.createDelegate(this, [false])
}
]
});
this.btns.render(this.bwrap);
},
afterRender: function(){
Ext.ux.grid.RowEditor.superclass.afterRender.apply(this, arguments);
this.positionButtons();
if(this.monitorValid){
this.startMonitoring();
}
},
onShow: function(){
if(this.monitorValid){
this.startMonitoring();
}
Ext.ux.grid.RowEditor.superclass.onShow.apply(this, arguments);
},
onHide: function(){
Ext.ux.grid.RowEditor.superclass.onHide.apply(this, arguments);
this.stopMonitoring();
this.grid.getView().focusRow(this.rowIndex);
},
positionButtons: function(){
if(this.btns){
var g = this.grid,
h = this.el.dom.clientHeight,
view = g.getView(),
scroll = view.scroller.dom.scrollLeft,
bw = this.btns.getWidth(),
width = Math.min(g.getWidth(), g.getColumnModel().getTotalWidth());
this.btns.el.shift({left: (width/2)-(bw/2)+scroll, top: h - 2, stopFx: true, duration:0.2});
}
},
// private
preEditValue : function(r, field){
var value = r.data[field];
return this.autoEncode && typeof value === 'string' ? Ext.util.Format.htmlDecode(value) : value;
},
// private
postEditValue : function(value, originalValue, r, field){
return this.autoEncode && typeof value == 'string' ? Ext.util.Format.htmlEncode(value) : value;
},
doFocus: function(pt){
if(this.isVisible()){
var index = 0,
cm = this.grid.getColumnModel(),
c;
if(pt){
index = this.getTargetColumnIndex(pt);
}
for(var i = index||0, len = cm.getColumnCount(); i < len; i++){
c = cm.getColumnAt(i);
if(!c.hidden && c.getEditor()){
c.getEditor().focus();
break;
}
}
}
},
getTargetColumnIndex: function(pt){
var grid = this.grid,
v = grid.view,
x = pt.left,
cms = grid.colModel.config,
i = 0,
match = false;
for(var len = cms.length, c; c = cms[i]; i++){
if(!c.hidden){
if(Ext.fly(v.getHeaderCell(i)).getRegion().right >= x){
match = i;
break;
}
}
}
return match;
},
startMonitoring : function(){
if(!this.bound && this.monitorValid){
this.bound = true;
Ext.TaskMgr.start({
run : this.bindHandler,
interval : this.monitorPoll || 200,
scope: this
});
}
},
stopMonitoring : function(){
this.bound = false;
if(this.tooltip){
this.tooltip.hide();
}
},
isValid: function(){
var valid = true;
this.items.each(function(f){
if(!f.isValid(true)){
valid = false;
return false;
}
});
return valid;
},
// private
bindHandler : function(){
if(!this.bound){
return false; // stops binding
}
var valid = this.isValid();
if(!valid && this.errorSummary){
this.showTooltip(this.getErrorText().join(''));
}
this.btns.saveBtn.setDisabled(!valid);
this.fireEvent('validation', this, valid);
},
lastVisibleColumn : function() {
var i = this.items.getCount() - 1,
c;
for(; i >= 0; i--) {
c = this.items.items[i];
if (!c.hidden) {
return c;
}
}
},
showTooltip: function(msg){
var t = this.tooltip;
if(!t){
t = this.tooltip = new Ext.ToolTip({
maxWidth: 600,
cls: 'errorTip',
width: 300,
title: this.errorText,
autoHide: false,
anchor: 'left',
anchorToTarget: true,
mouseOffset: [40,0]
});
}
var v = this.grid.getView(),
top = parseInt(this.el.dom.style.top, 10),
scroll = v.scroller.dom.scrollTop,
h = this.el.getHeight();
if(top + h >= scroll){
t.initTarget(this.lastVisibleColumn().getEl());
if(!t.rendered){
t.show();
t.hide();
}
t.body.update(msg);
t.doAutoWidth(20);
t.show();
}else if(t.rendered){
t.hide();
}
},
getErrorText: function(){
var data = ['<ul>'];
this.items.each(function(f){
if(!f.isValid(true)){
data.push('<li>', f.getActiveError(), '</li>');
}
});
data.push('</ul>');
return data;
}
});
Ext.preg('roweditor', Ext.ux.grid.RowEditor);
10.下面给出SSH框架的后台实现。
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.guet.function.easyMemo.view.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import com.guet.function.easyMemo.domain.EasyMemo;
import com.guet.function.easyMemo.service.IEasyMemoService;
import com.guet.function.easyMemo.view.form.EasyMemoForm;
import com.guet.function.util.PagerModel;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.*;
import javax.imageio.*;
/**
* MyEclipse Struts
* Creation date: 03-29-2011
*
* XDoclet definition:
* @struts.action path="/easyMemo" name="easyMemoForm" parameter="method" scope="request" validate="true"
*/
public class EasyMemoAction extends DispatchAction {
private IEasyMemoService easyMemoService;
/*
* by:rush date:2011年3月29日 19:31:53
* 功能:加载便签库
* 注:这部分函数没有实现完全,现在只是查询全部的信息,以后还要加上登陆账号的控制
* */
public ActionForward loadMemo(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
String hql = "select new map (e.id as id,e.title as title,e.saveDate as saveDate,e.lateDate as lateDate,e.detail as detail) from EasyMemo e order by e.id desc"
//List list = easyMemoService.findByHql(hql);
//int totalProperty = list.size();///设置查询的总数目
int start;
try {
start = Integer.parseInt(request.getParameter("start"));
} catch (NumberFormatException e1) {
start = 0;
}
int limit;
try {
limit = Integer.parseInt(request.getParameter("limit"));
} catch (NumberFormatException e1) {
limit = 2 ;
}
/*if(start>0)
start = start/limit;*/
/////////////下面开始处理分页数据
/*List listTemp = new ArrayList();//定义一个列表的临时变量
for(int i= start ; i< limit + start ; i++ ){
if(i == totalProperty){
break;
}
listTemp.add(list.get(i));
}
list = listTemp;
///////////////////
JSONArray memoObject = JSONArray.fromObject(list);
PrintWriter pw = null;
try {
//设置字符集编码
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
response.setHeader("Cache-Control", "no-cache");
pw = response.getWriter();
//为了分页,要加上start,limit,totalProperty,下面的符合json数据的形式
String jsonString = "{start:"+start+",limit:"+limit+",totalProperty:"+totalProperty+",memoList:"+memoObject.toString()+"}"
pw.print(jsonString);//输出json结果
} catch (Exception e) {
e.printStackTrace();
}*/
try {
PagerModel pagerModel = easyMemoService.findByHql(hql, start, limit, "start", "limit", "totalProperty", "memoList");
String jsonString = pagerModel.getJSONArrayString();
PrintWriter pw = null;
//设置字符集编码
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
response.setHeader("Cache-Control", "no-cache");
pw = response.getWriter();
pw.print(jsonString);//输出json结果
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/*
* by:rush date:2011年3月29日 21:05:13
* 功能:添加数据到数据库,
* 注:这部分函数也没有完全实现,没有考虑登陆的情况
* */
public ActionForward addMemoData(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
try {
EasyMemoForm easyMemoForm = (EasyMemoForm)form;
//声明一个便签的实例
EasyMemo easyMemo = new EasyMemo();
easyMemo.setUserId(easyMemoForm.getUserId());
easyMemo.setTitle(easyMemoForm.getTitle());
easyMemo.setSaveDate(easyMemoForm.getSaveDate());
easyMemo.setLateDate(easyMemoForm.getLateDate());
easyMemo.setDetail(easyMemoForm.getDetail());
/////////保存实例
easyMemoService.save(easyMemo);
//声明一个输出流
PrintWriter printWriter = null;
//设置字符集编码
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
response.setHeader("Cache-Control", "no-cache");
//获取到输出流
printWriter = response.getWriter();
printWriter.print("success");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/*
* by:rush date:2011年4月1日 09:40:34
* 功能:根据传递进来的memo的id号,删除这一条信息
* */
public ActionForward deleteMemoData(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
PrintWriter printWriter = null;//声明输出流对象
String id = request.getParameter("id");//获取传递进来的Memo的唯一编号
try {
easyMemoService.deleteById(Integer.valueOf(id.trim()));//根据id号码删除数据
//设置字符集编码
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
response.setHeader("Cache-Control", "no-cache");
printWriter = response.getWriter();//获取输出流对象
printWriter.print("success");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/*
* by:rush date:2011年4月1日 15:05:21
* 功能:更新便签内容
* */
public ActionForward updateMemoData(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
try {
EasyMemoForm easyMemoForm = (EasyMemoForm)form;//将页面信息强制转换到form类中途
EasyMemo easyMemo = easyMemoService.findById(easyMemoForm.getId());///按照id查找便签
if (easyMemo!=null) {
easyMemo.setTitle(easyMemoForm.getTitle());
easyMemo.setSaveDate(easyMemoForm.getSaveDate());
easyMemo.setLateDate(easyMemoForm.getLateDate());
easyMemo.setDetail(easyMemoForm.getDetail());
//更新信息
easyMemoService.merge(easyMemo);
PrintWriter printWriter = null;
//设置字符集编码
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
response.setHeader("Cache-Control", "no-cache");
printWriter = response.getWriter();//获取输出流对象
///输出成功信息
printWriter.print("success");
}else {
/////中情况应该不会发生,如果发生将是一个大的bug!!!
return null;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/*
* by:rush date:2011年4月1日 16:18:36
* 功能:生成便签的图片并显示在桌面上
* */
public ActionForward loadImage(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
try {
int width = 260, height = 130;//设置图片的长度和宽度
int fontSize = 12;
String title = "title"//例子
String lateDate = "时间:2010-04-01" //例子
String detail = "今天下午,你的,我的撒谎卡死开发哈萨克后付款的还是分开灰色的客户更快"//例子
//////////////////
List list = easyMemoService.findAll();
Random random = new Random();
int indexList = random.nextInt(list.size());
EasyMemo easyMemo = (EasyMemo)list.get(indexList);
title = easyMemo.getTitle().trim();
lateDate = "日期:"+easyMemo.getLateDate();
detail = easyMemo.getDetail();
//////////计算图像的高度
//表示所有字符的长度
int sizeFont = detail.length()*fontSize;
//声明一个表示有几行的变量
int len = sizeFont / width;
if((sizeFont % width) > 0){
len++;
}
/////////////////
height = 70 + len * fontSize;
////////////
//声明一个图像变量
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
//获取图形上下文
Graphics graphics = image.getGraphics();
int r=random.nextInt(255),g=random.nextInt(255),b=random.nextInt(255);
Color backgroundColor = new Color(r,g,b);//初始化一个染色的类
graphics.setColor(backgroundColor);//设定背景色
graphics.fillRect(0, 0, width, height);//将染色填充到区域
graphics.setFont(new Font("楷体",Font.PLAIN,fontSize));//设置字体样式
graphics.setColor(new Color(0,0,0));//设置字体为黑色
///////将标题居中
int x = (width/2) - (title.length() * fontSize)/2;
graphics.drawString(title, x, 20);//绘制标题文本
graphics.drawString(lateDate, 2, 40);//绘制到期时间文本
//宽度/每个字的宽度
width -= 10;
int rowSize = width / fontSize;
for(int i=0;i<len;i++){
if(i==len-1){
graphics.drawString(detail.substring(i*rowSize), 5, 60 +(i*fontSize));
}else {
graphics.drawString(detail.substring(i*rowSize, (i+1)*rowSize), 5, 60 +(i*fontSize));
}
}
///是图像生效
graphics.dispose();
//下面进行输出页面
response.setContentType("image/jpeg");
response.setCharacterEncoding("utf-8");
response.setHeader("pragma", "No-cache");
response.setHeader("Cache-Control", "No-cache");
response.setDateHeader("Expires", 0);
///下面输出图像到页面
ImageIO.write(image, "JPEG", response.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public IEasyMemoService getEasyMemoService() {
return easyMemoService;
}
public void setEasyMemoService(IEasyMemoService easyMemoService) {
this.easyMemoService = easyMemoService;
}
}
////////////////////////////OK,这样就实现了全部功能。