简体   繁体   English

如何将java bean传递到jsp页面以便jqQrid使用json显示?

[英]how to pass java beans to jsp page for jqQrid to display using json?

we are trying to use jqGrid with our jsp front end and java back end. 我们正在尝试将jqGrid与我们的jsp前端和java后端一起使用。

this page is displaying a grid of contacts : 此页面显示联系人网格:

jQuery(document).ready(function(){ 
  jQuery("#list").jqGrid({
    datatype: 'json',
    url:'gridContactDrv.jsp',
    mtype: 'GET',
    height:300,
    width:600,
    colNames:['First Name','Last Name', 'Company', 'Primary Phone','Email'],
    colModel :[ 
      {name:'firstname', index:'firstname', width:100}, 
      {name:'lastname', index:'lastname', width:100 }, 
      {name:'company', index:'company', width:100}, 
      {name:'phone', index:'phone', width:100 }, 
      {name:'email', index:'email', width:200}
    ],
    pager: '#pager',
    rowNum:10,
    rowList:[10,20,30],
    sortname: 'lastname',
    sortorder: 'desc',
    viewrecords: true
  }); 
});

gridContactDrv.jsp calls a search function which return a Vector of ContactBeans. gridContactDrv.jsp调用一个搜索函数,该函数返回一个ContactBeans的Vector。 In our current (old) way, we loop through the vector, hook out the 5 fields in each bean and contruct a HTML table. 以我们当前的(旧的)方式,我们遍历向量,勾勒出每个bean中的5个字段并构造一个HTML表。

now we want to use json and i can't figure out how to contruct a valid json (obect? array?) to pass to the grid. 现在我们要使用json,但我不知道如何构造有效的json(对象?数组?)以传递到网格。

Enumeration e = resultVector.elements();
    while (e.hasMoreElements()) 
    {
        ContactBean c = ContactBean((ContactBean)e.nextElement());
        c.getCompany() 
            c.getFirstName() etc etc and what to do?
        }

btw the ContactBean has many other data members but we are only displaying the 5 fields. 顺便说一句,ContactBean还有许多其他数据成员,但我们只显示5个字段。

can someone give me some pointers to start? 有人可以给我一些指导吗? i have searched for a few days and feel like not getting anywhere. 我搜索了几天,感觉好像什么都没到。

Have you looked at the JSONWriter class from json.org ? 您是否看过json.org的JSONWriter类

Quoting from the API docs : 引用API文档

  new JSONWriter(myWriter) .object() .key("JSON") .value("Hello, World!") .endObject(); 

which writes 哪个写

  {"JSON":"Hello, World!"} 

You need to: 你需要:

  1. Configure your jqGrid instance to expect JSON data 配置您的jqGrid实例以期望JSON数据
  2. Have something (servlet?) on back-end that would handle JSON request. 在后端有一些可以处理JSON请求的(servlet?)。 You could, of course, output grid data as JSON in the same JSP that renders jqGrid but that would largely defeat the purpose (especially for large volumes of data if pagination is involved). 当然,您可以在呈现jqGrid的同一JSP中以JSON格式输出网格数据,但这将大大超出其目的(尤其是涉及分页时,对于大量数据而言)。
  3. Use JSON library like json-lib to marshall your beans into JSON. 使用json-lib之类的JSON库将您的bean编组为JSON。 I personally like XStream but there are many various implementations available. 我个人喜欢XStream,但有许多可用的实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM