extjs应用实例

一、js就一个文件:plans.js
Ext.namespace("com.ibeans.ui");


/**
 * 数据列表
 * @class com.ibeans.PlansGridPanel 
 * @extends Ext.grid.GridPanel
 */
PlansGridPanel = Ext.extend(Ext.grid.GridPanel,{
	//1、定义基本属性
	id : 'id_plans_gridpanel',
	region : 'center',
	frame : true,
	border : true,
	trackMouseOver : true,
	loadMask : true,
	viewConfig : {forceFit : true},
	
	
	
	//2、重写父类函数initComonent(),完成对象的构造和初始化 
    initComponent : function() {    //必须,  
        this.store = new Ext.data.JsonStore({
			url : rootPath+'/plans/plans_findPageList.action',
			totalProperty : 'totalSize',
			id : 'id',
			root : 'list',
			remoteSort : true,
			fields :[
				{name:"plans.id",mapping:"id"},
				{name:"plans.plansName",mapping:"plansName"},
				{name:"plans.plansType",mapping:"plansType"},
				{name:"plans.recorder",mapping:"recorder"},
				{name:"plans.orgId",mapping:"orgId"},
				{name:"plans.orgName",mapping:"orgName"},
				{name:"plans.compileOrgName",mapping:"compileOrgName"},
				{name:"plans.issueOrgName",mapping:"issueOrgName"},
				{name:"plans.issueDate",mapping:"issueDate"},
				{name:"plans.recordDate",mapping:"recordDate"},
				{name:"plans.updateDate",mapping:"updateDate"},
				{name:"plans.status",mapping:"status"},
				{name:"plans.remark",mapping:"remark"}
			]
		}); 
        this.store.load({
			params : {
				start : 0,
				limit : 15
			}
		});
		
		this.sm = new Ext.grid.CheckboxSelectionModel();
		
        this.cm = new Ext.grid.ColumnModel([
			new Ext.grid.RowNumberer(), 
			this.sm,
			{
				header : "预案名称",
				width : 120,
				sortable : true,
				dataIndex : 'plans.plansName'
			}, {
				header : "预案类型",
				width : 90,
				sortable : true,
				dataIndex : 'plans.plansType'		
			}, {
				header : "编制单位",
				width : 90,
				sortable : true,
				dataIndex : 'plans.compileOrgName'
			}, {
				header : "发布单位",
				width : 90,
				sortable : true,
				dataIndex : 'plans.issueOrgName'
			},{
				header : "发布时间",
				width : 90,
				sortable : true,
				dataIndex : 'plans.issueDate',
				renderer : function(value){
					var v = value.substring(0,10);
					return v;
				}
			},{
				header : "报备时间",
				width : 90,
				sortable : true,
				dataIndex : 'plans.recordDate'
			},{
				header : "预案状态",
				width : 90,
				sortable : true,
				dataIndex : 'plans.status',
				renderer : function(value) {
					if(value=="0") value="已保存";
					if(value=="1") value="已备案";
					if(value=="2") value="修订中";
					return value;
				}
			}
		]); 
        this.cm.defaultSortable = true; 
         
        this.tbar = new Ext.Toolbar([{
			text : '添加',
			tooltip : '添加',
			iconCls : 'icon-add',
			handler : function(){
				new EditWindow().show();
			},
			scope : this
		}, '-', {
			text : '删除',
			tooltip : '删除',
			iconCls : 'icon-del',
			handler : this.remove,
			scope : this
		
		},'-', {
			text : '导出',
			tooltip : '导出到Excel',
			iconCls : 'icon-excel',
			handler : this.doExport,
			scope : this
		
		}]);
		
        this.bbar = new Ext.PagingToolbar({
			pageSize : 15,
			store : this.store,
			displayInfo : true,
			displayMsg : '显示第 {0} 到第 {1},共 {2} 条',
			emptyMsg : "没有可显示的记录"
		});
		
        PlansGridPanel.superclass.initComponent.call(this,{});  //必须  
        //....  
       
    },
    
    
    //3、实现对gridpanel事件的监听
	listeners : {
		"rowdblclick" : function(grid, rowNum, e) {
			var record = grid.store.getAt(rowNum);
			var win = new EditWindow(grid,"edit");
			win.show();
		}
	},
    
	
    //4、以下为根据具体业务需要自定义的扩展方法
	refresh : function() {
		this.store.removeAll();
		this.store.reload();
	},

	remove : function() {
		var selectedKeys = this.selModel.selections.keys;
		if(selectedKeys.length<1){
			Ext.MessageBox.alert('提示', '请选择要删除的记录');
			return;
		}
		//处理删除动作
		Ext.MessageBox.confirm('提示', '确定要删除选中的记录吗?', function(btn) {
			if (btn == "yes") {
				Ext.MessageBox.show({
					msg : '正在请求数据, 请稍侯',
					progressText : '正在请求数据',
					width : 300,
					wait : true,
					waitConfig : {
						interval : 200
					}
				});
				Ext.Ajax.request({
					url : rootPath+'/plans/plans_delete.action',
					params : {
						ids : selectedKeys
					},
					method : 'POST',
					success : function(response) {
						var r = Ext.decode(response.responseText);
						if (!r.success)
							Ext.Msg.alert("提示信息", "数据删除失败,由以下原因所致:<br/>" + (r.message));
						else {
							Ext.Msg.alert("提示信息", "成功删除数据!", function() {
								Ext.MessageBox.hide();
								this.refresh();
							}, this);
						}
					},
					scope : this
				});
			}
		}, this);
	},
	

	edit : function(){
		//var record = gridPanel.grid.getSelectionModel().getSelected();
		var selectedKeys = this.grid.selModel.selections.keys;
		if (!selectedKeys) {
			Ext.Msg.alert("提示", "请先选择要编辑的行!");
			return;
		}
	},
	
	doExport : function(){
		var panel = this; // 当前的panelGrid
		var selectid_str = "id";
		var data_grid = this.store;
		var form = queryForm.getForm();
		var win = new util.winexport.ExportWindow({
					searchform : form,//Ext.getCmp("mainPanel").queryForm.getForm(),
					selectid_str : selectid_str,
					export_url : rootPath
							+ "/agriculture/agriculture_exportExcel.action?SToken="+themis.commonjs.loginUser.token,
					data_grid : panel
				});
		win.show();
	}

});




