struts2和Jquery EasyUI整合数据查询(DataGrid)

最近在项目中很爱偷懒,于是用Jquery EasyUi处理分页,省去了要处理的分页参数信息。相比ExtJsEasyUi的体积还是小多了,上手也容易多了;再相比Jquery UI,就不用说了,压根就没有DataGird

准备工作:

Struts2类库:

Json类库:

 

 

 

Jquery EasyUI

 

 

 

当然还包括Jqueryjs库:

 

 

 

 

 

 

 

 

 

 

 

先看后台的类设计图:

 

 

 

 

 

 

 

 

 

看着挺多,其实写起来挺简单,本来可以用泛型把所有业务统一起来,但struts2对泛型有bug(不知道现在的版本解决没),当实例化泛型类时,一半概率会报ClassCastException。而且初学者看着一堆的泛型、抽象类、抽象方法很容易晕,所以用此设计,故不用原来的设计,这样做保证了代码安全稳定,付出的代价是写了不少重复代码。

 

前台页面:

orderlist.jsp

 

要包括的ui:

<link rel="stylesheet" type="text/css" href="<s:url value="/ui/themes/default/easyui.css"/>">

 

<link rel="stylesheet" type="text/css" href="<s:url value="/ui/themes/icon.css"/>">

 

<script type="text/javascript" src="<s:url value="/js/jquery-1.4.2.min.js"/>">script>

 

<script type="text/javascript" src="<s:url value="/ui/jquery.easyui.min.js"/>">script>

 

<script type="text/javascript" src="<s:url value="/ui/easyui-lang-zh_CN.js"/>">script>

我用的是绝对路径,用的struts2s:url标签,所以不要忘了引入struts2的标签库

<%@taglib prefix="s" uri="/struts-tags"%>

 

以上是在页面头包引入的库

 

真正的代码在下面:

 

<body>

    <table id="dataGrid">table>

body>

 

就这么一点点

 

当然,还要在一开始做初始化,以下代码直接在head标签内接着上面引入库后写就行。

 

<script type="text/javascript">

$(function(){

       //这个#dataGrid一定要和以上tableid对应

           $('#dataGrid').datagrid({

               title:'订单查询',

               width:910,

               height:400,

               nowrap: false,

               striped: true,

               collapsible:false,

               url:'',

               remoteSort: true,

               idField:'id',

               loadMsg:'装载中...',

               columns:[[

                   {field:'id',title:'订单号',width:50,align:'center'},

                   {field:'lastName',title:'',width:60,align:'center'},

                   {field:'firstName',title:'',width:60,align:'center'},

                   {field:'roomName',title:'房型名称',width:130,align:'center'},

                   {field:'roomNum',title:'订房数量',width:50,align:'center'},

                   {field:'orderDate',title:'下单日期',width:110,align:'center'},

                   {field:'liveDate',title:'住店日期',width:80,align:'center'},

                   {field:'leaveDate',title:'离店日期',width:80,align:'center'},

                   {field:'price',title:'总价格',width:100,align:'center'},

                   {field:'opt',title:'操作',width:95,align:'center',

                            formatter:function(value,rec){

                                return "查看  删除";

                            }

                   }

               ]],

               pagination:true,

               rownumbers:false

       });

 

    //其实上面就够了,下面纯属为了手动改dataGrid页脚下那些分页参数的label显示

       var p = $('#dataGrid').datagrid('getPager');

       if (p){

           $(p).pagination({

               beforePageText:"",

               afterPageText:"{pages}",

               displayMsg:"{total}条记录"

           });

       }

   });

script>

 

看到代码应该不用解释了吧,很简单,看着字段名就知道怎么设置

 

 

QueryAction.java:

public abstract class QueryAction extends ActionSuppot

{

 

    /**

     *

     */

    private static final long serialVersionUID = -3068675701440713082L;

 

    // easyUI前台传过来的请求页数,故必须以此命名,当然你也可以不这样,但set方法必须是setPage

    private int page;

    // easyUI前台传过来的请求记录数,故必须以此命名,原因同上

    private int rows;

    // easyUI前台传过来的排序字段,故必须以此命名,原因同上

    private String sort;

