查询下拉框的通用方法

前台采用EXTJS:

1、界面

var ReconDataImport_cmdUpload='/settBusi/uploadAction.do?METHOD=doUpload';
var ReconDataImport_cmdReturn='/settBusi/uploadAction.do?METHOD=preUpload';
var ReconDataImport_cmdReconData='/settBusi/uploadAction.do?METHOD=doBatch';
var ReconDataImport_cmdDownload='/settBusi/uploadAction.do?METHOD=doDownload';
 
 var filename = '';//文件名
 var filepath = '';//文件路径
 var resultNameSessionId = '';
 var sett_type = '';
 var workerSessionId = '';
 
Ext.define('sett.business.ReconDataImport', {
    extend: 'Ext.ux.desktop.Module',
    scope: this,
    
    requires: [
            'Ext.util.Format',
            'Ext.grid.Panel',
            'Ext.grid.RowNumberer',
            'Ext.Window',
            'Ext.form.*',
            'Ext.data.*'
    ],

    id:'imports',

    init : function(){
        this.launcher = {
            text: '合作方结算数据导入',
            iconCls:'cart_put',       
            handler : this.createWindow,
            scope: this
        };
    },
    createWindow : function(){
        
        var desktop = this.app.getDesktop();
        
        var win = desktop.getWindow('imports');
        if(!win){
            win = desktop.createWindow({
                id: 'imports',
                title:'合作方结算数据导入',
                //border:false,
                forceFit:true,
                layout:'border',
                maximized:true,
                iconCls:'cart_put',     
                animCollapse:false,
                constrainHeader:true,
                items:[
                  Ext.create('Ext.form.Panel', {
                      region:'center',
                     // border:false,
                      frame: true,
                      title:'结算数据导入',
                      width : 1200,
                        height : 590,
                      bodyPadding: 5,
                      width:800,
                      height:600,
                      maximized: true,
                      collapsible: true,
                      id:'importsform',
                          fieldDefaults: {
                              labelAlign: 'left',
                              labelWidth: 85,
                              msgTarget: 'side'
                            },
                            
                    items:[{
                            id:'ReconDataImport_bill_month',
                            name: 'bill_month',
                            fieldLabel : '账务月',
                            triggerAction:'all',
                            displayField:'name',
                              xtype : 'combo',
                              store: monthStore,
                              //queryMode:'local',
                              emptyText:'-请选择-',
                              valueField:'code',
                              allowBlank : false,
                            msgTarget : 'side',
                            blankText : '账务月不允许为空',
                            autoFitErrors : false
                         },{
                             id:'ReconDataImport_sett_obj_code',
                             name: 'sett_obj_code',
                               fieldLabel : '合作商',
                               triggerAction:'all',
                               displayField:'name',
                                 xtype : 'combo',
                                 store: partnerStore,
                                 emptyText:'-请选择-',
                                 allowBlank : false,
                            msgTarget : 'side',
                            blankText : '合作商不允许为空',
                            autoFitErrors : false,
                             flex: 1
                          },{
                             xtype:'fieldcontainer',
                             fieldLabel : '入库记录数',
                             layout:{
                                 type:'hbox',
                                 align:'middle'
                             },
                         items:[{id:'ReconDataImport_recodeNum',   
                                 name: 'recodeNum',
                                    xtype : 'textfield',
                                    inputId:'ReconDataImport_recodeNumId',
                                    allowBlank : false,
                                msgTarget : 'side',
                                blankText : '入库记录数不允许为空',
                                autoFitErrors : false,
                                labelWidth:85,
                                    width:150
                              },{
                                    forId:'ReconDataImport_recodeNumId',
                                    xtype:'label',
                                    text:'(最大值为2000)'
                              }]
                          },{
                                xtype : 'filefield',
                                id : 'ReconDataImport_upfile',
                                name: 'upfile',
                                allowBlank : false,
                            msgTarget : 'side',
                            blankText : '上传文件不允许为空',
                            autoFitErrors : false,
                                labelWidth:85,
                                width:305,
                                fieldLabel:'上传文件',
                                buttonText :'选择文件'
                          },{
                            xtype : 'textfield',
                            id:'ReconDataImport_comment',
                            name:'remark',
                            labelWidth:85,
                                width:500,
                                 fieldLabel:'备注'
                               },{
                            fieldLabel:'<b>上传格式要求    </b>',
                            labelWidth:100,
                            labelSeparator:':',
                            width:750,
                               xtype : 'displayfield',
                               value : 'Excel格式:账务月,业务区代码,业务区名称,套餐代码,套餐名称,本月应结数。其中第一行为标题,账务月格式为:YYYYMM,2011年5月为:201105,所有列不能为空。目前支持Excel2003和Excel2007 、Excel2010'
                         }
                    ],
                    padding:'5 40 300 0',
                    buttons:[{
                        resbtn:'',
                        id:'uploadbtn',
                        xtype:'button',
                        height:25,
                        width:100,
                           text:'上传文件',
                           handler:function(){
                               var ReconDataImportForm=Ext.getCmp("importsform").getForm();
                               var fvalue = Ext.getCmp('ReconDataImport_upfile').getValue();
                            var myReg=/^[a-zA-Z]:\\[^\:\*\?\/\|\"\<\>]+\.(xls|XLS)/;
                               if(ReconDataImportForm.isValid()) {
                                   if(Ext.getCmp('ReconDataImport_recodeNum').getValue() > 2000) {
                                       Ext.Msg.alert('提示','入库记录数不允许大于2000!');
                                       return;
                                   }
                                   
                                   if(!myReg.test(fvalue)){
                                       Ext.Msg.alert('提示','上传文件格式或路径错误,请检查!');
                                    return;
                                  }
                                   
                                   if(fvalue.substring(fvalue.length-3,fvalue.length).toLowerCase() != "xls"){
                                       if(fvalue.substring(fvalue.length-4,fvalue.length).toLowerCase() != "xlsx"){
                                       Ext.Msg.alert('提示','对不起,只能上传excel类型文件!');
                                    return;        
                                }
                                   }
                                   ReconDataImportForm.submit({
                                       url: contextPath + ReconDataImport_cmdUpload,
                                       method: 'POST',
                                       waitMsg: '正在上传文件请稍后...',
                                       success: function(fp, o) {
                                           Ext.getCmp('uploadbtn').resbtn = o.result.file;
                                           Ext.getCmp('imbtn').setDisabled(!o.result.file);
                                           Ext.Msg.alert('提示','您的文件  "' + o.result.file + '" 已经成功上传。');
                                           ReconDataImport_filepath = o.result.filepath;
                                           ReconDataImport_resultNameSessionId = o.result.resultNameSessionId;
                                           ReconDataImport_filename = o.result.file;
                                           ReconDataImport_workerSessionId = o.result.workerSessionId;
                                       }
                                   })
                               }
                           }
                    },{
                        xtype:'button',
                        id:'imbtn',
                        height:25,
                        width:100,
                           text:'导入结算数据',
                           disabled:true,
                           handler:function(){
                               
                               var ReconDataImportForm=Ext.getCmp("importsform").getForm();
                               if(ReconDataImportForm.isValid()) {
                                   if(Ext.getCmp('ReconDataImport_recodeNum').getValue() > 2000) {
                                       Ext.Msg.alert('提示','入库记录数不允许大于2000!');
                                       return;
                                   }
                                   
                                   ReconDataImportForm.load({
                                       url: contextPath + ReconDataImport_cmdReconData,
                                       params:{filepath: ReconDataImport_filepath,resultNameSessionId: ReconDataImport_resultNameSessionId, filename: ReconDataImport_filename, workerSessionId:ReconDataImport_workerSessionId},
                                       method: 'POST',
                                       waitMsg: '正在导入结算数据请稍后...',
                                       failure: function(form, action) {
                                           Ext.getCmp('download').setDisabled(false);
                                           if(action.result.success==true) {
                                               
                                               Ext.Msg.alert('提示','导入结算数据成功');
                                           }else {
                                               Ext.Msg.alert('提示', '导入结算数据失败!');
                                           }
                                       }
                                   })
                           }}
                    },{
                        xtype:'button',
                        id:'download',
                        height:25,
                        width:100,
                           text:'下载结果文件',
                           disabled:true,
                           handler:function(){
                               var ReconDataImportForm=Ext.getCmp("importsform").getForm();
                               ReconDataImportForm.submit({
                                   url: contextPath + ReconDataImport_cmdDownload,
                                   method: 'POST',
                                   failure: function(form, action) {
                                       if(action.result.success==true){
                                           Ext.Msg.alert('提示','下载结果文件成功');
                                       } else {
                                           Ext.Msg.alert('提示','下载结果文件失败!');
                                       }
                                   },
                                    success: function(form, action) {
                                       
                                        if(action.result.success==true){
                                            Ext.Msg.alert('提示','下载结果文件成功');
                                        } else {
                                            Ext.Msg.alert('提示','下载结果文件失败!');
                                        }
                                    }
                               })
                           }
                    }]
                 })]
           })
        }
        win.show();
        
      }
})


2、storedata

function StoreCollection(){}

var gcodeMap = new Ext.util.HashMap();
gcodeMap.add('province','get_province_4_mobile');
gcodeMap.add('product','get_product_map');
gcodeMap.add('product_code','get_product_map');
gcodeMap.add('role','get_role_name');
gcodeMap.add('orgnization','get_org_name');
gcodeMap.add('bill_month','get_bill_month');
gcodeMap.add('sett_obj_code','get_op_partners_code');

Ext.define('Code2Name', {
    extend: 'Ext.data.Model',
    fields: [
        {type: 'string', name: 'name'},
        {type: 'string', name: 'parentCode'},
        {type: 'string', name: 'code'},
        {type: 'string', name: 'exData'}
        
    ]
});

var commonQuery='/commons/commonQueryAction.do?METHOD=queryCode2Name';
var operatorQueryCondition='/admin/sysOperatorAction.do?METHOD=doQuery';


//账务月
var monthStore =Ext.create('Ext.data.JsonStore', {
  autoLoad: false,
  model: "Code2Name",
  proxy: {
      type: 'ajax',
      url : contextPath+commonQuery+'&gcode='+gcodeMap.get('bill_month'),
      reader: {
        type: 'json',
        root: 'recordes'
     }
 }
});

//合作商
var partnerStore = Ext.create('Ext.data.JsonStore', {
    autoLoad: false,
    model: "Code2Name",
    proxy: {
        type: 'ajax',
        url : contextPath+commonQuery+'&gcode='+gcodeMap.get('sett_obj_code'),
        reader: {
          type: 'json',
          root: 'recordes'
       }
   }
});

3、查询下拉列表框信息通用方法 后台处理

1) CommonQueryAction.java


