文档章节

Spring 3 JSON and datatables

lgscofield
 lgscofield
发布于 2015/03/17 20:56
字数 764
阅读 38
收藏 1

Spring 3 JSON and datatables

Don’t you just love JQuery. I’ve been using it with Jquery UI and Datatables.
I played about with some of this stuff (datatables) last year and was impressed with what I’d achieved – fetching tens of thousands of rows of data in a single JSON query – that datatables renders to the screen, makes it fully searchable. Great.
When I originally did this, I used the older style of configuring your Jackson mappers into the view resolver so that you could serve up json out of the request.
After reading about the inbuilt support for JSON in Spring 3, I simplified my spring context. But this meant the data being served back to datatables (which expects your JSON data to be in set format) wasn’t correct. I’ve read a number of blogs and the solution I came up with is a bit of a highbrid.

I don’t have time to outline all this in detail, so I will just post the relevant bits for reference.

Spring Context

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
 
    <!-- Scans the classpath of this application for @Components to deploy as beans -->
    <context:component-scan base-package="com.ubyfish.exampl.mvc" />
 
    <!-- Configures the @Controller programming model -->
    <mvc:annotation-driven />
 
    <!-- Forwards requests to the "/" resource to the "welcome" view -->
    <mvc:view-controller path="/" view-name="welcome"/>
 
    <!-- Configures Handler Interceptors --> 
    <mvc:interceptors>
        <!-- Changes the locale when a 'locale' request parameter is sent; e.g. /?locale=de -->
        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
    </mvc:interceptors>
 
    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources/ directory -->
    <mvc:resources mapping="/resources/**" location="/resources/" />
 
    <!-- Saves a locale change using a cookie -->
    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />
 
    <!-- Application Message Bundle -->
    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="/WEB-INF/messages/messages" />
        <property name="cacheSeconds" value="0" />
    </bean>
 
    <!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
     
    <import resource="controllers.xml" />
 
</beans>

Controller:


@Controller
@RequestMapping(value="/useradm")
public class UserAdminController {
     
     
    ....
     
    /**
    * Fetch a the user list from the service, and package up into a Map that is 
    * compatible with datatables.net
    */
     
    @RequestMapping(method={RequestMethod.POST,RequestMethod.GET} ,value="/fetchtableall")
    public @ResponseBody Map<String, Object[]> findAllForTableView(){
        try{
            Collection<UserBean> users = iamService.listUsers();  
            if (users == null) {
                throw new UserAdminException("Unable to fetch all users - ");
            }
            return Collections.singletonMap("aaData", getJSONForUser(users));
         
        }catch(ServiceException se){
            throw new UserAdminException("Unable to fetch all users  ");
        }
    }
     
    /**
    * I only want certain user info..
    */
    public Object[] getJSONForUser(Collection<UserBean> users){
        Object[] rdArray = new Object[users.size()];
        int i = 0;
        for(UserBean u:users){
            // [ name, id,arn,groups ]
            Object[] us = new String[]{u.getUser().getUserName(),u.getUser().getArn(),groupList(u.getGroups()),u.getUser().getUserId()}; 
            rdArray[i] = us;
            i++;            
        }
        return rdArray;
    }

The key bit in this controller is the @ResponseBody Map – it allows Spring to do it’s JSON magic. In the older world of wiring up your Jackson Mappers in the spring context, you could happily return a ModelAndView :

returnnewModelAndView("fetchall","aaData", getJSONForUser(users));

JSP

<%@ page session="false" %>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html>
<html>
 
<style type="text/css" title="currentStyle">
    @import "resources/styles/redmond/jquery-ui-1.8.20.custom.css";
    @import "resources/styles/demo_page.css"; 
    @import "resources/styles/header.css"; 
    @import "resources/styles/demo_table_jui.css";
    @import "resources/styles/ColReorder.css";
</style>
 
<script type="text/javascript" src="resources/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="resources/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="resources/js/ColReorder.min.js"></script>
 
<script type="text/javascript" src="resources/js/jquery-ui-1.8.20.custom.min.js"></script>
<script type="text/javascript">
 
$(document).ready( function () {
    $('#userinfo').dataTable( {
        "bJQueryUI": true,
        "sDom": '<"H"Tfr>t<"F"ip>',
        "sPaginationType": "full_numbers",
        "bProcessing": true,
        "sAjaxSource": 'useradm/fetchtableall.json',
        "aoColumnDefs": [ { "bVisible": false,  "aTargets": [ 1 ] },
                         {
                           "fnRender": function ( oObj,sVal ) {
                             return '<a href="usradm/fetch?' + sVal + '">edit</a>';
                           },
                           "bUseRendered": false,
                           "aTargets": [ 3 ]
                         }
                       ]  } );
} );    
 
 
....
 
<body id="dt_example">
<div id="container">
    <div class="full_width big">
        user administration
    </div>
 
