Extjs--后台数据传递解析

Extjs

Ext.BLANK_IMAGE_URL='../extsrc/resources/images/default/s.gif';
Ext.lib.Ajax.defaultPostHeader += ";charset=utf-8";
Ext.onReady(function(){
    Ext.QuickTips.init();
    //Ext.form.Field.prototype.msgTarget = 'side';
    var globalURL = '../control/IndexMajor?act=showMajor'; 

    //  store
    var store = new Ext.data.Store({      
        proxy: new Ext.data.ScriptTagProxy({//注意后台必须使用callback参数进行包装
            url: globalURL
        }), 
		reader : new Ext.data.JsonReader({
							totalProperty : 'totalCount',
							root : 'root'
						}, [{
								name : 'majorId'
							}, {
								name : 'majorName'
							}, {
								name : 'majorCode'
							}, {
								name : 'majorUseFlag'
							}																
			])
        //sortInfo:{field:'majorId', direction:'ASC'}
    });
    // start limit
    store.load();
    
    //	cm 
    var cm = new Ext.grid.ColumnModel([{
           id:'majorId',
           header: "专业序号",
           width:200,
           dataIndex: 'majorId'
           
        },{
        	id:'majorName',
            header: "专业名称",
            width:200,
            dataIndex: 'majorName'
           
     //      ,renderer:sourceRenderer
           
        },{
        	id:'majorCode',
           header: "专业编码",
           width:200,
           dataIndex: 'majorCode'
           
  //         ,renderer:targetRenderer
           
        },{
            id:'majorUseFlag',
            header: "使用标志",
            width:100,
            dataIndex: 'majorUseFlag'
   //         ,renderer:exectimeRenderer
            
         }
    ]);
   	cm.defaultSortable = true; 
   


	var newrecord = Ext.data.Record.create([
		
			{ 
				name:'majorId',
				type:'string'
			},	{
				name : 'majorName',
				type : 'string'
			}, 	{
				name : 'majorCode',
				type : 'string'
			},{
				name : 'majorUseFlag',
				type : 'string'
			},{
				name : 'flag',
				type : 'string'
			}
	]);
	
		
	
	function doadd(){
		var newrrecord = new newrecord({
					
					majorId:'',
					majorName : '',
					majorCode : '',
					majorUseFlag:'',
					flag: '1'

				})
		grid.stopEditing();
		store.insert(0, newrrecord);
		
	}
	
	function dosave() {
		var m = grid.store.getModifiedRecords();
		var jsonData = '[';
		for (var i = 0; i < m.length; i++) { // m表示被修改的行
			if(m[i].get('majorId')==''){
				Ext.Msg.alert('信息提示', '专业序号不能为空!');
				return false;
			}
			if(m[i].get('majorName')==''){
				Ext.Msg.alert('信息提示', '专业名称不能为空!');
				return false;
			}
			if(m[i].get('majorCode')==''){
				Ext.Msg.alert('信息提示', '专业编码不能为空!');
				return false;
			}
			if(m[i].get('majorUseFlag')==''){
				Ext.Msg.alert('信息提示', '使用标志不能为空!');
				return false;
			}
			var n=store.getCount();
		
			
			jsonData = jsonData + Ext.util.JSON.encode(m[i].data) + ',';
		}
		jsonData += ']';
		if (jsonData == '[]') {
			Ext.Msg.alert('信息提示', '没有发现保存项,请确认有保存项!');
			return false;
		}

		Ext.Msg.confirm('信息', '确定要保存所选项吗?', function(btn) {
			if (btn == 'yes') {
				Ext.MessageBox.wait("正在保存", "请稍候...");
					Ext.Ajax.request({
				   	url : '../control/IndexMajor?act=saveMajor',
				   	params : {
				       jsonData : jsonData				       
				   	},
				   	method: 'POST',
			       	success: function (request ) {
			            var message = request.responseText;								
						var resp=Ext.util.JSON.decode(request.responseText);
						if(resp.success == 'fail'){
							Ext.Msg.alert('信息','<center>保存项保存失败!<p>'+ resp.Info+'</center>');
						}
						else{
							Ext.Msg.alert('信息','保存项保存成功!');
							store.each(function(record) {
								record.commit();
							})
							loadF = 0;
							selectedrecord = null;							
							grid.getView().refresh();
							saved=true;	
							store.reload();
							renderGrid();
						}  
			       	},			
				   	failure: function ( result, request) { 
					        Ext.Msg.alert('错误','保存时出现未知错误.');  
				   	} 
				  });
		
			}
		})

	}

	
	function dodelete(){
		Ext.MessageBox.confirm('确认删除', '你真的要删除所选行记录吗?', function(btn) {
					if (btn == 'yes') {
						Ext.MessageBox.wait("正在删除", "请稍候...");
						var m = grid.getSelections();			        						
						var majorIds='';
			            for(var i=0;i<m.length-1;i+=1){
			             majorIds+=m[i].get('majorId')+','; 
			            }	
			             pros+=m[m.length-1].get('protocol');
				Ext.Ajax.request({
				   	url : '../control/IndexMajor?act=deleteMajor',
				   	params : {
				       majorIds : majorIds
				   	},
				   	method: 'POST',
			       	success: function (request ) {
						var resp=Ext.util.JSON.decode(request.responseText);
						if(resp.success == 'fail'){
							Ext.Msg.alert('信息','<center>记录删除失败!<p>'+ resp.Info+'</center>');
						}
						else{
							Ext.Msg.alert('提示', '记录删除成功!');
							store.reload();
							grid.getView().refresh();
							store.commitChanges();
						}
			       	},			
				   	failure: function ( result, request) { 
					        Ext.Msg.alert('错误','删除时出现未知错误.'); 
				   	} 
				  });
				}
			})
	}
	
	
  
    
    //	tbar
    var tbar= [
	   		{text:'查询',width:100,iconCls:'search',handler : dosearch},' ','-',
            {text:'新增',width:100,iconCls:'user_add',handler : doadd},' ','-',
			{text:'保存',width:100,iconCls:'save',handler : dosave},' ','-',
			{text:'删除',width:100,iconCls:'user_delete',handler : dodelete}	
			];
    // bbar
	var bbar = new Ext.PagingToolbar({
				pageSize : 30,
				store : store,
				displayInfo : true,
				displayMsg : '共有 {2} 条记录.当前显示 {0} - {1}条记录.',
				emptyMsg : "没有数据"
			});
    
    store.load({params : {start : 0,limit : 30}});
    
    function renderGrid() {
		store.load({
					params : {
						start : 0,
						limit : 30
					}
				});
	}
    
    //	grid 
    var grid = new Ext.grid.EditorGridPanel({
    	id:'grid',
        store: store,
        cm: cm,
        height:Ext.getBody().getComputedHeight()-20,
        //title:'任务管理',
        frame:true,
      //  plugins:checkColumn,
        clicksToEdit:1,
        sm: new Ext.grid.RowSelectionModel({singleSelect:false}),
        bbar: bbar,
        tbar: tbar,
     	renderer:renderGrid()
   	});
    
    //	viewport
    var viewport =  new Ext.Viewport({
	   // region:'center', 
	    layout:'fit',   
	    split:true,   
	    collapsible: true,   
	    margins:'0 0 20 0',   
	    frame:true,   
	    items:[{autoScroll:false,items:[grid]}]
    });
    
    function dosearch() {
		
		store.load({
					params : {
						start : 0,
						limit : 30
					}
		});
		
		grid.reconfigure(store, cm);
		grid.getBottomToolbar().render();// 重新渲染询问工具栏
		grid.view.startCollapsed = false;
		
	}
});





handler  


handler 要继承  org.apache.struts.action.Action   

否则报错:

Bean named '/login'must be of type [org.apache.struts.action.Action], but was actually of type[action.LoginAction]

package com.econ.assessment;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.json.JSONArray;
import org.json.JSONObject;

import com.econ.assessment.bean.IndexdbConstants;
import com.econ.control.AbstractHandler;
import com.econ.control.BaseWebKeys;

/**
 * 专业major管理
 * @creator BEN by 2013.1.4
 * @author JBL
 *
 */
public class IndexMajorHandler extends AbstractHandler{

	private String userAcct; //当前登录用户账号
	private String userGrpId; //当前登录用户所属用户组Id
	/**
	 * @param args
	 */
	private IndexMajorDAO madao=new IndexMajorDAO();

	@Override
	public String process(HttpServletRequest request, ActionForm form,
			HttpServletResponse response) {
		// TODO Auto-generated method stub
		userAcct = request.getSession().getAttribute(
				BaseWebKeys.SAK_SYS_USR_ACCT).toString();
		userGrpId = request.getSession().getAttribute(
				BaseWebKeys.SAK_SYS_USR_GRP_ID).toString();
    	
		String result = "IndexMajorShow";
		String action = request.getParameter("act");
		if("showMajor".equals(action))//显示专业
			result = showMajor(request,response);
		if("createMajor".equals(action))//创建专业
			result = createMajor(request,response);
		if("editMajor".equals(action))//修改专业
			result = editMajor(request,response);
		if("deleteMajor".equals(action))//删除专业
			result = deleteMajor(request,response);		
		if("expireMajor".equals(action))//专业过期
			result = expireMajor(request,response);	
		if("saveMajor".equals(action))//保存修改
			result = saveMajor(request,response);	
		return result;
	}

