当前位置: 移动技术网 > IT编程>开发语言>Jquery > 用easyui从servlet传递json数据到前端页面的两种方法

用easyui从servlet传递json数据到前端页面的两种方法

2019年09月05日  | 移动技术网IT编程  | 我要评论

用easyui从servlet传递json数据到前端页面的两种方法

 

两种方法获取的数据在servlet层传递的方法相同,下面为servlet中代码,以查询表中所有信息为例。

//重写doget方法
protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
    // todo auto-generated method stub
​
    request.setcharacterencoding("utf-8");//防止request请求时中文数据出现乱码
    string flag = request.getparameter("flag");//通过flag值判定增删改查操作
    if(flag == null) {
        queryoffer(request,response);
    }else if("add".equals(flag)){
        addoffer(request,response);
    }else if("del".equals(flag)) {
        deleteoffer(request,response);
    }else if("update".equals(flag)) {
        updateoffer(request,response);
    }
}
​
//处理从数据库查询到的数据以返回前端
protected void queryoffer(httpservletrequest request, httpservletresponse response) {
    // todo auto-generated method stub
    list<offer> offers = new arraylist<offer>();
    offers = offerservice.queryofferservice();
    try {
        string str=jsonarray.tojsonstring(offers);//将数据库查询到的集合转换成json字符串
        system.out.println(str);
        response.setcontenttype("text/html;charset=utf-8");//防止response时中文数据乱码
        response.getwriter().print(str);//向前台传递字符串
    } catch (exception e) {
        // todo auto-generated catch block
        e.printstacktrace();
    }
}

 

  • 通过easyui包含的table标签中的属性来获取后端传递的数据

    jsp代码:

    • url:传递数据的地址(本篇使用的是servlet,所以路径为servlet路径;也可以使用action或者php)

    • field:传递的json数据的字段名称,就是数据库的字段(列名)

    <table id="dg" title="用户列表" class="easyui-datagrid" style="width:80%;height:250px"
                url="<%=request.getcontextpath() %>/offerservlet"     
                toolbar="#toolbar"
                rownumbers="true" fitcolumns="true" singleselect="true">
            <thead>
                <tr>
                    <th field="offerid" width="50">商品id</th>
                    <th field="offername" width="100">商品名称</th>
                    <th field="offertype" width="200">商品类型</th>
                    <th field="offerdesc" width="200">商品描述</th>
                    <th field="price" width="200">商品价格</th>
                </tr>
            </thead>
        </table>

     

  • 通过js来传递json数据到前端

    jsp代码:

    <table id="dg" title="用户列表" class="easyui-datagrid" style="width:1000px;height:250px" toolbar="#toolbar">
    </table>

     

    js代码:

    • title:显示的表格列名

    $(function(){
        $('#dg').datagrid({
            url:"${pagecontext.request.contextpath}/offerservlet",//servlet路径
            columns:[[
                {field:'offerid',title:'商品id',width:100},
                {field:'offername',title:'商品名称',width:100},
                {field:'offertype',title:'商品类型',width:100},
                {field:'offerdesc',title:'商品描述',width:300},
                {field:'price',title:'商品价格',width:150}
            ]]      
        });
    }); 

     

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网