/**
 * 与实体类关联的业务表单
 * @param {} _grid
 * @param {} _type
 */
PlansForm = function(_grid,_type) {
	this.grid = _grid;
	this.type = _type;
	PlansForm.superclass.constructor.call(this,{
		id:'id_plans_editform',
		//region : 'center',
		bodyStyle : 'padding:5px',
		items : [{
			layout : 'column',
			border : false,
			labelSeparator : ':',
			items : [{
				columnWidth : 1,
				layout : 'form',
				border : false,
				items : [{
					xtype : 'textfield',
					fieldLabel : '<font color="red">*</font>预案名称',
					labelStyle : "text-align: right;",
					allowBlank : false,
					maxLength : 100,
					name : 'plans.plansName',
					anchor : '95%'
				}, {
					xtype : 'hidden',
					name : 'plans.id'
				},{
					xtype : 'hidden',
					name : 'plans.orgId'
				},{
					xtype : 'hidden',
					name : 'plans.status'
				},{
					xtype : 'hidden',
					name : 'relationId'
				}]
			},{
				columnWidth : .5,
				layout : 'form',
				border : false,
				items : [{
					name : 'plans.orgName',
					fieldLabel : '<font color="red">*</font>所属单位',
					labelStyle : "text-align: right;",
					xtype : 'textfield',
					allowBlank : false,	
					maxLength : 60,
					anchor : '90%',
					value : themis.commonjs.org.orgName
				}]
			},{
				columnWidth : .5,
				layout : 'form',
				border : false,
				items : [{
							xtype : 'combo',
							name : "plans.plansType",
							fieldLabel : "<font color='red'>*</font>预案类型",
							labelStyle : "text-align: right;",
							allowBlank : false,
							blankText:'请输入类型信息!',
							maxLength : 50,
							displayField : 'plansType',
							mode : 'remote',
							anchor : '90%',
							store : new Ext.data.JsonStore({
								totalProperty : 'totalCount',
								root : "root",
								successProperty : "success",
								fields : ["plansType"],
								url : rootPath+ "/plans/plans_findByField.action?fieldName=plansType"
							}),
							selectOnFocus : true,
							editable : true,
							typeAhead : false,
							minChars : 1,
							// pageSize : 10,
							queryParam : 'plansType',
							triggerAction : 'all',
							loadingText : '加载中...'
						}]
			}, {
				columnWidth : .5,
				layout : 'form',
				border : false,
				items : [{
					name : 'plans.compileOrgName',
					fieldLabel : '编制单位',
					labelStyle : "text-align: right;",
					xtype : 'textfield',
					//allowBlank : false,	
					maxLength : 60,
					anchor : '90%'
					//value : themis.commonjs.org.orgName
				}]
			},{
				columnWidth : .5,
				layout : 'form',
				border : false,
				items : [{
					name : 'plans.issueOrgName',
					fieldLabel : '发布单位',
					labelStyle : "text-align: right;",
					xtype : 'textfield',
					//allowBlank : false,	
					maxLength : 60,
					anchor : '90%'
				}]
			},{
				columnWidth : .5,
				layout : 'form',
				border : false,
				items : [{
					xtype : 'datefield',
					name : 'plans.issueDate',
					//value: new Date(),
					format : 'Y-m-d',
					anchor : '90%',
					fieldLabel : '发布时间',
					labelStyle : "text-align: right;"
					//labelSeparator:'',
					//validator:function(value) {}
				}]
			},{
				columnWidth : .5,
				layout : 'form',
				border : false,
				disabled : false,
				items : [{
					xtype : 'datefield',
					//id:'releaseDate2',
					name : 'plans.recordDate',
					//value: new Date(),
					format : 'Y-m-d h:m',
					anchor : '90%',
					fieldLabel : '备案时间',
					labelStyle : "text-align: right;",
					//labelSeparator:'',
					disabled : true
				}]	
			},{
				columnWidth : .5,
				layout : 'form',
				border : false,
				items : [{				
					name : 'plans.recorder',
					xtype : 'textfield',
					fieldLabel : '<font color="red">*</font>报备人',
					labelStyle : "text-align: right;",
					allowBlank : false,
					maxLength : 50,
					anchor : '90%'
				}]
			},{
				columnWidth : .5,
				layout : 'form',
				border : false,
				items : [{
							xtype:"textfield",
							name : "status",
							fieldLabel : "预案状态",
							labelStyle : "text-align: right;",
							//allowBlank : false,
							blankText:'请输入信息类型!',
							maxLength : 50,
							anchor : '90%',
							disabled : true
							// pageSize : 10,
						}]
			},{
				columnWidth:1,
				layout:'form',
				border:false,
				items:[{
					//cls:'key',
					name:'plans.remark',
					xtype:'textarea',
					fieldLabel:'备注',
					labelStyle : "text-align: right;",
					anchor:'95%',
					height:120,
					maxLength : 2000
				}]
			}]
		}],
		listeners : {
			afterlayout  : function(form) {	//afterlayout
				if (this.grid != null && this.type!="add"){
					form.loadData();
				}
			}
		}
	});

};
Ext.extend(PlansForm, Ext.form.FormPanel, {
	//装载表单数据
	loadData : function() {
		//从grid加载数据
		var record = this.grid.getSelectionModel().getSelected();
		this.getForm().loadRecord(record);
		
		//对部分特殊字段进行处理
		var issueDate = record.get('plans.issueDate');
		var status = record.get('plans.status');
		//Date.parseDate(issueDate,"Y-m-d");
		issueDate = issueDate.substring(0,10);
		this.getForm().findField('plans.issueDate').setValue(issueDate);
		if(status=="0")
			this.getForm().findField('status').setValue("已保存");
		if(status=="1")
			this.getForm().findField('status').setValue("已备案");
	}

});