	/**
	 * 查询展示
	 * @param request
	 * @param response
	 * @return
	 */
	public String showMajor(HttpServletRequest request,HttpServletResponse response){
		String jsonStr = null;
		String startStr = request.getParameter("start");
		String limitStr = request.getParameter("limit");
		
		String majorId = (request.getParameter("searchMajorId")!= null? request.getParameter("searchMajorId"):"");
		String majorName = this.getRequestIsNull(request, "searchMajorName","utf-8");
		String majorCode = (request.getParameter("searchMajorCode")!= null? request.getParameter("searchMajorCode"):"");
		String majorUseFlag = (request.getParameter("searchMajorUseFlag")!= null? request.getParameter("searchMajorUseFlag"):"");
		String majorHistoryFalg = (request.getParameter("historyFlag")!= null? request.getParameter("historyFlag"):"");
		//System.out.println("majorname :"+majorName);
		//int start = 0;
		//int limit = 30;
		int start = Integer.parseInt(startStr);;
		int limit = Integer.parseInt(limitStr);;
		
		
		String cb = request.getParameter("callback");
		jsonStr = cb+madao.getMajor(start, limit, majorId, majorName, majorCode,majorUseFlag,majorHistoryFalg);
		System.out.println(jsonStr);
		request.setAttribute("jsonData", jsonStr);
		
		return "extDataPage";
	}
	
	/**
	 * 在创建专业的同时,在历史库中新建记录,添加专业开始时间
	 * @param request
	 * @param response
	 * @return
	 */
	public String createMajor(HttpServletRequest request,HttpServletResponse response){
		
		return "extDataPage";
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public String editMajor(HttpServletRequest request,HttpServletResponse response){
		
		return "extDataPage";
	}
	
	/**
	 * 软删除,只将use_flag置位。同时在历史库打上过期标记
	 * @param request
	 * @param response
	 * @return
	 */
	public String deleteMajor(HttpServletRequest request,HttpServletResponse response){
		String jsonData = "";    	
		try {
			String majorCodes=request.getParameter("majorCodes");
			String majorHistoryFalg = request.getParameter("historyFlag");
			String[] majorCodeArr=majorCodes.split(",");
			jsonData=madao.deleteMajor(majorCodeArr,majorHistoryFalg);							
		} catch (Exception e) {			
			e.printStackTrace();
			jsonData=e.getMessage();
		}    	
		if (!jsonData.equalsIgnoreCase("")) { 
			jsonData = "{success:'fail',Info:'" + jsonData + "'}";
		} else {
			jsonData = "{success:'success',Info:'保存成功!'}";
		}
		request.setAttribute("jsonData", jsonData);
		
		return "extDataPage";
	}
	
	/**
	 * 过期专业,需要更新历史库
	 * @param request
	 * @param response
	 * @return
	 */
	public String expireMajor(HttpServletRequest request,HttpServletResponse response){
		
		return "extDataPage";
	}
	
	/**
	 * 保存修改
	 * @param request
	 * @param response
	 * @return
	 */
	public String saveMajor(HttpServletRequest request,HttpServletResponse response){
		String jsonData = "";    	
    	List<String> addSqls=new ArrayList<String>();
    	List<String> updateSqls=new ArrayList<String>();
    	
    	try {
			String data = URLDecoder.decode(request.getParameter("jsonData"),"utf-8");
			JSONArray jb = new JSONArray(data);
			for(int i=0;i<jb.length();i++){
				JSONObject jobj = jb.getJSONObject(i);
				String majorId= jobj.getString("majorId");
				String majorName = jobj.getString("majorName");
				//String majorCode = jobj.getString("majorCode");
				String majorUseFlag = jobj.getString("majorUseFlag");
				String flag = jobj.getString("flag");
				if(flag.equals("1")){
					//新建的时候“使用标志”默认为1
					String param=majorId+","+majorName+","+IndexdbConstants.bm_use_flag_use;
					addSqls.add(param);
				}else{
					String param=majorId+","+majorName+","+majorUseFlag;
					updateSqls.add(param);
				}
			}
			jsonData = madao.addMajor(addSqls);
			jsonData += madao.updateMajor(updateSqls);
		} catch (Exception e) {
			e.printStackTrace();
			jsonData=e.getMessage();
		}
		if (!jsonData.equalsIgnoreCase("")) { 
			jsonData = "{success:'fail',Info:'" + jsonData + "'}";
		} else {
			jsonData = "{success:'success',Info:'保存成功!'}";
		}
		request.setAttribute("jsonData", jsonData);
		return "extDataPage";	
	}
}





dao

package com.econ.assessment;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.econ.assessment.bean.IndexdbConstants;
import com.econ.control.AbstractDAO;

/**
 * 专业major管理DAO类
 * @creator BEN by 2013.1.4
 * @author JBL
 *
 */
public class IndexMajorDAO extends AbstractDAO{
	public void getDBConn() {
		this.getConn();
	}
	public void releaseDBConn() {
		this.closeAll();
	}
	