    // easyUI前台传过来的排序方式(desc?asc),故必须以此命名,原因同上

    private String order;

 

    @Override

    public abstract String execute() throws Exception;

 

    public int getPage()

    {

       return page;

    }

 

    public void setPage(int page)

    {

       this.page = page;

    }

 

    public int getRows()

    {

       return rows;

    }

 

    public void setRows(int rows)

    {

       this.rows = rows;

    }

 

    /**

     * @return the sort

     */

    public String getSort()

    {

       return sort;

    }

 

    /**

     * @param sort

     *            the sort to set

     */

    public void setSort(String sort)

    {

       this.sort = sort;

    }

 

    /**

     * @return the order

     */

    public String getOrder()

    {

       return order;

    }

 

    /**

     * @param order

     *            the order to set

     */

    public void setOrder(String order)

    {

       this.order = order;

    }

 

}

 

OrderQueryAction:

public class OrderQueryAction extends QueryAction

{

 

    /**

     *

     */

    private static final long serialVersionUID = -2113641189213286787L;

 

    // 查询条件

    private OrderQueryConditon condition;

 

    // 返回页面的json对象

    private JSONObject result;

 

    // 这是service,请根据自己具体实际情况修改

    private RoomService roomTypeService;

 

    // 这是查询条件的KEY,每次查询把查询条件放session里面

    public static final String ORDER_QUERY_KEY = "order_query_key";

 

    @Override

    public String execute() throws Exception

{

// 防止空指针,暂时做的很差劲的处理

        if (condition == null)

        {

            condition = new OrderQueryConditon();

        }

       // 设置前台传来的排序字段和排序方式

        condition.setSortObj(new SortObject(getSort(), getOrder()));

        // 图里面提到的,主要是转换一些特殊字段,如Date时进行处理的配置

JsonConfig config = new JsonConfig();

        config.registerJsonValueProcessor(Date.class,

                new RoomTypeJsonValueProcessor());

       // 设置我自己封装的JsonBean对象

        JsonBean jsonDb = roomTypeService.queryOrderList(condition,

                getPage(), getRows());

 

        json.setRows(jsonDb.getRows());

        json.setTotal(jsonDb.getTotal());

      

       // 这就是为什么要封装JsonBean的原因,一步转化成Json对象

        result = JSONObject.fromObject(json, config);

 

        ServletActionContext.getRequest().getSession().setAttribute(

                ORDER_QUERY_KEY, condition);

 

        return SUCCESS;

    }

 

    /**

     * @return the result

     */

    public JSONObject getResult()

    {

        return result;

    }

 

    /**

     * @param result

     *            the result to set

     */

    public void setResult(JSONObject result)

    {

        this.result = result;

    }

 

    public OrderQueryConditon getCondition()

    {

        return condition;

    }

 

    public void setCondition(OrderQueryConditon condition)

    {

        this.condition = condition;

    }

 

    public RoomService getRoomTypeService()

    {

        return roomTypeService;

    }

 

    public void setRoomTypeService(RoomService roomTypeService)

    {

        this.roomTypeService = roomTypeService;

    }

}

顺带提一下上面代码出现的RoomTypeJsonValueProcessor,其实就是对Date进行处理

RoomTypeJsonValueProcessor.java

public class RoomTypeJsonValueProcessor implements JsonValueProcessor

{

 

    public Object processArrayValue(Object arg0, JsonConfig arg1)

    {

       return null;

    }

 

    public Object processObjectValue(String key, Object value, JsonConfig arg2)

    {

        if (key.equals("dateBegin"))

        {

            return DateUtil.getDateStr((Date) value);

        }

 

        if (key.equals("dateEnd"))

        {

            return DateUtil.getDateStr((Date) value);

        }

       

        if (key.equals("liveDate"))

        {

            return DateUtil.getDateStr((Date) value);

        }

 

        if (key.equals("leaveDate"))

        {

            return DateUtil.getDateStr((Date) value);

        }

        if (key.equals("orderDate"))

        {

            return DateUtil.getDateStr((Date) value,"yyyy-MM-dd HH:mm:ss");

        }

 

       return value;

    }

 

}

 

JsonBean的用处上面很明确了,用了泛型:

JsonBean.java:

 

