文档章节

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

粉丝 20
博文 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

没有更多内容

加载失败,请刷新页面

加载更多

下一页

OSChina 周日乱弹 —— 种族不同,禁止交往

Osc乱弹歌单(2018)请戳(这里) 【今日歌曲】 @小小编辑:推荐歌曲《苏菲小姐》- 鱼果 《苏菲小姐》- 鱼果 手机党少年们想听歌,请使劲儿戳(这里) @貓夏:下大雨 正是睡觉的好时候 临睡前...

小小编辑
今天
226
6
Python 搭建简单服务器

Python动态服务器网页(需要使用WSGI接口),基本实现步骤如下: 1.等待客户端的链接,服务器会收到一个http协议的请求数据报 2.利用正则表达式对这个请求数据报进行解析(请求方式、提取出文...

代码打碟手
今天
1
0
Confluence 6 删除垃圾内容

属性(profile)垃圾 属性垃圾的定义为,一个垃圾用户在 Confluence 创建了用户,但是这个用户在自己的属性页面中添加了垃圾 URL。 如果你有很多垃圾用户在你的系统中创建了属性,你可以使用...

honeymose
今天
1
0
qduoj~前端~二次开发~打包docker镜像并上传到阿里云容器镜像仓库

上一篇文章https://my.oschina.net/finchxu/blog/1930017记录了怎么在本地修改前端,现在我要把我的修改添加到部署到本地的前端的docker容器中,然后打包这个容器成为一个本地镜像,然后把这...

虚拟世界的懒猫
今天
1
0
UML中 的各种符号含义

Class Notation A class notation consists of three parts: Class Name The name of the class appears in the first partition. Class Attributes Attributes are shown in the second par......

hutaishi
今天
1
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部