	//修改考核专业
	public String updateMajor(List<String> paramList){
		String ret="";
		int length = paramList.size();
		if(length<1){
			return ret;
		}
		String sql = "update sysadmin.T_INDEX_MAJOR set ORDER_NO=? "+", "+ "NAME=? "+", "+"USE_FLAG=? where CODE=?";
		try {
			this.getConn();
			conn.setAutoCommit(false);
			pStmt = conn.prepareStatement(sql);
			for(int i=0;i<length;i++){				
				String[] params = paramList.get(i).split(",");
				pStmt.setString(1, params[0]);
				pStmt.setString(2, params[1]);
				pStmt.setString(3, params[3]);
				pStmt.setString(4, params[2]);				
				pStmt.addBatch();
			}	
			pStmt.executeBatch();
			conn.commit();
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}finally {
				this.closeAll();
			}
			ret = e.getMessage();
		}
		return ret;
	}
	
	
	//添加考核专业
	public String addMajor(List<String> paramList){
		String ret="";
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat();
		sdf.applyPattern("yyyy-MM-dd");
		//System.out.println(sdf.format(date));
		String stime = sdf.format(date);
		String type = "1";
		String code = "";
		int length = paramList.size();
		if(length<1){
			return ret;
		}
		String codeNoSql = "select sysadmin.SEQ_T_INDEX_MAJOR.NEXTVAL from DUAL";
		String sql="insert into sysadmin.T_INDEX_MAJOR (ORDER_NO,NAME,CODE,USE_FLAG)values(?,?,?,?)";	
		String cycleSql = "insert into sysadmin.T_INDEX_CYCLE (PID,STIME,TYPE,CODE,FLAG)values(sysadmin.SEQ_T_INDEX_CYCLE.nextval,"+"to_date('"+stime+"','yyyy-mm-dd'),?,?,?)";
		System.out.println("#######"+cycleSql);
		try {
			this.getConn();
			conn.setAutoCommit(false);
			
			
			
			pStmt = conn.prepareStatement(sql);
			for(int i=0;i<length;i++)
			{
				stmt = conn.createStatement();
				rs = stmt.executeQuery(codeNoSql);
				if(rs.next()){
					code = "MAJOR"+rs.getString("NEXTVAL");
				}else{
					return ret;
				}
				
				
				String[] params = paramList.get(i).split(",");
				pStmt.setString(1, params[0]);
				pStmt.setString(2, params[1]);
				pStmt.setString(3, code);
				pStmt.setString(4, params[2]);
				pStmt.executeUpdate();	
				
				pStmt = conn.prepareStatement(cycleSql);
				//pStmt.setString(1, stime);
				pStmt.setString(1, type);
				pStmt.setString(2, code);
				pStmt.setString(3, params[2]);
				pStmt.executeUpdate();	
			}
			conn.commit();
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			ret="数据插入失败";
		}finally{
			this.closeAll();
		}
		
		
		return ret;
	}
	
