【问题标题】:Adding search field to gson jtable将搜索字段添加到 gson jtable
【发布时间】:2014-08-07 13:32:34
【问题描述】:

我正在尝试在我拥有的 jtable 中的特定列上添加搜索字段。我目前正在使用 gson 来传递 json 数据。这是我的控制器:

public class gsonTestController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public void doPost(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {

   String action = request.getParameter("action");
   if ( action != null) 
   {
        List<Student> studentList = new ArrayList<Student>();

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        response.setContentType("application/json");

        if (action.equals("list")) 
        {
                try
                {                                                                       
                // Add data to Student list
                studentList.add(new Student(1, "Grover", "IT", "xyz@xyz.com"));
                studentList.add(new Student(2, "Bugs Bunny", "ECE", "xyz@gmail.com"));
                studentList.add(new Student(3, "Taz", "MECH", "abc@gmail.com"));
                studentList.add(new Student(4, "Cookie Monster", "ECE", "efg@gmail.com"));
                studentList.add(new Student(5, "Billy the Kid", "CSC", "xyz@gmail.com"));
                studentList.add(new Student(6, "Dustin Hoffman", "CSC", "123@gmail.com"));
                studentList.add(new Student(7, "Obama", "ECE", "789@gmail.com"));
                studentList.add(new Student(8, "Adam Sandler", "ECE", "123@gmail.com"));
                studentList.add(new Student(9, "Pikachu", "IT", "xyz@gmail.com"));

                // Convert Java Object to Json
                String jsonArray = gson.toJson(studentList);

                //Return Json in the format required by jTable plugin
                jsonArray="{\"Result\":\"OK\",\"Records\":"+jsonArray+"}";
                System.out.println(jsonArray);
                response.getWriter().print(jsonArray);
                }
                catch(Exception ex){
                        String error="{\"Result\":\"ERROR\",\"Message\":"+ex.getMessage()+"}";
                        response.getWriter().print(error);
                }                               
                }
            }
         }
}

这会访问 Student.java(基本的 getter/setter 方法),最后将 json 化的数据传递给 jsp 上的以下脚本:

<script type="text/javascript">
        $(document).ready(function() {
                $('#StudentTableContainer').jtable({
                        title : 'Students List',
                        sorting: true,
                        defaultSorting: 'Name',
                        actions : {
                                listAction: 'gsonTestController?action=list',
                                createAction:'gsonTestController?action=create',
                                updateAction: 'gsonTestController?action=update',
                                deleteAction: 'gsonTestController?action=delete'
                        },
                        fields : {
                                studentId : {
                                        title : 'Student Id',
                                        width : '30%',
                                        key : true,
                                        list : true,
                                        create : true
                                },
                                name : {
                                        title : 'Name',
                                        width : '30%',
                                        edit : false
                                },
                                department : {
                                        title : 'Department',
                                        width : '30%',
                                        edit : true
                                },
                                emailId : {
                                        title : 'Email',
                                        width : '20%',
                                        edit : true
                                }
                        }
                });
                $('#StudentTableContainer').jtable('load');
        });
</script>

html 很简单:

<div id="StudentTableContainer"></div>

在阅读过滤器的 jtable 文档时,我找不到任何使用 gson 实现过滤器的示例代码(与 php 或 ASP.NET 等专用服务器端技术相反)。他们的过滤器演示页面位于:http://www.jtable.org/Demo/Filtering

现在,我的控制器暂时只使用硬编码数据,因为我还没有设置数据源。最终,所有数据都将通过 DAO(在 Spring MVC 中)访问。我不熟悉 ASP.NET,但我从页面上的演示中了解到,基本思想是设置变量并根据用户输入的值过滤数据。我只是不确定如何在我当前的结构中进行设置。我通读了 gson 用户指南,但我不确定我需要寻找什么。任何指针都非常感谢。

【问题讨论】:

  • 如果您使用的是spring mvc,那么我建议您使用spring-webmvc 来实现您的控制器。这样,您不必使用 gson,也不必担心读取和写入 json,因为框架会为您完成 - 您只需接受并返回 pojos。
  • @EngineerDollery - 真的吗?你能提供一个解释这个功能的链接吗?我读到的所有内容都告诉我,如果我没有可以处理数据的服务器端技术,我需要使用 Jackson 或 GS​​ON(或类似的)来处理 JSON 数据。
  • 虽然这是一种过时的方法(我们不再真正使用 xml 配置)...journaldev.com/2552/…
  • 一个更新的例子:spring.io/guides/gs/rest-service
  • 使用 spring-webmvc,大多数时候你可以简单地在类路径中使用 jackson,只要你有一个产生或使用 json 的方法,spring 就会为你做翻译。跨度>

标签: java json gson jquery-jtable


【解决方案1】:

所以,在他们的过滤器示例中

//Re-load records when user click 'load records' button.
$('#LoadRecordsButton').click(function (e) {
   e.preventDefault();
   $('#StudentTableContainer').jtable('load', {
      name: $('#name').val(),
      cityId: $('#cityId').val()
   });
});

//Load all records when page is first shown
$('#LoadRecordsButton').click();

您可以看到他们只是使用用户编写的参数重新执行对 URL 的请求,因此您可以做的第一件事就是编辑您的 doPost

String studentName = request.getParameter("studentName");

检查是否通过,并过滤集合 studentList 以仅包含搜索到的学生

if (studentName != null) {
    Iterator<Student> iterator = studentList.iterator();
    while (iterator.hasNext()) {
      if (student.getName().startsWith(studentName)) {
          iterator.remove();
       }
    }
}

(这段代码应该在json序列化之前) (如果你使用 Guava,你可以使用 Iterables.filter 等

这只是一个如何实现过滤器的示例,如果您从数据库中获取数据,则可以使用 SQL 查询过滤数据

现在在studentList 中,您将只拥有提供姓名的学生,无需更改更多代码。

jQuery 代码如下所示

$('#LoadRecordsButton').click(function (e) {
   e.preventDefault();
   $('#StudentTableContainer').jtable('load', {
      studentName: $('#name').val()
   });
});

其中LoadRecordsButton 是单击开始搜索的按钮,StudentTableContainer 是表格,name 是输入名称的输入文本

如果您想手动处理 Json 数据,然后使用 addRecordjTable,您可以避免使用此代码块,但经过一番小搜索后,我发现它有一些问题,所以我会避免它(How to add record to jTable?

【讨论】:

    猜你喜欢
    • 2021-03-04
    • 1970-01-01
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    • 2015-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多