import java.util.List;

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

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.xxx.sett.commons.utils.JsonPackage;
import com.xxx.sett.commons.utils.Translate;
import com.xxx.sett.commons.web.struts.BaseAction;

public class CommonQueryAction extends BaseAction {
    
    private static Logger logger = Logger.getLogger(CommonQueryAction.class);
    /*
     * 查询下拉列表框信息通用方法
     */
    public ActionForward queryCode2Name(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
            StringBuffer jsonString = new StringBuffer();
        try {
            String gcode=request.getParameter("gcode");
            //这里不适用 Translate tl = new Translate();获取Translate实例
            //只是通过getInstance()获取Translate单例
            List codeNames=Translate.getInstance().getDataListNoParam(gcode);
            
            JsonPackage.packageCode2Name(response,codeNames);
            
        } catch (Exception e) {
            log.info(e.getMessage());
            e.printStackTrace();            
            
            JsonPackage.packageCode2Name(response,null);
        }
        logger.info(jsonString.toString());
        return null;
    }    

}


2) Translate

package com.maywide.sett.commons.utils;

import java.util.List;

import com.xxx.sett.commons.cache.StaticData;
import com.xxx.sett.commons.cache.StaticDataVO;
/**
 *
 * @author user
 *
 */
public class Translate {
    public static final String SYSPARAM = "SYSPARAM";