    <div id="demo">
        <table cellpadding="0" cellspacing="0" border="0" class="display" id="userinfo">
        <thead>
            <tr>
                <th>Name</th>
                <th>Arn</th>
                <th>Groups</th>
                <th>Edit</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
        <tfoot>
            <tr>
                <th>Name</th>
                <th>Arn</th>
                <th>Groups</th>
                <th>Edit</th>
            </tr>
        </tfoot>      
         
        </table>
    </div>
</div>



本文转载自:https://cjbradshaw.wordpress.com/2012/05/31/spring-3-json-and-datatables/

共有 人打赏支持
lgscofield

lgscofield

粉丝 23
博文 140
码字总数 63036
作品 0
南京
架构师
私信 提问
DataTables_详细使用方法

jQuery的DataTables插件的使用方法 ADMIN 2011年11月23日 13:15:45 发布 在做后台的时候并没有美工和前端工程师来配合你做页面,为了显示数据并有一定的美感,我们可以使用jQuery的DataTable...

喵王不瞌睡
2015/05/02
0
1
bootstrap中使用datatables

今天大象研究了下datatables表格,下面来介绍下datatables,我是在bootstrap中使用的,引入必须的JS后就可以开始使用了,首先表格的HTML <div class="row-fluid"> datatables增删改查的实...

别人说我名字很长
2014/03/28
0
2
dataTables-使用详细说明整理

本文共四部分:官网 | 基本使用|遇到的问题|属性表 一:官方网站:[http://www.datatables.NET/] 二:基本使用:[http://www.guoxk.com/node/jQuery-datatables] 1、DataTables的默认配置 $(...

ahl123
07/02
0
0
DataTables 使用配置

一:官方网站:[http://www.datatables.net/] 二:基本使用:[http://www.guoxk.com/node/jquery-datatables] 1、DataTables的默认配置 $(document).ready(function() { $('#example').dataT......

谢锡鹏
2015/01/19
0
0
Datatables + Bootstrap 组合基础示例 2

前言 示例 1 请见[上一篇博文][1]。 示例 2 Datatables 插件使用 Bootstrap 框架的组合示例。 功能 分页 / 排序 / 过滤 / json 数据源 / 数据导出 (需 flash 支持) / 自定义列 / 自定义分页选...

星塵子
2013/05/05
0
1

没有更多内容

加载失败,请刷新页面

加载更多

/etc/profile和/etc/profile.d/的区别

/etc/profile 是文件, /etc/profile.d/ 是目录,用在设置环境变量方面,/etc/profile 文件和 /etc/profile.d/ 目录实现效果是一样的,可根据自己对环境变量配置的需求场景,选择一种最好的方...

calmsnow
2分钟前
0
0
支付系统设计

概述 支付系统是连接消费者、商家(或平台)和金融机构的桥梁,管理支付数据,调用第三方支付平台接口,记录支付信息(对应订单号,支付金额等),金额对账等功能,根据不同公司对于支付业务...

小致dad
3分钟前
0
0
解决Docker Image镜像无法删除问题的方法

前言 Docker是Docker.Inc公司开源的一个基于轻量级虚拟化技术的容器引擎项目,整个项目基于Go语言开发,并遵从Apache 2.0协议。通过分层镜像标准化和内核虚拟化技术,Docker使得应用开发者和运...

临江仙卜算子
6分钟前
0
0
centos 7 redis_install.sh

#!/bin/bashprintf "============开始安装redis\n"printf "============输入redis下载url,按enter默认下载5.0.3版本\n"download_url='';while truedoread download_url...

偶遇一只小仙女
10分钟前
0
0
分布式消息通信ActiveMQ原理-消费消息策略-笔记

消费端消费消息的原理 我们通过上一节课的讲解,知道有两种方法可以接收消息, 一种是使用同步阻塞的MessageConsumer#receive方法。 另一种是使用消息监听器MessageListener。 这里需要注意的...

Java搬砖工程师
12分钟前
0
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部