/**
 * 查询表单
 * @param {} _grid
 */
QueryForm = function(_grid) {
	this.grid = _grid;
	
	QueryForm.superclass.constructor.call(this, {
		id:'id_plans_queryform',
		// frame : true,
		border:false,
		bodyStyle : 'padding:2px',
		region : 'north',
		height : 52,
		title : '查询',
		collapsible : true,
		// collapsed: true,
		layout : 'column',
		items : [{
				columnWidth : .3,
				layout : 'form',
				border : false,
				labelWidth : 70,
				items : [{
					id : 'agriculture-queryform-title',
					cls : 'key',
					xtype : 'textfield',
					fieldLabel : '&nbsp;&nbsp;预案名称 ',
					name : 'plans.plansName',
					//allowBlank : false,
					//regex : /^[\u4e00-\u9fa5]{1,4}$/,
					//regexText : '联系人只能输入1-4个汉字',
					maxLength : 20,
					anchor : '90%'
				}]
			},{
			columnWidth : .3,
			layout : 'form',
			border : false,
			labelWidth : 55,
			items : [{
				xtype : 'datefield',
				id:'releaseDate1',
				name : 'plans.recordBeginTime',
				format : 'Y-m-d',
				anchor : '85%',
				fieldLabel : '报备时间',
				validator:function(value) {
					var compareDate = Ext.getCmp("releaseDate2").getRawValue();
					if(compareDate && value > compareDate) {
						return "开始时间不能够大于结束时间!";
					}
					Ext.getCmp("releaseDate2").clearInvalid();
					return true;
				}
			}]
		},{
			columnWidth : .3,
			layout : 'form',
			border : false,
			labelWidth : 45,
			items : [{
				xtype : 'datefield',
				id:'releaseDate2',
				name : 'plans.recordEndTime',
				//value: new Date(),
				format : 'Y-m-d',
				anchor : '85%',
				fieldLabel : '----',
				labelSeparator:'',
				validator:function(value) {
					var compareDate = Ext.getCmp("releaseDate1").getRawValue();
					if(compareDate && value < compareDate) {
						return "结束时间不能够小于开始时间!";
					}
					Ext.getCmp("releaseDate1").clearInvalid();
					return true;
				}
			}]
		}, {
			//columnWidth : .1,
			layout : 'form',
			border:false,
			items : [{
				xtype : 'button',
				text : '查询',
				handler:this.query.createDelegate(this, [])
			}]
		}]
	});

};
Ext.extend(QueryForm, Ext.form.FormPanel, {
	query : function(){
		var a = this.getForm().getValues();
		this.grid.store.baseParams = a;
		//this.grid.refresh();
		this.grid.store.load({
			params:{
				start: 0,
				limit: 15
			}
		});
	}
});