    public static final String SYSPARAM_EX = "SYSPARAMEX";

    private static final String SEP = ",";

    private static Translate me = new Translate();

    private Translate() {
    }

    public static Translate getInstance() {
        return me;
    }
    /**
     * 用指定的sql语句查询所有mcode和mname,用List返回
     * @param sql_id
     *                 sql语句的id
     * @return
     *                 包含查询到的mcode和mname的List
     */
    public List<StaticDataVO> getDataListNoParam(String sql_id) {
        return StaticData.getInstance().getStaticDataNoParam(sql_id);
    }
}


3)  StaticData

package com.xxx.sett.commons.cache;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.xxx.sett.commons.dao.StaticDataDAO;
import com.xxx.sett.commons.dao.maps.QuerysqlVO;
import com.xxx.sett.commons.utils.FileUtils;

public class StaticData {
    private static final Log log = LogFactory.getLog(StaticData.class);

    // private static StaticData me = new StaticData();
    public final static String DC_PUBLIC_PARAM = "SYSPARAM";

    public final static String DC_PUBLIC_PARAM_EX = "SYSPARAMEX";
    
    public final static String DC_PUBLIC_PARAM_bilmonth = "get_bill_month";

    public static List<String> staticType = null;

    private StaticData() {
        if (staticType == null) {
            staticType = new ArrayList<String>();
            try {
                String[] rec = new FileUtils()
                        .readFile("loadmemorylist.properties");
                for (int i = 0; i < rec.length; i++) {
                    if (rec[i].trim().length() < 2) {
                        continue;
                    }
                    if (rec[i].trim().startsWith("#")) {
                        continue;
                    }
                    if (rec[i].trim().startsWith("-")) {
                        continue;
                    }
                    staticType.add(rec[i]);
                }
            } catch (Exception ex) {
                staticType = null;
            }
        }
    }

