• ajax与java前后台传值及数据表查询解决一个bug的问题


       前台选中某些表,确定提交到后台,偶尔会报500错误,通过排查发现:由于后台代码写的不严谨,导致前台选中的表名如果全不存在的话就会导致后台走异常报500错误,所以决定在前台先对数据进行一次过滤,使至少有一个表名存在的话才会去走跳转语句。数据过滤成功之后再去请求下载的方法。下面相关代码记录:

    1、此处获取所有选中复选框的id。

    function getCheckbox(){
        var checkbox = $('.un-p-l input'),
            len = checkbox.length,
            checkboxStr = '';
        for(var i = 0; i < len; i++){
            if(checkbox.eq(i).prop("checked")){
                checkboxStr += checkbox.eq(i).val() + ',';
            }
        }
        return checkboxStr.substring(0,checkboxStr.length - 1);
    }

    2、把选中的复选框的id值传给后台。

    function AcceptClick(){
        var checkboxStr = getCheckbox();
         if($.checkSession()){
                 $.ajax({
                    url:'${basePath}/dict/logConfigAction_validatorBackUp.do',
                    datatype:"text",
                    async:true,
                    data:{
                        'checkbox':checkboxStr
                    },
                    success:function(responseText){
                        var obj = eval("(" + responseText + ")");
                        if(obj.result == "success"){
                            var $form =  $("#backupForm") ;
                            var action = "";
                            try {
                                action = $form.attr("action"); 
                                $form.attr("action","${basePath}/dict/logConfigAction_backup.do").submit();    
                            }finally{
                                $form.attr("action",action);
                            }
                        }else{
                            dialogMsg("选中的表名全不存在,无法备份!",-1);
                        }
                    }
                });
            }
    }

    3、java后台获取值,内部操作并返回给前台

    public void validatorBackUp(){
            log.info("备份校验-BEGIN");
            this.msg=RESULT_FAIL;
            String[] logConfigIdsArr = getRequest().getParameter("checkbox").split(",");//获取前台传过来的值,并拆分成数组
            List<String> successName = new ArrayList<String>();
            List<LogConfig> logConfigList = logConfigService.queryByIds(logConfigIdsArr);//通过id去查找表名
            List<LogConfig> logConfigNewList = new ArrayList<LogConfig>();
            if(!logConfigList.isEmpty()){
                for(LogConfig LogConfig: logConfigList){
                    LogConfig logConfigTemp = new LogConfig();
                    logConfigTemp.setName(MessageUtils.getMessage(LogConfig.getName()));
                    logConfigTemp.setTableName(LogConfig.getTableName());
                    logConfigNewList.add(logConfigTemp);
                    successName.add(MessageUtils.getMessage(LogConfig.getName()));
                }
            }
            boolean tableFlag = logConfigService.tableExits(logConfigNewList,schemaName.toLowerCase());
            if(tableFlag){
                this.msg=RESULT_SUCCESS;
            }else{
                this.msg="tableNameFail";
            }
            print("{result: '"+ this.msg +"'}");
        }

    queryByIds方法在service层:

    public class LogConfigServiceImpl extends BaseServiceImpl<LogConfig> implements LogConfigService {
        ……
        public List<LogConfig> queryByIds(String[] ids) {
            return logConfigDao.queryByIds(ids);
        }
        ……
    }

    dao层里的queryByIds

    public class LogConfigDaoImpl extends BaseDaoImpl<LogConfig> implements LogConfigDao {
        ……
        public List<LogConfig> queryByIds(String[] ids) {
            String hql = "from " + this.clazz.getName() + " this where this.id in:ids";
            //hql:from com.vrv.cems.dict.domain.LogConfig this where this.id in:ids
            return getSession().createQuery(hql).setParameterList("ids", ids).list();
        }
        ……
    }

    返回的数据就是:

    经过循环处理之后,我们只需要数据里的:name和tableName

    4、查询表,返回给java方法的值。logConfigService.tableExits代表service层的tableExits方法:

    public boolean tableExits(List<LogConfig> logConfigList,String schemaName ) {
            List<Object[]> li = null;
            List<String> l = new ArrayList<String>();
            if(logConfigList.size()>0){
                for(LogConfig logConfig : logConfigList){
                    l.add(logConfig.getTableName().trim());
                }
                li = logConfigDao.queryLogTableByTableNames(l,schemaName);
            }
            if(li != null && li.size() > 0){
                return true;
            }else{
                return false;
            }
        }

    经过循环处理,l只需要它的tableName

    5、采用in查询查询表的方法:logConfigDao.queryLogTableByTableNames,dao层的queryLogTableByTableNames方法

      @Override
        public List<Object[]> queryLogTableByTableNames(List tableNames,String schemaName) {
                StringBuilder sql=new StringBuilder();
                Map<String,Object> paraMap=new HashMap<String, Object>();//paraMap:{}
                sql.append("  select COLUMN_NAME,DATA_TYPE FROM information_schema.COLUMNS WHERE table_name  IN (:tableNames) and table_schema =:schemaName");
           //sql:select COLUMN_NAME,DATA_TYPE FROM information_schema.COLUMNS WHERE table_name  IN (:tableNames) and table_schema =:schemaName paraMap.put(
    "tableNames", tableNames); paraMap.put("schemaName", schemaName);
           //paraMap:{schemaName=cems, tableNames=[cems_log_device_openlog, cems_log_device_clientLog, cems_log_device_clientLog, cems_log_device_clientLog]} Query q
    =getSession().createSQLQuery(sql.toString()); q = assignValues(q, paraMap); return q.list(); } public Query assignValues(Query query, Map<String, ?> values) { if (values != null) {   Set<String> keySet = values.keySet();   for (String string : keySet) {     Object obj = values.get(string);     if (obj instanceof Collection<?>) {       query.setParameterList(string, (Collection<?>) obj);     } else if (obj instanceof Object[]) {       query.setParameterList(string, (Object[]) obj);     } else {       query.setParameter(string, obj);     }   } } return query; }

     通过in查询li获取的值是很多字段,如果查询到的话;如果没查询到就返回的都是空

    最后在service层通过判断返回逻辑值给action层,action层再通过逻辑值确定返回值给前台。

    action层:service层和dao层:

  • 相关阅读:
    技术面试之经验总结
    为何只有两篇文章?
    LOJ6364 烂柯
    mysql批量更新数据(性能优化)
    一个对象的key引发的血案
    总结与元素坐标相关的属性(再也搞不混了)
    利用nodejs搭建服务器,测试AJAX
    初探jquery之强大丰富的选择器
    Web前端开发规范手册
    IE8下标签float导致的bug。
  • 原文地址:https://www.cnblogs.com/goloving/p/7381116.html
Copyright © 2020-2023  润新知