/**
 * 业务表单编辑窗口
 * @class EditWindow
 * @extends Ext.Window
 */
EditWindow = function(_grid,_type){
	//this.grid = _grid;
	//this.type = _type;
	this.form = new PlansForm(_grid,_type);
	this.tempid = themis.commonjs.loginUser.getTempRelaId();//
	
	EditWindow.superclass.constructor.call(this, {
		title : '窗口',
		layout : 'fit',
		plain : true,
		items : this.form,
		closeAction : 'hide',
		width : 600,
		height : 400,
		modal : true,
		resizable : false,
		buttons : [{
			text : '附件',
			handler : this.addFile,
			scope : this

		},{
			text : '保存',
			handler : this.save,//this.showTargetWindow,
			scope : this
		},{
			text : '报备',
			handler : this.send,//this.showTargetWindow,
			scope : this
		},{
			text : '取消',
			handler : this.hide.createDelegate(this, [])
		}],
		listeners:{
			beforerender:function(win){
				if(_grid){
					var record = _grid.getSelectionModel().getSelected();
					var status=record.get('plans.status');
					if(status== '1'){
						win.buttons[1].hide();
						win.buttons[2].hide();
					}
				}
			}
		}
	});
}
Ext.extend(EditWindow,Ext.Window, {
	addFile : function() {
		//alert(this.tempid);
		var id = this.form.getForm().findField("plans.id").getValue();
		var tmpid = this.tempid;
		if (id) {
			this.form.getForm().findField("relationId").setValue(id);
			tmpid = id;
		}
		HM.themis.FileUploadMgr.relationId = tmpid;
		HM.themis.FileUploadMgr.sort = "plans";
		HM.themis.FileUploadMgr.title = "上传附件";
		HM.themis.FileUploadMgr.show();
	},
		
	save : function(){
		var form = this.form.getForm();
		if (form.isValid()) {

			var url = rootPath+'/plans/plans_save.action';

			form.submit({
				waitMsg : '正在保存数据...',
				url : url,
				scope : this,
				method : 'POST',
				success : function(form1, action) {
					var responseArray = Ext.util.JSON.decode(action.response.responseText);
					if (responseArray && responseArray.success == true) {
						Ext.Msg.alert("保存成功!", "保存成功");
						var grid = Ext.getCmp("id_plans_gridpanel");
						grid.refresh();
						this.close();
					} else {
						Ext.MessageBox.alert("警告", responseArray ? responseArray.message : '保存失败');
					}

				}
			});
		}
	},
	
	send : function(){
		var form = this.form.getForm();
		if (form.isValid()) {

			var url = rootPath+'/plans/plans_send.action';

			form.submit({
				waitMsg : '正在保存数据...',
				url : url,
				scope : this,
				method : 'POST',
				success : function(form1, action) {
					var responseArray = Ext.util.JSON.decode(action.response.responseText);
					if (responseArray && responseArray.success == true) {
						Ext.Msg.alert("信息提示", "预案报送成功!");
						var grid = Ext.getCmp("id_plans_gridpanel");
						grid.refresh();
						this.close();
					} else {
						Ext.MessageBox.alert("警告", responseArray ? responseArray.message : '报送失败');
					}

				}
			});
		}
	},
	
	
	myRequest : function() {// 增加 or 修改方法
		var win = this;
		var myForm = win.getMyForm();
		if (!myForm.isValid()) {
			return;
		}
		win.getEl().mask('正在提交数据,请稍候...');
		myForm.submit({
					clientValidation : true,
					url : win.formUrl,
					method : "POST",
					success : function(form, action) {
						win.getEl().unmask();
						myAlert("操作成功");
						Ext.getCmp("disasterGridPanel").store.reload();
						win.hide();
						myForm = null;
					},
					failure : function(form, action) {
						win.getEl().unmask();
						if (action.failureType == Ext.form.Action.SERVER_INVALID) {
							myAlert("您的输入中有错误,请重新输入!", Ext.Msg.ERROR);
						} else {
							myAlert("访问服务器发生错误!", Ext.Msg.ERROR);
						}
						myForm = null;
					}
				});
	},
	getMyForm : function() {// 获取此window的form表单
		return this.items.get(0).getForm();
	},
	getMyButton : function() {// 获取此window的提交按钮
		return this.buttons[1];
	},

	setReadOnly : function(bool) {
		if (bool) {
			HM.themis.FileUploadMgr.viewFlag = true;
			this.buttons[1].hide();
			this.buttons[2].hide();
		} else {
			HM.themis.FileUploadMgr.viewFlag = false;
			this.buttons[1].show();
			this.buttons[2].show();
		}
	}

});