    public static StaticData getInstance() {
        return new StaticData();
    }

    public boolean isExist(String sql_id) {
        if (sql_id == null) {
            return false;
        }
        if (staticType.contains(sql_id)) {
            return true;
        }
        return false;
    }

 
    public List getStaticDataNoParam(String sql_id) {
        return getStaticData(sql_id, null);
    }

    public List getStaticData(String sql_id, String firstPKey) {
        try {
//            // sql
//            QuerysqlVO sqlvo = getSqlVO(sql_id, firstPKey);

            // data
            List dataList = null;
            dataList = StaticDataCache.getInstance().getStaticData(sql_id,
                    firstPKey);
            if (dataList == null) {
                // sql但缓存中去不到再去去QuerysqlVO并通过SQL获取下拉框数据
                QuerysqlVO sqlvo = getSqlVO(sql_id, firstPKey);
                dataList = StaticDataDAO.getInstance().getStaticData(
                        sqlvo.getSelectsql(), firstPKey);
                if (dataList == null) {
                    throw new Exception("找不到静态数据, 静态数据定义名:" + sql_id + "_"
                            + firstPKey);
                } else {
                    if (StaticData.getInstance().isExist(sql_id)
                            || StaticData.DC_PUBLIC_PARAM
                                    .equalsIgnoreCase(sql_id)
                            || StaticData.DC_PUBLIC_PARAM_EX
                                    .equalsIgnoreCase(sql_id)
                            //||StaticData.DC_PUBLIC_PARAM_bilmonth.equalsIgnoreCase(sql_id)
                                    ) {

                        StaticDataCache.getInstance().setStaticData(sql_id,
                                firstPKey, dataList);
                        StaticDataCache.getInstance().updateStaticData(sql_id,
                                firstPKey);
                    }
                }
            }
            return dataList;
        } catch (Exception ex) {
            log.error("获取静态数据出错,dataNames:" + sql_id + "_" + firstPKey, ex);
        }
        return null;
    }


    public QuerysqlVO getSqlVO(String sql_id, String firstPKey)
            throws Exception {
        QuerysqlVO sqlvo = StaticDataCache.getInstance().getSqlVO(sql_id,
                firstPKey);
        if (sqlvo == null) {//如果缓存中没有 则在数据库中从新查找
            sqlvo = StaticDataDAO.getInstance().getSqlVO(sql_id);
            if (sqlvo == null) {
                throw new Exception("找不到相关静态数据的SQL定义, 静态数据定义名:" + sql_id + "_"
                        + firstPKey);
            }
            StaticDataCache.getInstance().setSql(sql_id, firstPKey, sqlvo);
        }
        return sqlvo;
    }

    public void clearCache() {
        StaticDataCache.getInstance().clearCache();
    }

}

4) StaticDataCache

package com.xxx.sett.commons.cache;

import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


import com.xxx.sett.commons.dao.maps.QuerysqlVO;

public class StaticDataCache implements Serializable {
    /**
     *
     */
    private static final long serialVersionUID = -956824502758120571L;

    private static int durationSeconds = -1;

    private static Map<String, List> dataCache = Collections
            .synchronizedMap(new HashMap<String, List>());

    private static StaticDataCache me = null;

    private static long lastUpdateCheck = System.currentTimeMillis();

    synchronized public static StaticDataCache getInstance() {
        if (me == null) {
            me = new StaticDataCache();
        }
        return me;
    }