	//查询考核专业
	public String getMajor(int start, int limit, String majorId, String majorName, String majorCode, String majorUseFlag,String majorHistoryFalg) {
		StringBuffer sb = new StringBuffer();
		int recordTotal = 0;
		this.getConn();
		String str="";
		String etime ="";
		String stime="";
		int seatchFalg;
		if(majorHistoryFalg != null && majorHistoryFalg.equals("mark") ){
			seatchFalg = IndexdbConstants.bm_use_flag_unuse;
		}else{
			seatchFalg = IndexdbConstants.bm_use_flag_use;
		}
		
		String sqlTotal = "select count(*) from sysadmin.T_INDEX_MAJOR m,sysadmin.T_INDEX_CYCLE c where m.USE_FLAG = "+seatchFalg+" and m.CODE = c.CODE";
		//                select * from (select t1.*, rownum r from (select m.order_no,m.name,m.code,m.use_flag,c.stime,c.etime from sysadmin.T_INDEX_MAJOR m,sysadmin.T_INDEX_CYCLE c where m.USE_FLAG = 1 and c.CODE = m.CODE order by m.ORDER_NO) t1 where rownum<31) where r>0
		String sqlShow = "select * from (select t1.*,rownum r from (select m.order_no,m.name,m.code,m.use_flag,c.stime,c.etime from sysadmin.T_INDEX_MAJOR m,sysadmin.T_INDEX_CYCLE c where m.USE_FLAG = "+seatchFalg+" and m.CODE = c.CODE";
		int finish = start + limit + 1;	
		if(majorId!=null&&!majorId.equals("")){
			str+=" and m.ORDER_NO like'%"+majorId+"%'";
		}
		if(majorName!=null&&!majorName.equals("")){
			str+=" and m.NAME like'%"+majorName+"%'";
		}
		if(majorCode!=null&&!majorCode.equals("")){
			str+=" and m.CODE like'%"+majorCode+"%'";
		}
		if(majorUseFlag!=null&&!majorUseFlag.equals("")){
			str+=" and m.USE_FLAG like'%"+majorUseFlag+"%'";
		}
	
		sqlTotal+=str;
		sqlShow = sqlShow  +str+ " order by ORDER_NO) t1 where rownum<"
				+ finish + ") where r>" + start ;
		try {
			System.out.println(sqlShow);
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sqlTotal);
			while (rs != null && rs.next()) {
				recordTotal = rs.getInt(1);
			}
			sb.append("({totalCount:" + recordTotal + ",root:[");
			rs = stmt.executeQuery(sqlShow);
			while (rs.next()) {
				sb.append("{majorId:'" + rs.getString("ORDER_NO") + "',");
				sb.append("majorName:'" + rs.getString("NAME") + "',");
				sb.append("majorCode:'" + rs.getString("CODE") + "',");
				sb.append("majorUseFlag:'" + rs.getString("USE_FLAG") + "',");
				stime = rs.getString("STIME");
				etime = rs.getString("ETIME");
				sb.append("majorStime:'" + stime.substring(0, 10) + "',");
				if(etime == null){
					etime = "正在使用";
					sb.append("majorEtime:'" + etime + "'},");
				}else{
					//etime.substring(0, 10);
					sb.append("majorEtime:'" + etime.substring(0, 10) + "'},");
				}
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			this.closeAll();
		}
		if ( sb.length()>0 && sb.lastIndexOf(",") == sb.length() - 1) {
			sb = sb.deleteCharAt(sb.length() - 1);
		}
		sb.append("]})");
		return sb.toString();
	}
	
	
	//删除  软删除,只将use_flag置位。同时在历史库打上过期标记
	public String deleteMajor(String[] majorCodeArr,String majorHistoryFalg){
		
		String ret="";
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat();
		sdf.applyPattern("yyyy-MM-dd");
		String etime = sdf.format(date);
		int delFalg;
		String cycleSql;
		if(majorHistoryFalg != null && majorHistoryFalg.equals("mark")){
			delFalg = IndexdbConstants.bm_use_flag_use;
			cycleSql ="update sysadmin.T_INDEX_CYCLE set FLAG = "+delFalg+",ETIME = to_date('','yyyy-mm-dd') where CODE =?";
		}else{
			delFalg = IndexdbConstants.bm_use_flag_unuse;
			cycleSql = "update sysadmin.T_INDEX_CYCLE set FLAG = "+delFalg+",ETIME = to_date('"+etime+"','yyyy-mm-dd') where CODE =?";
		}
		String sql = "update sysadmin.T_INDEX_MAJOR set USE_FLAG = "+delFalg+"where CODE =?";
		//                 update sysadmin.T_INDEX_CYCLE set FLAG = 0, ETIME = to_date('2012-12-12','yyyy-mm-dd') where sysadmin.T_INDEX_CYCLE.CODE ='Major1011';
		
		
		
		
		try {
			this.getConn();
			conn.setAutoCommit(false);
			for(int i=0;i<majorCodeArr.length;i++){
				pStmt = conn.prepareStatement(sql);						
				pStmt.setString(1, majorCodeArr[i]);
				pStmt.executeUpdate();
				pStmt = conn.prepareStatement(cycleSql);						
				pStmt.setString(1, majorCodeArr[i]);
				pStmt.executeUpdate();
				
			}
			conn.commit();
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
				ret=e.getMessage();
			}
		}finally{
			this.closeAll();
		}
		
		return ret;
	}
		

}






asdasd

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值