1.开发环境
1.1 Struts2框架相关jar包
1.2 json-lib-2.2.3-jdk15.jar
1.3 jquery.dataTables.min.js版本为1.10.8和jQuery相关js
2.编写目的
将DataTables插件与Struts2交互变得更简单易用,代码整洁化!
3.核心代码
3.1 前端封装DataTables插件的相关js代码
datatables-pack.js
/**
*处理DataTable的数据
*公共部分
*/
var DataTablePack = function(){
//汉化分页条
var language = {
paginate:{
first:'首页',
last:'末页',
previous:'上一页',
next:'下一页'
},
lengthMenu:'显示 _MENU_ 条',
zeroRecords:'没有检索到有效数据!',
info:'显示 _START_ 到 _END_ 条记录',
infoEmpty:'没有检索到有效数据!',
search:'查找:',
processing:'正在加载数据,请稍候...',
infoFiltered:'共计 _TOTAL_ 条记录'
}
/* 全选以及选中效果功能 */
function checkAll(table){
//全选功能
table.find('.checkall').change(function () {
var allCheck = table.find('tbody input[type=checkbox]');
if(jQuery(this).is(":checked")){
allCheck.each(function(){
jQuery(this).attr('checked',true);
jQuery(this).parent().addClass('checked'); //used for the custom checkbox style
});
}else{
allCheck.each(function(){
jQuery(this).attr('checked',false);
jQuery(this).parent().removeClass('checked'); //used for the custom checkbox style
});
}
});
//选中效果
table.on('change', 'tbody tr .check', function () {
$(this).parents('tr').toggleClass("active");
if(jQuery(this).is(":checked")){
jQuery(this).attr('checked',true);
jQuery(this).parent().addClass('checked');
}else{
jQuery(this).attr('checked',false);
jQuery(this).parent().removeClass('checked');
}
});
// table.parent().parent().find('.dataTables_length select').addClass("form-control input-xsmall input-inline"); // modify table per page dropdown
}
/** 公开调用方法 **/
var DataTablePublic = {
/* 处理处理静态数据 */
baseTable:function(table){
var oTable = table.dataTable({
'language':language,//汉化工具条
'lengthMenu':[10,20,30,50,100],//显示每页大小的下拉框中的选项
'dom': "<'row' <'col-md-12'T>><'row'<'col-md-6 col-sm-12'f><'col-md-6 col-sm-12'l>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>", // horizobtal scrollable datatable
'pagingType':'full_numbers',//分页样式
'columnDefs':[{
'targets':[0,1],
'orderable':false
}],//默认列参数
"order":[
[2, "asc"]
] //默认排序的列
});
checkAll(table);//全选功能
return oTable;
},
/* 即时后台获取数据*/
serverTable:function(table,url,reqData,columns,startNum){
//alert(url);
var oTable = table.dataTable({
'ajax':{
dataType:'json',
/////contentType:'application/json',
type:'post',//更改Ajax的请求方式
url:url,//从一个ajax数据源读取数据给表格内容
data:function(aoData){
reqData['dtJson'] = JSON.stringify(aoData);
return reqData;
},
//data:'{"username":"admin","userpwd":"123456"}',
error:function (resp){
alert(JSON.stringify(resp));
}//添加额外的参数发送到服务器
},
'serverSide':true,//是否开启服务器模式
'stateSave':true,//保存状态 - 在页面重新加载的时候恢复状态(页码等内容)
'processing':true,//当表格处在处理过程(例如排序)中时,启用或者禁止 'processing'指示器的显示。
'displayStart':startNum,//初始化显示的时候从第几条数据开始显示(一开始显示第几页)
'columns':columns,
'language':language,//汉化工具条
'lengthMenu':[10,20,30,50,100],//显示每页大小的下拉框中的选项
'dom': "<'row' <'col-md-12'T>><'row'<'col-md-6 col-sm-12'f><'col-md-6 col-sm-12'l>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>", // horizobtal scrollable datatable
'sPaginationType':'full_numbers',//分页显示所有按钮
'columnDefs':[{
'targets':[0,1],
'orderable':false
}],//默认列参数
"order":[
[2, "asc"]
] //默认排序的列
});
checkAll(table);//全选功能
return oTable;
}
};
return DataTablePublic;
}();
jQuery(document).ready(function(){
var table = jQuery('#protable');
var columns = [
{
'data':null,
'render':function(data,type,full){
var content = '';
content += '';
content += '';
return content;
}
},
{'data':'name'},
{'data':'url'},
{'data':'descmark'},
{'data':'logopath'},
{'data':'role_type'},
{
'data':null,
'render':function(data,type,full){
var content = '';
content += ' Edit ';
return content;
}
}
];
var reqData = {"menu.name":"admin","menu.url":"123456"};
DataTablePack.serverTable(table,'manage/menuajaxShow.action',reqData,columns,1);
});
3.3.1 DataTables.java
package llcrm.base.action.datatables;
import java.util.ArrayList;
import java.util.List;
/**
* Class:DataTables
* Description: DataTables插件参数对象
* @author XQL
* @Date 2015年9月9日 下午5:40:33
*/
public class DataTables {
//请求传递参数
private int draw = 0;
private List columns = new ArrayList();
private List order = new ArrayList();
private int start;
private int length;
private Search search = new Search();
//相应传递参数
private Object data;
private int recordsTotal = 0;
private int recordsFiltered = 0;
public int getDraw() {
return draw;
}
public void setDraw(int draw) {
this.draw = draw;
}
public List getColumns() {
return columns;
}
public void setColumns(List columns) {
this.columns = columns;
}
public List getOrder() {
return order;
}
public void setOrder(List order) {
this.order = order;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public Search getSearch() {
return search;
}
public void setSearch(Search search) {
this.search = search;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public int getRecordsTotal() {
return recordsTotal;
}
public void setRecordsTotal(int recordsTotal) {
this.recordsTotal = recordsTotal;
}
public int getRecordsFiltered() {
return recordsFiltered;
}
public void setRecordsFiltered(int recordsFiltered) {
this.recordsFiltered = recordsFiltered;
}
@Override
public String toString() {
return "DataTables [draw=" + draw + ", columns=" + columns.get(0).toString() + ", order=" + order.get(0).toString() + ", start=" + start
+ ", length=" + length + ", search=" + search + ", data=" + data + ", recordsTotal=" + recordsTotal
+ ", recordsFiltered=" + recordsFiltered + "]";
}
}
package llcrm.base.action.datatables;
/**
* Class:Columns
* Description: 包装DataTables字段信息
* @author XQL
* @Date 2015年9月9日 下午6:10:23
*/
public class Columns {
private String data;
private String name;
private boolean searchable;
private boolean orderable;
private Search search;
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isSearchable() {
return searchable;
}
public void setSearchable(boolean searchable) {
this.searchable = searchable;
}
public boolean isOrderable() {
return orderable;
}
public void setOrderable(boolean orderable) {
this.orderable = orderable;
}
public Search getSearch() {
return search;
}
public void setSearch(Search search) {
this.search = search;
}
@Override
public String toString() {
return "Columns [data=" + data + ", name=" + name + ", searchable=" + searchable + ", orderable=" + orderable
+ ", search=" + search.toString() + "]";
}
}
3.3.3 Order.java
package llcrm.base.action.datatables;
/**
* Class:Order
* Description: 包装DataTables排序信息
* @author XQL
* @Date 2015年9月9日 下午6:11:17
*/
public class Order {
private int column;
private String dir;
public int getColumn() {
return column;
}
public void setColumn(int column) {
this.column = column;
}
public String getDir() {
return dir;
}
public void setDir(String dir) {
this.dir = dir;
}
@Override
public String toString() {
return "Order [column=" + column + ", dir=" + dir + "]";
}
}
3.3.4 Search.java
package llcrm.base.action.datatables;
/**
* Class:Search
* Description: 包装DataTables查询信息
* @author XQL
* @Date 2015年9月9日 下午6:11:54
*/
public class Search {
private String value;
private boolean regex;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public boolean isRegex() {
return regex;
}
public void setRegex(boolean regex) {
this.regex = regex;
}
@Override
public String toString() {
return "Search [value=" + value + ", regex=" + regex + "]";
}
}
注意:这里利用了struts2的自定义类型转换器
DataTablesConvert.java
package llcrm.base.action.convert;
import java.util.HashMap;
import java.util.Map;
import com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter;
import llcrm.base.action.datatables.Columns;
import llcrm.base.action.datatables.DataTables;
import llcrm.base.action.datatables.Order;
import net.sf.json.JSONObject;
/**
* Class:DataTablesConvert
* Description: 将前端的DataTables插件转为Datatables对象
* @author XQL
* @Date 2015年9月9日 下午5:39:39
*/
public class DataTablesConvert extends DefaultTypeConverter{
@Override
@SuppressWarnings("rawtypes")
public Object convertValue(Map context, Object value, Class toType){
String json = ((String[])value).length > 0 ? json = ((String[])value)[0] : "";
System.out.println("|-00-|"+json);
DataTables dt = null;
if(toType == DataTables.class){
JSONObject jsonobj = JSONObject.fromObject(json);
Map clsMap = new HashMap();
clsMap.put("columns", Columns.class);
clsMap.put("order", Order.class);
dt = (DataTables)JSONObject.toBean(jsonobj,DataTables.class,clsMap);
System.out.println("|-01-|"+dt.toString());
}
return dt;
}
}
3.5 配置文件以及后端调用DataTables的参数,以及各种应用
BaseAction-conversion.properties
dtJson = llcrm.base.action.convert.DataTablesConvert
BaseAction.java
package llcrm.base.action;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.util.ServletContextAware;
import com.opensymphony.xwork2.ActionSupport;
import llcrm.base.action.datatables.DataTables;
public class BaseAction extends ActionSupport implements ServletRequestAware,ServletResponseAware, ServletContextAware{
private static final long serialVersionUID = -7588102526595752037L;
public HttpServletRequest request;
public HttpServletResponse response;
public ServletContext context;
private DataTables dtJson;
public DataTables getDtJson() {
return dtJson;
}
public void setDtJson(DataTables dtJson) {
this.dtJson = dtJson;
}
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
public void setServletResponse(HttpServletResponse response) {
this.response = response;
}
public void setServletContext(ServletContext context) {
this.context = context;
}
}
AdminMenuAction.java
package llcrm.admin.action;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import llcrm.base.action.BaseAction;
import llcrm.base.action.datatables.Columns;
import llcrm.base.action.datatables.Order;
import llcrm.entity.Lc_AdminMenu;
import llcrm.service.Lc_AdminMenuService;
@Controller("adminMenuAction")
@Scope("prototype")
public class AdminMenuAction extends BaseAction {
private static final long serialVersionUID = 1L;
private Lc_AdminMenuService lc_AdminMenuService;
public Lc_AdminMenu menu;
public String gotoPage(){
return "page";
}
public String ajaxShow(){
System.out.println(menu.getName()+"|||"+menu.getUrl());
System.out.println("查询:");
System.out.println("检索条件:"+super.getDtJson().getSearch().getValue());
System.out.println("检索条件是否匹配正则表达式:"+super.getDtJson().getSearch().isRegex());
System.out.println("排序:");
for(Order ord : super.getDtJson().getOrder()){
List cols = super.getDtJson().getColumns();
System.out.println("排序字段:"+cols.get(ord.getColumn()).getData());
System.out.println("排序方式:"+ord.getDir());
}
List list = new ArrayList();
for(int i=0;i<10;i++){
Lc_AdminMenu lc_menu = new Lc_AdminMenu();
lc_menu.setDescmark("descmark"+i);
lc_menu.setId(i);
lc_menu.setLogopath("logopath"+i);
lc_menu.setName("name"+i);
lc_menu.setParent(null);
lc_menu.setRole_type(i);
lc_menu.setUrl("url"+i);
list.add(lc_menu);
}
super.getDtJson().setData(list);
super.getDtJson().setRecordsFiltered(20);
super.getDtJson().setRecordsTotal(100);
return "json";
}
public Lc_AdminMenu getMenu() {
return menu;
}
public void setMenu(Lc_AdminMenu menu) {
this.menu = menu;
}
}