    private StaticDataCache() {
        durationSeconds = 60;
    }

    public List getStaticData(String sql_id, String firstPKey) {
        return (List) dataCache.get(getFlag(sql_id, firstPKey));
    }

    public List getStaticData(String sql_id, String firstPKey,
            String secondePKey) {
        return (List) dataCache.get(getFlag(sql_id, firstPKey, secondePKey));
    }


    public QuerysqlVO getSqlVO(String sql_id, String firstPKey) {
        long interval = System.currentTimeMillis() - lastUpdateCheck;
        if (durationSeconds >= 0) {
            if (interval > 1000 * durationSeconds) {
                if (checkCache != null) {
                    Iterator it = checkCache.keySet().iterator();
                    while (it.hasNext()) {
                        Long timeCheck = (Long) it.next();
                        if (timeCheck.longValue() > lastUpdateCheck) {
                            String dataName = (String) checkCache
                                    .get(timeCheck);
                            if (dataName != null
                                    && dataName.trim().toLowerCase().equals(
                                            "all")) {
                                dataCache.clear();
                            } else if (dataName != null) {
                                dataCache.remove(dataName.toLowerCase());
                                dataCache.remove(dataName.toUpperCase());
                            }
                        }
                    }
                }
                lastUpdateCheck = System.currentTimeMillis();
            }
        }
        return (QuerysqlVO) sqlCache.get(getFlag(sql_id, firstPKey));
    }

    
    private String getFlag(String sql_id, String firstPKey) {
        String flag = sql_id;
        if (firstPKey != null) {
            flag += "_" + firstPKey;
        }
        return flag;
    }
    
    public void setStaticData(String sql_id, String firstPKey, List dataList) {
        dataCache.put(getFlag(sql_id, firstPKey), dataList);
    }

    public void setSql(String sql_id, String firstPKey, QuerysqlVO vo) {
        String FlagStr = getFlag(sql_id, firstPKey);
        sqlCache.put(FlagStr, vo);
    }


    public boolean updateStaticData(String sql_id, String firstPKey) {
        if (sql_id == null) {
            return false;
        }

        String FlagStr = getFlag(sql_id, firstPKey);

        if (checkCache == null) {
            checkCache = Collections
                    .synchronizedMap(new HashMap<Long, String>());
        }

        Long timeCheck = Long.valueOf(System.currentTimeMillis());
        checkCache.put(timeCheck, FlagStr);

        return true;
    }
    public synchronized void clearCache() {
        dataCache = null;
        checkCache = null;
        dataCache = Collections.synchronizedMap(new HashMap<String, List>());
        checkCache = Collections.synchronizedMap(new HashMap<Long, String>());
    }

}

package com.xxx.sett.commons.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.xxx.sett.commons.cache.LoadSqlFile;
import com.xxx.sett.commons.cache.StaticDataVO;
import com.xxx.sett.commons.dao.maps.QuerysqlVO;
import com.xxx.sett.commons.utils.DAOUtils;
import com.xxx.sett.commons.utils.SpringContextUtil;

public class StaticDataDAO extends SqlMapClientDaoSupport{
    private static final Log log = LogFactory.getLog(StaticDataDAO.class);

    private static StaticDataDAO me = null;

    private static String sel_sql_table = null;
    
    //private QuerysqlDAO querysqlDAO;

    private StaticDataDAO() {
        if (sel_sql_table == null) {
            sel_sql_table = LoadSqlFile.loadSQL("SELECT_SQL_TABLE");
        }
    }

    synchronized static public StaticDataDAO getInstance() {
        if (me == null) {
            me = (StaticDataDAO)SpringContextUtil.getBean("staticDataDAO");
        }
        return me;
    }

