首页 > 代码库 > SpringMVC +mybatis+spring 结合easyui用法及常见问题总结

SpringMVC +mybatis+spring 结合easyui用法及常见问题总结

SpringMVC +mybatis+spring 结合easyui用法及常见问题总结

1.FormatString的用法.

 技术分享

 

2.用postAjaxFillGrid实现dataGrid 把form表单转换成一个map对象传入后台实现条件查询.

Js代码:

var oPage = {

    pageIndex: 1,

    pageSize: 20

};

   postAjaxFillGrid(‘#FormID‘,‘${contextPath}/discountController/selectDiscount‘,‘#DataGridId‘, oPage);

 

参数说明: formID为查询条件的formId属性值,DataGridId为实现datagrid的Id属性值.opage为设置显示多少条.

 

 

Java代码:

@ResponseBody

@RequestMapping(value = "http://www.mamicode.com/selectDiscount", method = RequestMethod.POST)

public DataGrid selectDiscount(@RequestBody ConditionEx condition){

        Page<Discount> discountPage=discountService.selectDiscountPage(condition.getCondition(),

                Integer.valueOf(condition.getPage().get("pageIndex").toString())-1,

                Integer.valueOf(condition.getPage().get("pageSize").toString()));

        return new DataGrid(discountPage);

  }

参数说明:

method = RequestMethod.POST 设置为Post 必须设置

@RequestBody ConditionEx condition @RequestBody为前台传过来的json字符串绑定到condition对象或者集合上.所以我们得到了数据

解析postAjaxFillGrid

function postAjaxFillGrid(formId,url,gridId){

var condition = $.serializeObject(formId);//通过formId把里面的数据转换成json对象

    jQuery.ajax({

        type: ‘POST‘,

        contentType: ‘application/json‘,

        url: url,

        data: jQuery.toJSON({condition: condition, page: oPage}),//json对象转换成json字符串

        dataType: ‘json‘,//按照json格式传入后台

        success: function (data) {

            $(gridId).datagrid(‘loadData‘, data);

        },

        error: function (data) {

            console.error("读取数据失败");

        }

    });

}

 

3.把form表单转换成json对象.

$.serializeObject = function(form) {

    var o = {};

    $.each($(form).serializeArray(), function(index) {

        if (o[this[‘name‘]]) {

            o[this[‘name‘]] = o[this[‘name‘]] + "," + this[‘value‘];

        } else {

            o[this[‘name‘]] = this[‘value‘];

        }

    });

    return o;

};

4.解析doPagination

DoPagination 为easyui默认分页事件.调出可手动更改其方法.

 

5.excel报表导出实现

Js代码:

function dataExport() {

            var condition = $.serializeString(‘#searchForm‘);//把form表单数据转换成字符串,url样式

            var url=‘${contextPath}/settlementController/exportSettlementReport‘+condition;

            $(‘#exportForm‘).attr(‘action‘,url);//替换form表单的action属性值

            $(‘#exportForm‘).submit();

        }

 

$.serializeString = function(form) {

    var o=‘‘;

    var a = $(form).serializeArray();

    var index=0;

    $.each(a, function() {

        if ($.trim(this.value) != ‘‘) {

            if(index == 0){

                o=o+‘?‘+this.name+‘=‘+this.value

            }else{

                o=o+‘&&‘+this.name+‘=‘+this.value

            }

            index++;

        }

        else{

            if(index == 0){

                o=o+‘?‘+this.name+‘=‘+‘‘

            }else{

                o=o+‘&&‘+this.name+‘=‘+‘‘

            }

            index++;

        }

    });

    return o;

};

Java代码:

@ResponseBody

    @RequestMapping(value = "http://www.mamicode.com/exportSettlementReport", method = RequestMethod.POST)

    public ModelAndView exportSettlementReport(@RequestParam Map<String ,Object> conditionx) {

        List<Settlement> listResult=settlementService.selectDailySettlement(conditionx);

        Map<String,Object> model = new HashMap<String, Object>();

        model.put("data",listResult);

        String organName=organServiceI.selectOrganByCode(listResult.get(0).getSubCode());

        model.put("itemsName",organName);

 

       SettlementExcelView excelView = new SettlementExcelView();

        return new ModelAndView(excelView,model);

}

 

 

import bjnme.Lng.ibms.dto.Settlement;

import bjnme.Lng.ibms.utils.AbstractPOIExcelView;//引用类

import org.apache.poi.ss.usermodel.*;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

 

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.FileInputStream;

import java.util.List;

import java.util.Map;

 

public class SettlementExcelView extends AbstractPOIExcelView {

    @Override

    protected Workbook createWorkbook() throws Exception {

        String path = this.getClass().getClassLoader().getResource("/").getPath();

 

//        Biff8EncryptionKey.setCurrentUserPassword("123456");

        Workbook workbook = new XSSFWorkbook(new FileInputStream(path + "excels/settlement.xlsx"));

        return workbook;

    }

 

    @Override

    protected void buildExcelDocument(Map<String, Object> model,

                                      Workbook workbook, HttpServletRequest request, HttpServletResponse response)

            throws Exception {

 

 

        Sheet sheet = workbook.getSheet("总公司日结表");

 

        CellStyle style = workbook.createCellStyle();

        style.setBorderBottom(CellStyle.BORDER_THIN);

        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());

        style.setBorderLeft(CellStyle.BORDER_THIN);

        style.setLeftBorderColor(IndexedColors.BLACK.getIndex());

        style.setBorderRight(CellStyle.BORDER_THIN);

        style.setRightBorderColor(IndexedColors.BLACK.getIndex());

        style.setBorderTop(CellStyle.BORDER_THIN);

        style.setTopBorderColor(IndexedColors.BLACK.getIndex());

        Font font = workbook.createFont();

        font.setFontName("宋体");

        font.setFontHeightInPoints((short) 9);

        style.setFont(font);

        style.setLocked(true);

 

        List<Settlement> listResult = (List<Settlement>) model.get("data");

        Row row = sheet.getRow(1);

        row.getCell(0).setCellValue("单位:"+(String) model.get("itemsName"));

        String time = String.format("时间:%1s-%2s",listResult.get(0).getStartTime(),listResult.get(0).getEndTime());

        row.getCell(8).setCellValue(time);

        int index = 5;//设置从第几行开始填充

 

        for (Settlement settlement : listResult) {

             row =  sheet.createRow(index);

//设置一共要填充多少列

            for (int i = 0; i < 19; i++) {

                row.createCell(i).setCellStyle(style);

            }

            //为每一列赋值

            row.getCell(0).setCellValue(settlement.getId());

            row.getCell(1).setCellValue(settlement.getSubCode());

            row.getCell(2).setCellValue(settlement.getCardTypeCode());

 

            row.getCell(3).setCellValue(settlement.getCardNo());

            row.getCell(4).setCellValue(settlement.getUnit());

            row.getCell(5).setCellValue(settlement.getLastBalance());

            row.getCell(6).setCellValue(settlement.getLocalTotal());

 

 

            row.getCell(7).setCellValue(settlement.getTotalRecharge());

            row.getCell(8).setCellValue(settlement.getTotalPromotion());

            row.getCell(9).setCellValue(settlement.getSumGasMakeUp());

            row.getCell(10).setCellValue(settlement.getTotalBackDiff());

 

 

            row.getCell(11).setCellValue(settlement.getRemoteRecharge());

            row.getCell(12).setCellValue(settlement.getTotal());

            row.getCell(13).setCellValue(settlement.getTotalTrade());

            row.getCell(14).setCellValue(settlement.getRemoteTrade());

 

            row.getCell(15).setCellValue(settlement.getRefund());

            row.getCell(16).setCellValue(settlement.getCalcBalance());

            row.getCell(17).setCellValue(settlement.getActualBalance());

            row.getCell(18).setCellValue(settlement.getDiffBalance());

 

            index++;

        }

        String filename = "总公司日结表.xlsx";//设置下载时客户端Excel的名称

        if (request.getHeader("user-agent").contains("MSIE")) {

            filename = java.net.URLEncoder.encode(filename, "utf-8");

        } else {

            filename = new String(filename.getBytes("utf-8"), "iso-8859-1");

        }

        response.setHeader("Content-disposition", "attachment;filename=" + filename);

 

    }

参数说明:

@RequestParam用来获得静态的URL请求入参     spring注解时action里用到。就是把这个url参数封装到map集合里面.

6. easyUI_动态改变datagrid的url值

$(‘#tt‘).datagrid({  

url:‘/demo/user/getUsers‘,  

queryParams:{  

id:‘001‘,  

state:‘ok‘  

}  

});

 

 

7. easyui dataGrid 动态添加列.

Js代码:

<script>
    $(function () {

       $.getJSON(‘${pageContext.request.contextPath}/resources/json/datagrid_data.json‘,function(result){
            varcolumns=new Array();
            $.each(result.headers[0],function(i, field){
               var column={};
               column["title"]=i;
               column["field"]=field;
               column["width"]=50;
               columns.push(column);//当需要formatter的时候自己添加就可以了,原理就是拼接字符串.
            });
           $(‘#tt‘).datagrid({
               title:‘ XXX公司价差补差分配表‘,
               height:500,
               singleSelect:true,
               url:‘‘,
               frozenColumns :[[
                   {field:‘name‘,title:‘项目‘,width:80,sortable:true,align:‘center‘},
                   {field:‘count‘,title:‘合计‘,width:150,sortable:true}
               ]],columns : [
                   columns
               ],
               rownumbers:true}).datagrid(‘loadData‘,result.bodys);
        });
    })
</script>
<div title="XXX公司价差补差分配表"fit="true" border="false" style="height:94%;">
<table id="tt"  ></table>
</div>

Json代码:

 

json 代码格式.我这不用分页 也就没有total

{"headers":[
    {"一月份":"Jan","二月份":"Feb"}
],"bodys":[
    {"name":"LNG","count":"50000","Jan":"20000","Feb":"30000"}
]
}

8.easyui子页面增加tab的实现方法

//dataGrid行双击时间,这个增加tab的例子是建立在行双击的基础上面的

onDblClickRow:function(rowIndex,rowData){

addSubPage(“tab的名称”,‘${contextPath}/saleAnalysisController/showSaleAnalysis12‘,rowData.subCode)

            }

 

//增加tab所需的方法

functionaddSubPage(title,url,subCode){

        var jq = top.jQuery; //取得整个父页面对象

 

        var content=‘<iframescrolling="auto" frameborder="0"  src="http://www.mamicode.com/‘+url+‘?subCode=‘+subCode+‘"style="width:100%;height:100%;"></iframe>‘;

       jq("#index_tabs").tabs(‘add‘,{

            title:title,

            content:content,

            closable:true

        });

 

}

 

9.模块树形导航的制作

类似这样的

 

<scripttype="text/javascript">

 

    function initMenus() {

        <c:forEach items="${l2Menus}" var="parentMenu">

 

        var tr = $("#tree" +${parentMenu.resourceId});

        tr.tree({

            url:‘${pageContext.request.contextPath}/resourceController/getResourceTree?l2Menu=‘+ ${parentMenu.resourceId},

            idField: ‘id‘,

            parentField: ‘pid‘,

            textField: ‘text‘,

            onClick: function (node) {

 

                if (node.attributes &&node.attributes.url) {

                    var url;

                    var iframe;

                    if (node.attributes.url.indexOf(‘/‘)== 0) {

                        url =‘${pageContext.request.contextPath}‘ + node.attributes.url;

                    } else {

                        url =node.attributes.url;

                    }

                    //iframe = ‘<iframesrc="http://www.mamicode.com/‘ + url + ‘" frameborder="0"style="border:0;width:100%;height:98%;" sandbox></iframe>‘;

                    iframe = ‘<iframesrc="http://www.mamicode.com/‘ + url + ‘" frameborder="0"style="border:0;width:100%;height:98%;"></iframe>‘;

                    var t = $(‘#index_tabs‘);

                    var opts = {

                        title: node.text,

                        closable: true,

                        iconCls: node.iconCls,

                        content: iframe,

                        border: false

                    };

                    if (t.tabs(‘exists‘,opts.title)) {

                        t.tabs(‘select‘,opts.title);

                    } else {

                        t.tabs(‘add‘, opts);

                    }

                }

            }

 

        });

        </c:forEach>

 

    }

 

    $(function () {

        initMenus();

    });

 

</script>

<divid="divMenus" class="easyui-accordion"data-options="fit:true,border:false">

    <c:forEach items="${l2Menus}"var="parentMenu">

        <divtitle="${parentMenu.resourceName}" data-options="iconCls:‘iconicon-table-m‘" class="nav_title">

            <ulid="tree${parentMenu.resourceId}"></ul>

        </div>

    </c:forEach>

</div>

 

 

粉色部分其中${l2Menus}为在登录成功后查出来的综合管理系统下面的1级菜单.jstl标签遍历l2Menus这个集合,建立所有分类.每个分类里里面放一个ul,为了后面添加tree(树形菜单)

 

棕色即为tree的具体构建,此时的url查出来的是这个资源下面的资源.形成树.

10.datagrid合并单元格

 

Js代码:

 

$(function(){

         varnullData=http://www.mamicode.com/‘{"rows":[{"code":"一班","name":"张三","age":"21"},{"code":"一班","name":"李四","age":"22"}]}‘;

          var json=eval(‘(‘ + nullData + ‘)‘);

         $(‘#hebing‘).datagrid({

                   height:300,

                   width:500,

                   singleSelect:true,

        fitColumns:true,

                   data:json,

                   columns:[[

                            {field:‘code‘,title:‘班级‘,width:100},

                            {field:‘name‘,title:‘姓名‘,width:100},

                            {title:‘年纪‘,field:‘age‘,width:100}

                   ]],

                   onl oadSuccess:function(data){

                            $(‘#hebing‘).datagrid(‘mergeCells‘,{

                                               index:0,

                                               field:‘code‘,

                                               rowspan:2

                                     })     

                   }

                   });

         });

标红部分为主要实现方法,调用其方法.index表示索引从第几行开始field 找到索引行的列  ,rowspan表示跨2行合并,也可以用colspan实现跨两列实现.

 

11.datagrid扩展数据行鼠标悬停离开事件

可用于展示某列详情使用

 

打开jquery.easyui.min.js 文件,根据datagrid-row-over关键字找到关键行

 

 

此处扩展onMouseOutRow事件 ,红框内为要添加的代码.

 

其中_52c和_53d 根据easyui不同版本  参数会有不同. 根据红框上面数据改变.

 

代码为:     

  //此处为添加的鼠标悬停事件

varrow=opts.finder.getRow(_52c,_53d);

opts.onMouseOutRow.call(_52c,e,_53d,row);

  //此处结束

 

 

此处扩展onMouseOverRow事件 ,红框内为要添加的代码.

同上

 

 

12.mybatis里面如何用LIKE模糊查询

有两种方法,建议用第一种

 一,

<iftest="param1.cardNo!=‘‘">

            and CARD_NO LIKE CONCAT(CONCAT(‘%‘,#{param1.cardNo, jdbcType=VARCHAR}),‘%‘)

</if>

 

二,

       <if test="param1.userName!=‘‘">

            USER_NAME like‘%${param1.userName}%‘

        </if>

 

下面我们看看# 和 $ 区别,为什么要用第一种

 

  1. #将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号。如:order by #user_id#,如果传入的值是111,那么解析成sql时的值为order by "111", 如果传入的值是id,则解析成的sql为order by "id".
      
    2. $将传入的数据直接显示生成在sql中。如:order by $user_id$,如果传入的值是111,那么解析成sql时的值为order by user_id,  如果传入的值是id,则解析成的sql为order by id.
      
    3. #方式能够很大程度防止sql注入。
      
    4.$方式无法防止Sql注入。

    5.$方式一般用于传入数据库对象,例如传入表名.
      
    6.一般能用#的就别用$.


    MyBatis排序时使用order by 动态参数时需要注意,用$而不是#


    字符串替换
    默认情况下,使用#{}格式的语法会导致MyBatis创建预处理语句属性并以它为背景设置安全的值(比如?)。这样做很安全,很迅速也是首选做法,有时你只是想直接在SQL语句中插入一个不改变的字符串。比如,像ORDER BY,你可以这样来使用:
    ORDER BY ${columnName}
    这里MyBatis不会修改或转义字符串。
    重要:接受从用户输出的内容并提供给语句中不变的字符串,这样做是不安全的。这会导致潜在的SQL注入攻击,因此你不应该允许用户输入这些字段,或者通常自行转义并检查。

 

 

所以在注重安全的情况下 我们用第一种,防止sql注入.

SpringMVC +mybatis+spring 结合easyui用法及常见问题总结