/**
 * 主界面
 * @class MainPanel
 * @extends Ext.Panel
 */
MainPanel = Ext.extend(Ext.Panel, {

	id : 'mainPanel',
	region:'center',
	autoScroll : true,
	layout : "border",
	message :"",

	//重写父类方法
	initComponent : function() {
		
		MainPanel.superclass.initComponent.call(this);
		
		this.grid = new PlansGridPanel();
		
		this.queryForm = new QueryForm(this.grid);
		
		this.add(this.queryForm);
		this.add(this.grid);
	}
});


二、struts对应的action:PlansAction.java
package com.ibeans.plans.web.action;


import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import com.ibeans.apportal.sdk.role.IRole;
import com.ibeans.export.IExport;
import com.ibeans.plans.domain.Plans;
import com.ibeans.plans.service.IPlansService;
import com.ibeans.themis.commons.Constants;
import com.ibeans.themis.commons.MessageConstants;
import com.ibeans.themis.commons.bean.LoginUserInfo;
import com.ibeans.themis.commons.exception.BaseDaoException;
import com.ibeans.themis.commons.exception.BaseServiceException;
import com.ibeans.themis.commons.util.ListRange;
import com.ibeans.themis.commons.web.action.BaseAction;

/**
 * 业务流程控制类
 * @author 
 *
 */
public class PlansAction extends BaseAction {
	private static final long serialVersionUID = 3849953321202091076L;
	private static final Logger logger = Logger.getLogger(PlansAction.class);
	private String id;
	private String[] ids;
	private Plans plans;
	private String exports;				//要导出的字段数组
	private IPlansService plansService;
	private IExport fwexportService;	//数据导出工具

	////////////////////////////////////////////////////////////////
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	
	public Plans getPlans() {
		return plans;
	}
	public void setPlans(Plans plans) {
		this.plans = plans;
	}
	
	public IPlansService getPlansService() {
		return plansService;
	}
	public void setPlansService(IPlansService plansService) {
		this.plansService = plansService;
	}
	