    public List<StaticDataVO> getStaticData(String selectSQL, String firstPkey)
            throws Exception {
        PreparedStatement stmt = null;
        ResultSet result = null;
        Connection conn = null;

        List<StaticDataVO> retList = new ArrayList<StaticDataVO>();

        try {
            conn = super.getDataSource().getConnection();
            stmt = conn.prepareStatement(selectSQL);
            if (log.isDebugEnabled()) {
                log.debug("SQL = [" + selectSQL + "]\r\nparams=[" + firstPkey
                        + "]");
            }
            if (firstPkey != null || selectSQL.indexOf("?") != -1) {
                stmt.setString(1, firstPkey);
            }
            result = stmt.executeQuery();

            int columCount = stmt.getMetaData().getColumnCount();
            while (result.next()) {
                StaticDataVO staticDataVo = new StaticDataVO();
                if (columCount == 3) {
                    staticDataVo.setCode(result.getString(1));
                    staticDataVo.setName(result.getString(2));
                    staticDataVo.setParentCode(result.getString(3));
                } else if (columCount == 2) {
                    staticDataVo.setCode(result.getString(1));
                    staticDataVo.setName(result.getString(2));
                    staticDataVo.setParentCode(null);
                } else if (columCount > 3) {
                    staticDataVo.setCode(result.getString(1));
                    staticDataVo.setName(result.getString(2));
                    staticDataVo.setParentCode(result.getString(3));
                    List<String> exData = new ArrayList<String>();
                    for (int i = 4; i <= columCount; i++) {
                        exData.add(result.getString(i));
                    }
                    staticDataVo.setExData(exData);
                }
                retList.add(staticDataVo);
            }
        } catch (SQLException se) {
            throw new DAOException("SQLException while getting " + "sql:\n"
                    + se.getMessage(), se);
        } finally {
            DAOUtils.closeAll(conn, stmt, result);
        }

        return retList;
    }
}


5)StaticDataDAO

package com.xxx.sett.commons.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.xxx.sett.commons.cache.LoadSqlFile;
import com.xxx.sett.commons.cache.StaticDataVO;
import com.xxx.sett.commons.dao.maps.QuerysqlVO;
import com.xxx.sett.commons.utils.DAOUtils;
import com.xxx.sett.commons.utils.SpringContextUtil;

public class StaticDataDAO extends SqlMapClientDaoSupport{
    private static final Log log = LogFactory.getLog(StaticDataDAO.class);

    private static StaticDataDAO me = null;

    private static String sel_sql_table = null;
    
    //private QuerysqlDAO querysqlDAO;

    private StaticDataDAO() {
        if (sel_sql_table == null) {
            sel_sql_table = LoadSqlFile.loadSQL("SELECT_SQL_TABLE");
        }
    }

    synchronized static public StaticDataDAO getInstance() {
        if (me == null) {
            me = (StaticDataDAO)SpringContextUtil.getBean("staticDataDAO");
        }
        return me;
    }

    public List<StaticDataVO> getStaticData(String selectSQL, String firstPkey)
            throws Exception {
        PreparedStatement stmt = null;
        ResultSet result = null;
        Connection conn = null;

        List<StaticDataVO> retList = new ArrayList<StaticDataVO>();

        try {
            conn = super.getDataSource().getConnection();
            stmt = conn.prepareStatement(selectSQL);
            if (log.isDebugEnabled()) {
                log.debug("SQL = [" + selectSQL + "]\r\nparams=[" + firstPkey
                        + "]");
            }
            if (firstPkey != null || selectSQL.indexOf("?") != -1) {
                stmt.setString(1, firstPkey);
            }
            result = stmt.executeQuery();

            int columCount = stmt.getMetaData().getColumnCount();
            while (result.next()) {
                StaticDataVO staticDataVo = new StaticDataVO();
                if (columCount == 3) {
                    staticDataVo.setCode(result.getString(1));
                    staticDataVo.setName(result.getString(2));
                    staticDataVo.setParentCode(result.getString(3));
                } else if (columCount == 2) {
                    staticDataVo.setCode(result.getString(1));
                    staticDataVo.setName(result.getString(2));
                    staticDataVo.setParentCode(null);
                } else if (columCount > 3) {
                    staticDataVo.setCode(result.getString(1));
                    staticDataVo.setName(result.getString(2));
                    staticDataVo.setParentCode(result.getString(3));
                    List<String> exData = new ArrayList<String>();
                    for (int i = 4; i <= columCount; i++) {
                        exData.add(result.getString(i));
                    }
                    staticDataVo.setExData(exData);
                }
                retList.add(staticDataVo);
            }
        } catch (SQLException se) {
            throw new DAOException("SQLException while getting " + "sql:\n"
                    + se.getMessage(), se);
        } finally {
            DAOUtils.closeAll(conn, stmt, result);
        }

        return retList;
    }
    
        public QuerysqlVO getSqlVO(String sql_id) throws Exception {
        QuerysqlDAO query =(QuerysqlDAO)SpringContextUtil.getBean("querysqlDAO");
        return (QuerysqlVO) query.getObjectByID(sql_id);
    }
}