public class JsonBean

{

    private int total;

 

    private List rows;

 

    public int getTotal()

    {

       return total;

    }

 

    public void setTotal(int total)

    {

       this.total = total;

    }

 

    public List getRows()

    {

       return rows;

    }

 

    public void setRows(List rows)

    {

       this.rows = rows;

    }

 

    /**

     * 计算当前页开始记录

     *

     * @param pageSize

     *            每页记录数

     * @param currentPage

     *            当前第几页

     * @return 当前页开始记录号

     */

    public static int countOffset(final int pageSize, final int currentPage)

    {

       final int offset = currentPage == 0 ? 0 : pageSize * (currentPage - 1);

       return offset;

    }

 

}

 

 

QueryCondition主要用在后台底层查值时传递参数

QueryCondition.java:

public class QueryCondition

{

    private SortObject sortObj;

   

    /**

     * @return the sortObj

     */

    public SortObject getSortObj()

    {

       return sortObj;

    }

 

    /**

     * @param sortObj the sortObj to set

     */

    public void setSortObj(SortObject sortObj)

    {

       this.sortObj = sortObj;

    }

 

}

 

OrderQueryConditon具体业务的查询条件

OrderQueryConditon.java:

 

public class OrderQueryConditon extends QueryCondition

{

 

    private Date dateBegin;

 

    private Date dateEnd;

 

    private String roomTypeId;

 

    private Integer roomNum;

 

    public Date getDateBegin()

    {

        return dateBegin;

    }

 

    public void setDateBegin(Date dateBegin)

    {

        this.dateBegin = dateBegin;

    }

 

    public Date getDateEnd()

    {

        return dateEnd;

    }

 

    public void setDateEnd(Date dateEnd)

    {

        this.dateEnd = dateEnd;

    }

 

    public String getRoomTypeId()

    {

        return roomTypeId;

    }

 

    public void setRoomTypeId(String roomTypeId)

    {

        this.roomTypeId = roomTypeId;

    }

 

    public Integer getRoomNum()

    {

        return roomNum;

    }

 

    public void setRoomNum(Integer roomNum)

    {

        this.roomNum = roomNum;

    }

 

 

   

}

 

SortObject就两字段

SortObject.java:

public class SortObject

{

    private String sortName;

   

    private String sortType;

   

   

 

    public SortObject(String sortName, String sortType)

    {

       super();

       this.sortName = sortName;

       this.sortType = sortType;

    }

 

    public SortObject()

    {

       super();

    }

 

    /**

     * @return the sortName

     */

    public String getSortName()

    {

       return sortName;

    }

 

    /**

     * @param sortName the sortName to set

     */

    public void setSortName(String sortName)

    {

       this.sortName = sortName;

    }

 

    /**

     * @return the sortType

     */

    public String getSortType()

    {

       return sortType;

    }

 

    /**

     * @param sortType the sortType to set

     */

    public void setSortType(String sortType)

    {

       this.sortType = sortType;

    }

   

   

}

 

还有struts的配置文件:

<action name="queryOrder" class="action.OrderQueryAction">

            <result type="json">

                <param name="root">resultparam>

            result>

        action>

这里action配置一定要和前台请求的url一致

到此为止,列表查询是没问题了,但实际需求往往还要加入条件查询,其实上面后台代码已经加入了条件查询的部分,只是前台没有加入,可以如下加入条件:

 

 

在查询按钮的onclick事件调用以下函数

 

function query (){

// 获取查询参数

var queryParams = $('#dataGrid').datagrid('options').queryParams;

       var roomNum = $.trim($("#condition.roomNum").val());

       // condition对应action的实例变量condition

       queryParams["condition.roomNum"] = roomNum;

       // 重置查询页数为1

       $('#dataGrid').datagrid('options').pageNumber = 1;

       var p = $('#dataGrid_queryYmjtcy').datagrid('getPager');

       if (p){

           $(p).pagination({

              pageNumber:1

           });

       }

       // 刷新列表数据

       $('#dataGrid_queryYmjtcy').datagrid('reload');

    }

 

 

 

 

 

 

 

 

你可能感兴趣的:(struts2和Jquery EasyUI整合数据查询(DataGrid))