文档章节

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

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

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

喵王不瞌睡
2015/05/02
0
1
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
jquery之DataTables的使用

强大的表格解决方案,有多强大,一起来看下吧: 1、DataTables的默认配置 $(document).ready(function() { $(‘#example’).dataTable(); } ); 示例:http://www.guoxk.com/html/DataTables/...

mickelfeng
2012/11/12
0
1
bootstrap中使用datatables

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

别人说我名字很长
2014/03/28
0
2

没有更多内容

加载失败,请刷新页面

加载更多

学习设计模式——中介者模式

1. 认识中介者模式 1. 定义:用一个中介对象来封装一系列的对象交互行为,中介者使得各对象不需要显式的互相引用,从而使其松散耦合,独立的改变他们之间的交互。 2. 结构: Mediator:中介者...

江左煤郎
26分钟前
0
0
深入理解Plasma(1):Plasma 框架

这一系列文章将围绕以太坊的二层扩容框架,介绍其基本运行原理,具体操作细节,安全性讨论以及未来研究方向等。本篇文章作为开篇,主要目的是理解 Plasma 框架。 Plasma 作为以太坊的二层扩容...

HiBlock
33分钟前
0
0
Java 8 日期 示例

Java 8 推出了全新的日期时间API。Java处理日期、日历和时间的方式一直为社区所诟病,将 java.util.Date设定为可变类型,以及SimpleDateFormat的非线程安全使其应用非常受限。Java也意识到需...

阿刚ABC
59分钟前
1
0
RxJava操作符lift 笔记

在内部,每个Rx operator都做3件事: 它订阅源并观察值。 它根据操作员的目的转换观察到的序列。 它通过调用onNext,onError和onCompleted将修改后的序列推送到自己的订阅者。 compose运算符...

woshixin
今天
1
0
lnmp+coreseek实现站内全文检索(安装篇)

软件安装包 安装环境 系统环境 centos7.2 1核2G 软件环境 coreseek-3.2.14 lnmp1.5 安装mmseg 更新依赖包和安装编译环境 yum -y install m4 autoconf automake libtoolyum -y install gcc g...

毛毛雨rain
今天
1
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部