6)  SpringContextUtil

package com.xxx.sett.commons.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringContextUtil implements ApplicationContextAware {
    
//     Spring应用上下文环境
    private static ApplicationContext applicationContext;
    
    /**
    * 实现ApplicationContextAware接口的回调方法,设置上下文环境
    */
    public void setApplicationContext(ApplicationContext applicationContext)throws BeansException  {
           SpringContextUtil.applicationContext= applicationContext;
    }
    
    public static ApplicationContext getApplicationContext(){
           return applicationContext;
    }
    
    /**
    * 获取对象
    * 这里重写了bean方法,起主要作用
    * @param name
    * @return Object 一个以所给名字注册的bean的实例
    * @throws BeansException
    */
    public static Object getBean(String beanId)throws BeansException {
           return applicationContext.getBean(beanId);
    }
}

7) QuerysqlDAO

package com.xxx.sett.commons.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.xxx.sett.commons.cache.ItemChoiceVO;
import com.xxx.sett.commons.cache.StaticData;
import com.xxx.sett.commons.dao.maps.QuerysqlVO;
import com.xxx.sett.commons.utils.DAOUtils;
import com.xxx.sett.commons.utils.PageBeanVO;
import com.xxx.sett.commons.utils.SpringContextUtil;
import com.xxx.sett.commons.utils.StringUtils;

public class QuerysqlDAO extends SqlMapClientDaoSupport{
       
      private static final Log log = LogFactory.getLog(QuerysqlDAO.class);
    
       public QuerysqlVO getObjectByID(String id) throws Exception{
              return (QuerysqlVO)super.getSqlMapClient().queryForObject("getObjectByID", id);
       }
}


8)localdataAccessContext.xml

<?xml version="1.0" encoding="UTF-8"?>