	public String[] getIds() {
		return ids;
	}
	public void setIds(String[] ids) {
		this.ids = ids;
	}
	
	public String getExports() {
		return exports;
	}
	public void setExports(String exports) {
		this.exports = exports;
	}
	public IExport getFwexportService() {
		return fwexportService;
	}
	public void setFwexportService(IExport fwexportService) {
		this.fwexportService = fwexportService;
	}
	////////////////////////////////////////////////////////////////////////
	/**
	 * 根据某个 字段查找
	 * */
	@SuppressWarnings("unchecked")
	public void findByField(){
		try{
			String fieldName=this.getRequest().getParameter("fieldName");//要查找的字段名字
			String fieldValue=this.getRequest().getParameter(fieldName);//模糊查时用
			List list = plansService.findByField(fieldName,fieldValue);
//			List list = extPage.getResultList();
			StringBuffer arrBuffer = new StringBuffer("[");
			for (int i = 0; i < list.size(); i++) {
				String value = (String) list.get(i);
				arrBuffer.append("{"+fieldName+":'" + value + "'},");
			}
			String arr = "";
			if (arrBuffer.length() > 1) {
				arr = arrBuffer.substring(0, arrBuffer.length() - 1) + "]";
			} else {
				arr = arrBuffer + "]";
			}
			JSONObject json = new JSONObject();
			json.put("root", arr);
//			json.put("totalCount", extPage.getTotalCount());
			this.getResponse().setContentType("text/json");
			this.getResponse().setCharacterEncoding("utf-8");
			PrintWriter out = this.getResponse().getWriter();
			out.print(json);
			out.close();
		}catch(Exception e){
			this.outJsonByErrorMsg("系统异常,请稍后再试!");
		}
	}

	/**
	 * 保存预案信息
	 */
	public void save() throws IllegalAccessException, InvocationTargetException{
		ListRange<Plans> formList = new ListRange<Plans>();
		String message = "";
		boolean result = false;
		
		Plans plans  = this.getPlans();
		LoginUserInfo user = this.getLoginUserInfo();
		try{
			plansService.saveOrUpdate(plans, user);
			result = true;
		}catch(Exception e){
			e.printStackTrace();
			message = MessageConstants.ACTION_SAVE_SERVICE_FAILURE;
			if (e.getCause() instanceof BaseDaoException){
				message = MessageConstants.ACTION_SAVE_DB_FAILURE;
			}
		}
		
		formList.setMessage(message);
		formList.setSuccess(result);
		this.outJson(formList);
	}
	
	/**
	 * 发送/报备预案信息
	 */
	public void send() throws IllegalAccessException, InvocationTargetException{
		ListRange<Plans> formList = new ListRange<Plans>();
		String message = "";
		boolean result = false;
		LoginUserInfo user = this.getLoginUserInfo();
		try{
			plansService.doSend(plans, user);
			result = true;
		}catch(Exception e){
			e.printStackTrace();
			message = MessageConstants.ACTION_SAVE_SERVICE_FAILURE;
			if (e.getCause() instanceof BaseDaoException){
				message = MessageConstants.ACTION_SAVE_DB_FAILURE;
			}
		}
		
		formList.setMessage(message);
		formList.setSuccess(result);
		this.outJson(formList);
	}
	
	public void edit(){
		
	}
	
	/**
	 * 删除预案信息
	 */
	public void delete(){
		ListRange<Plans> listRange = new ListRange<Plans>();
		//String[] ids = this.getRequest().getParameterValues("ids");
		boolean success = false;
		try{
			plansService.delete(ids);
			success = true;
		} catch (Exception e){
			e.printStackTrace();
			listRange.setMessage(e.getMessage());
		}
		listRange.setSuccess(success);
		this.outJson(listRange);
	}
	
	/**
	 * 根据id进行信息查询
	 */
	public void findById(){
		//取得用户信息
		//LoginUserInfo user = (LoginUserInfo)this.getRequest().getSession().getAttribute(Constants.SESSION_USER_INFO);
		String message ="";
		boolean result = false;
		Plans plans = null;
		try	{
			plans = plansService.findById(this.getId());
			result = true;
		} catch (BaseServiceException e1){
			e1.printStackTrace();
		}finally{
			JSONObject object = JSONObject.fromObject(plans, this.getJsonConfig());
			object.accumulate("message", message);
			object.accumulate("success", result);
			this.outJsonString(object.toString());
		}
	}
	