<!--
  - Application context definition for JPetStore's data access layer.
  - Accessed by business layer objects defined in "applicationContext.xml"
  - (see web.xml's "contextConfigLocation").
  -
  - This version of the data access layer works on a combined database,
  - using a local DataSource with DataSourceTransactionManager. It does not
  - need any JTA support in the container: It will run as-is in plain Tomcat.
  -->
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
            http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">

    <!-- ========================= RESOURCE DEFINITIONS ========================= -->

    <!-- Local Apache Commons DBCP DataSource that refers to a combined database -->
    <!-- (see dataAccessContext-jta.xml for an alternative) -->
    <!-- The placeholders are resolved from jdbc.properties through -->
    <!-- the PropertyPlaceholderConfigurer in applicationContext.xml -->
    <!-- jee命名空间里的<jee:jndi-lookup>元素可以从JNDI获取对象-->    
    <jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/defaultDS"/>
    
    <!--bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>-->
    
    <!--bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation">
              <value>/WEB-INF/hibernate.cfg.xml</value>
        </property>
    </bean>-->

    <!-- Transaction manager for a single JDBC DataSource -->
    <!-- (see dataAccessContext-jta.xml for an alternative) -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- SqlMap setup for iBATIS Database Layer -->
    <bean id="sqlMapClient" class="com.xxx.sett.commons.dao.SqlMapClientFactoryBean">
        <property name="configLocation" value="WEB-INF/sql-map-config.xml"/>
        <property name="dataSource" ref="dataSource"/>
        <property name="sqlExecutor">
            <ref bean="sqlExecutor" />
        </property>
    </bean>


    <!-- ========================= DAO DEFINITIONS: IBATIS IMPLEMENTATIONS ========================= -->
    <bean id="querysqlDAO" class="com.xxx.sett.commons.dao.QuerysqlDAO">
        <property name="sqlMapClient" ref="sqlMapClient"/>
    </bean>
    
    <bean id="staticDataDAO" class="com.xxx.sett.commons.dao.StaticDataDAO">
        <property name="sqlMapClient" ref="sqlMapClient"/>        
    </bean>
    
    <bean id="ajustmentAccountDao" class="com.xxx.sett.business.dao.AjustmentAccountDaoImp">
        <property name="sqlMapClient" ref="sqlMapClient"/>        
    </bean>
    
    <bean id="billingResultDao" class="com.xxx.sett.business.dao.BillingResultDaoImp">
        <property name="sqlMapClient" ref="sqlMapClient"/>        
    </bean>
    
    <bean id="partnersSettReconDataDao" class="com.xxx.sett.business.dao.PartnersSettReconDataDaoImp">
        <property name="sqlMapClient" ref="sqlMapClient"/>        
    </bean>
    
    <bean id="distributionItemDao" class="com.xxx.sett.business.dao.DistributionItemDaoImp">
        <property name="sqlMapClient" ref="sqlMapClient"/>        
    </bean>    
    
    <bean id="productSetDao" class="com.xxx.sett.busiconf.dao.ProductSetDaoImp">
        <property name="sqlMapClient" ref="sqlMapClient"/>        
    </bean>
    
    <bean id="ruleSectionDao" class="com.xxx.sett.busiconf.dao.RuleSectionDaoImp">
        <property name="sqlMapClient" ref="sqlMapClient"/>        
    </bean>    
    <bean id="sqlExecutor" class="com.xxx.sett.commons.dao.engine.LimitSqlExecutor">
        <property name="dialect">
            <bean class="com.xxx.sett.commons.dao.jdbc.OracleDialect" />
        </property>
    </bean>

</beans>

一些VO

QuerysqlVO

package com.xxx.sett.commons.dao.maps;

public class QuerysqlVO {

    private static final long serialVersionUID = -4082867189353383334L;

    // fields
    private String id;

    private String selectsql;

    private String name;

    private String kind;

    private String title;

    private String head;

    private String fmt;

    private String condition;

    
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getSelectsql() {
        return selectsql;
    }

    public void setSelectsql(String selectsql) {
        this.selectsql = selectsql;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCondition() {
        return condition;
    }

    public void setCondition(String condition) {
        this.condition = condition;
    }

    public String getFmt() {
        return fmt;
    }

    public void setFmt(String fmt) {
        this.fmt = fmt;
    }

    public String getKind() {
        return kind;
    }

    public void setKind(String kind) {
        this.kind = kind;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getHead() {
        return head;
    }

    public void setHead(String head) {
        this.head = head;
    }

}


StaticDataVO

package com.xxx.sett.commons.cache;
import java.util.List;
import com.xxx.sett.commons.dao.BaseVO;

public class StaticDataVO extends BaseVO {

    private static final long serialVersionUID = -124055849640704217L;

    private String name = "";

    private String parentCode = "";

    private String code = "";

    private List exData = null;

    public String getName() {
        return name;
    }

    public String getParentCode() {
        return parentCode;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setParentCode(String parentCode) {
        this.parentCode = parentCode;
    }

    public void setExData(List exData) {
        this.exData = exData;
    }

    public String getCode() {
        return code;
    }

    public List getExData() {
        return exData;
    }

    public StaticDataVO() {
    }
}

对service层返回数据的处理

JsonPackage:

package com.xxx.sett.commons.utils;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;

import com.xxx.sett.commons.cache.StaticDataVO;

public class JsonPackage {
    
    private static Logger logger = Logger.getLogger(JsonPackage.class);
    
    private static final String CONTENT_TYPE = "text/json; charset=utf-8";

    public static final String ROOT = "root";
    
    public static final String CODE = "code";

    public static final String RECORDS = "recordes";

    public static final String RESULTKEY = "result";

    public static void  packageCode2Name(HttpServletResponse response,List codeNames)throws Exception{
          
          //PrintWriter out = response.getWriter();
        try{
            StringBuffer jsonString=packageCode2Name(codeNames);
            response.setContentType("text/json; charset=utf-8");
            response.getWriter().write(jsonString.toString());
            logger.info(jsonString.toString());
        }finally{
            response.getWriter().close();
            
        }    
           
    }
    
    public static StringBuffer packageCode2Name(List codeNames)throws Exception{
        StringBuffer jsonString = new StringBuffer();
        JSONArray jsonArry = new JSONArray();
        if(codeNames!=null&&codeNames.size()>0){
            for(int i=0;i<codeNames.size();i++){
                StaticDataVO dataVO=(StaticDataVO)codeNames.get(i);
                JSONObject map = new JSONObject();
                map.put("code", dataVO.getCode());
                map.put("name", dataVO.getName());
                jsonArry.put(map);
            }    
        }
        
        jsonString.append("{\""+RECORDS+"\":");
        jsonString.append(jsonArry.toString());
        jsonString.append("}");
        return jsonString;
    }
}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值