	/**
	 * 分页查询
	 */
	public void findPageList(){
		//1、初始化对象
		List<Plans> infos = new ArrayList<Plans>();
		Plans plans = this.getPlans();
		if(null == plans) plans = new Plans();
		
		//2、根据用户信息判断查询类型
		//LoginUserInfo user = (LoginUserInfo)this.getRequest().getSession().getAttribute(Constants.SESSION_USER_INFO);
		LoginUserInfo user = this.getLoginUserInfo();
		List<IRole> userRoles = user.getPersonRol();
		A:for(IRole rol : userRoles){
			if("js_fbzby".equals(rol.getRoleCode()) || "js_fbgly".equals(rol.getRoleCode())){
				plans.setQueryType("1");//0,预案单位查询;1,预案中心查询
				break A;
			}
		}
		if(null == plans.getQueryType() || "".equals(plans.getQueryType()))
			plans.setQueryType("0");
		if(null == plans.getOrgId() || "".equals(plans.getOrgId()))
			plans.setOrgId(user.getUserOrgId());
		
		//3、执行查询
		long totalSize = 0;
		try{
			infos = plansService.findPageByCriteria(plans, this.getStart(), this.getLimit(), this.getSort(), this.getDir());
			totalSize = plansService.findCountByCriteria(plans);
		} catch (BaseServiceException e1){
			e1.printStackTrace();
		}
		
		//4、返回查询结果
		this.outJsonByMsg(infos,totalSize,null,Constants.DATETIME_FORMAT_NO_SECEND);
	}
	

	
	/**
	 * 分页查询发布功能信息列表
	 */
	/*public void findPageList4Release(){
		//取得用户信息
		//LoginUserInfo user = (LoginUserInfo)this.getRequest().getSession().getAttribute(Constants.SESSION_USER_INFO);
		List<Plans> infos = new ArrayList<Plans>();
		AgricultureInfo info = this.getModelByForm();
		long totalSize = 0;
		try{
			String hql = "from Plans info where info.status in ('"+DictContants.WEATHER_INFO_STATUS_IS_AUDIT+"','"+DictContants.WEATHER_INFO_STATUS_IS_RELEASE+"')";
			infos = plansService.findPageListByHql(hql,this.getStart(), this.getLimit(), this.getSort(), this.getDir());
			totalSize = plansService.getListCountByHql(hql, null);
		} catch (BaseServiceException e1){
			e1.printStackTrace();
		}
		
		this.outJsonByMsg(infos,totalSize,null,Constants.DATETIME_FORMAT_NO_SECEND);
		JSONArray objs = JSONArray.fromObject(infos, this.getJsonConfig());
		this.outJson(objs);
	}*/

	
	
	
	
	
	/**
	 * 导出到excel
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public void exportExcel() throws Exception{
		LoginUserInfo userInfo = this.getLoginUserInfo();
		//1.取得查询条件参数
		Plans plans = this.getPlans();
		
		//2.取得要导出的记录列表
		List list = new ArrayList<Plans>();
		if(ids!=null && !"".equals(ids)){
			list = plansService.findByIds(ids);
		}else{
			list = plansService.findPageByCriteria(plans, 0, 10000, this.getSort(), this.getDir());//设置一次性大最导出数量为10000
		}
		
		//3.对要导出的列表进行数据字典转换
		list = plansService.getFormatedList(list);
		
		//4.导出列表到excel
		Map map = this.getExportMap(this.getExports());
		this.fwexportService.setSortMap(map);
		this.fwexportService.export(list);
		//5.
		this.fwexportService.output(this.getResponse(), "预案备案信息");
	}
	
	@SuppressWarnings("unchecked")
	private Map getExportMap(String exports) {
		Map map = new LinkedHashMap();
		String[] export = exports.split(",");
		for (int i = 0; i < export.length; i++) {
			String[] tempexport = export[i].split("-");
			map.put(tempexport[0], tempexport[1]);
		}
		return map;

	}
	
}



三、实体类:Plans.java
package com.ibeans.plans.domain;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.hibernate.annotations.GenericGenerator;

import com.ibeans.themis.persistence.domain.MySysFile;

@Entity
@Table(name="hm_plans")
public class Plans {

	private String id;
	private String plansName;		//预案名称
	private String orgId;			//所属单位ID
	private String orgName;			//所属单位名称
	private String plansType;		//预案类型
	private String compileOrgName;	//编制单位
	private String issueOrgName;	//发布单位
	private String recorder;		//报备人
	private Date issueDate;			//发布时间
	private Date recordDate;		//备案时间
	private Date updateDate;		//更新时间
	private String status;			//预案状态
	private String remark;			//备注
	private String isDelete;		//是否删除
	
	//
	private String queryType;		//查询类型(0,预案单位查询;1,预警中心查询)
	private String relationId;		//关联的附件id
	private List<MySysFile> files = new ArrayList<MySysFile>();//关联的附件
	private String recordBeginTime;
	private String recordEndTime;
	//getters and setters=============================================
	@Id
	@GeneratedValue(generator="system-uuid")
	@GenericGenerator(name="system-uuid",strategy="uuid")
	public String getId() {
		
		return "".equals(id) ? null : id;
	}
	public void setId(String id) {
		this.id = id;
	}


	@Column(name="plans_name")
	public String getPlansName() {
		return plansName;
	}
	public void setPlansName(String plansName) {
		this.plansName = plansName;
	}


	@Column(name="org_id")
	public String getOrgId() {
		return orgId;
	}
	public void setOrgId(String orgId) {
		this.orgId = orgId;
	}


	@Column(name="org_name")
	public String getOrgName() {
		return orgName;
	}
	public void setOrgName(String orgName) {
		this.orgName = orgName;
	}


	@Column(name="plans_type")
	public String getPlansType() {
		return plansType;
	}
	public void setPlansType(String plansType) {
		this.plansType = plansType;
	}


	@Column(name="compile_org_name")
	public String getCompileOrgName() {
		return compileOrgName;
	}
	public void setCompileOrgName(String compileOrgName) {
		this.compileOrgName = compileOrgName;
	}


	@Column(name="issue_org_name")
	public String getIssueOrgName() {
		return issueOrgName;
	}
	public void setIssueOrgName(String issueOrgName) {
		this.issueOrgName = issueOrgName;
	}


	@Column(name="issue_date")
	public Date getIssueDate() {
		return issueDate;
	}
	public void setIssueDate(Date issueDate) {
		this.issueDate = issueDate;
	}


	@Column(name="record_date")
	public Date getRecordDate() {
		return recordDate;
	}
	public void setRecordDate(Date recordDate) {
		this.recordDate = recordDate;
	}


	@Column(name="update_date")
	public Date getUpdateDate() {
		return updateDate;
	}
	public void setUpdateDate(Date updateDate) {
		this.updateDate = updateDate;
	}


	@Column(name="status")
	public String getStatus() {
		return status;
	}
	public void setStatus(String status) {
		this.status = status;
	}


	@Column(name="remark")
	public String getRemark() {
		return remark;
	}
	public void setRemark(String remark) {
		this.remark = remark;
	}


	@Column(name="is_delete")
	public String getIsDelete() {
		return isDelete;
	}
	public void setIsDelete(String isDelete) {
		this.isDelete = isDelete;
	}
	
	
	@Column(name="recorder")
	public String getRecorder() {
		return recorder;
	}
	public void setRecorder(String recorder) {
		this.recorder = recorder;
	}
	
	@Transient
	public String getRelationId() {
		return relationId;
	}
	public void setRelationId(String relationId) {
		this.relationId = relationId;
	}
	
	@Transient
	public List<MySysFile> getFiles() {
		return files;
	}
	public void setFiles(List<MySysFile> files) {
		this.files = files;
	}
	
	@Transient
	public String getQueryType() {
		return queryType;
	}
	public void setQueryType(String queryType) {
		this.queryType = queryType;
	}
	
	@Transient
	public String getRecordBeginTime() {
		return recordBeginTime;
	}
	public void setRecordBeginTime(String recordBeginTime) {
		this.recordBeginTime = recordBeginTime;
	}
	
	@Transient
	public String getRecordEndTime() {
		return recordEndTime;
	}
	public void setRecordEndTime(String recordEndTime) {
		this.recordEndTime = recordEndTime;
	}
	
	
}

你可能感兴趣的:(ExtJs)