flexigrid报错:org.apache.jasper.JasperException: Unable to initialize TldLocationsCache: null

Jquery flexigrid使用

使用技术:struts2.1.6+spring+hibernate+jquery+flexigrid+thickbox+mysql

主要的js文件:jquery.js,flexigrid.js,query.js,thickbox.js,util.js

 

其中:

util.js是扩展flexigrid的功能,如条件查询用到的getQuery属性。

query.js是自定义的flexigrid界面显示和函数触发文件。

 

Jar包:

 

使用过程:

Struts2 jar只能用 2.1.6,web.xml中配置:

<taglib>

       <taglib-uri>struts-tags</taglib-uri>

       <taglib-location>/WEB-INF/lib/struts2-core-2.1.6.jar</taglib-location>

    </taglib>

 

struts2-core-2.0.14会报错:

org.apache.jasper.JasperException:   Unable   to   initialize   TldLocationsCache:   null

 

Jsp页面:

引入jqueryflexigrid插件文件以及test.jsbody中编写:

<body>

<table id="grid"></table>

</body>   

 

js文件中使用flexigrid创建页面:

$(document).ready( function() {

 

    $("#grid").flexigrid( {

       // url :'jsp/query/json.json',

url : 'getPaginationAction.action',

       dataType :'json',

       colModel : [ {

           display :'编号',

           name :'id',

           width :60,

           sortable :true,

           align :'center'

       }, {

           display :'',

           name :'firstname',

           width :120,

           sortable :true,

           align :'left'

       }, {

           display :'',

           name :'lastname',

           width :120,

           sortable :true,

           align :'left'

       }, {

           display :'操作',

           name :'opt',

           width :120,

           sortable :true,

           align :'left',

           process :operate

       } ],

       searchitems : [ {

           display :'id',

           name :'id',

           isdefault :true

       }, {

           display :'',

           name :'firstname',

           isdefault :true

       }, {

           display :'',

           name :'lastname',

           isdefault :true

       } ],

       // 右下方工具条按钮

       buttons : [ {

           name :'Add',

           bclass :'add',

           displayname :'增加',

           onpress :test,

           separator :true

       }, {

           name :'Delete',

           bclass :'delete',

           displayname :'删除',

           onpress :test

       }, {

           name :'Modify',

           bclass :'modify',

           displayname :'修改',

           onpress :test

       } ],

       sortname :"id",

       sortorder :"asc",

       striped :true,

       usepager :true,

       resizable: true,

       title :'人员管理',

       useRp :true,

       total :10,

       rp :2,

       pagestat :'显示 {from} {to} 条, {total}条记录',

       procmsg :'加载中, 请稍等 ...',

       showTableToggleBtn :true,

       rpOptions : [ 2, 5, 10, 15, 20 ],// 可选择设定的每页结果数

       width :1000,

       height :300,

       getQuery :getQuery

    });

});

 

条件筛选查询时使用的:

Form id=search;

查询按钮的iddosearch:

<input name="" type="button" class="btn-search2" value="查询"

                     id="dosearch" />

 

 

Flexigrid插件中getQuery属性对应页面上部“更多高级选项”处的“查询”,也是点击树形菜单“角色授权”执行过程是相同的。

Manage_list.jsp中页面上部“更多高级选项”处的“查询”id=”dosearch”,

jquery.flexigrid.trace.js插件中

            $('#dosearch').click(function() {g.doSearch();});

doSearch()中使用getQuery,而getQueryflexigrid的一个属性:

doSearch: function() {

              //shoru 添加查询扩展参数

              if(!p.getQuery){

                 p.query="";

              }else{

                 p.query=p.getQuery();

                  p.newp = 1;

                  this.populate();

                }

            }

 

Js/util.js:

/*分页显示辅助函数*/

function getQuery(){

    return getJSONStr('search');

}

Js/util.js中的getJSONStr()函数是将form中的文本框inputname,value装入数组a

function getJSONStr(formId) {

    var a = [];

    // 文本框

    $("#" + formId + " input[type=text]").each(function(i) {

       a.push({

           name : this.name,

           value : this.value

       });

    });

 

 

 

 

点击角色列表中“授权查询”链接执行的

tb_show(caption,url,imageGroup)在插件thickbox.js中定义,其中url中含有几个参数(KeepThis=true&TB_iframe=true等还有对话框大小设置)需要传入,此函数用来弹出一个对话框。

 

 

 

Struts配置 文件:初始显示flexgrid表格

<struts>

    <package name="roleduty" extends="default" namespace="/flexjson">

       <action name="manage_servicetype" class="example.flex.DefaultAction" method="getPagination">

           <param name="queryName">roleduty</param>

 

           <result name="json" type="json">

              <param name="contentType">text/json</param>

              <param name="excludeNullProperties">false</param>

              <param name="root">paginationJson</param>

              <param name="noCache">true</param>

           </result>

           <result name="error" type="json">

              <param name="contentType">text/json</param>

              <param name="excludeNullProperties">false</param>

              <param name="root">jsonResult</param>

              <param name="noCache">true</param>

           </result>

。。。。。。。。。。。。。

</package>

</struts>

对每条记录进行操作

/**

 * 链接每条记录的增删改查

 *

 * @param value

 * @param id

 * @return

 */

function operate(value, pid) {

    return "<a href='javascript:optView(" + pid + ");'>查询</a> "

           + "<a href='javascript:optEdit(" + pid + ")'>编辑</a> "

           + "<a href='javascript:optDelete(" + pid + ")'>删除</a> ";

 

}

 

function optView(id) {

    tb_show(

           "这是查询操作",

           'flexigrid_SelectInitAction.action?model.id='

                  + id

                  + '&KeepThis=true&TB_iframe=true&height=420&width=580&modal=true',

           false);

}

function optEdit(id) {

    tb_show(

           "这是编辑操作",

           'flexigrid_ModInitAction.action?model.id='

                  + id

                  + '&KeepThis=true&TB_iframe=true&height=420&width=580&modal=true',

           false);

}

function optDelete(id) {

    tb_show(

           "这是删除操作",

           'flexigrid_DeleteInitAction.action?model.id='

                  + id

                  + '&KeepThis=true&TB_iframe=true&height=420&width=580&modal=true',

           false);

}

数据及时更新

插入数据后关闭弹出框,主页表格数据要及时刷新,对应于util.jsflexReload()方法:

function flexReload() {

    $("#grid").flexReload();

}

 

#gridflexigridjsp页面的选择符对应。

 

 

Jsp页面上按钮点击刷新父页面后关闭弹出框:

<input name="" type="button" class="btn-canel" value="确定"

onclick="self.parent.flexReload();self.parent.tb_remove();" />

 

条件查询

DefaultAction.javagetPaginatinon()方法中defaultForm.getQuery方法,对应FlexiPaginatinoForm.java,其中设置了几个参数,与jquery.flexigrid.trace.js591行的param参数相同,可自行修改添加。

 

json格式数据写入jsp后在flexigrid表格中显示

Struts.xml配置:

<action name="flexigridAction" class="flexigridGetAllStudentAction"

           method="flexigridShow">

           <result name="input">/login.jsp</result>

           <result name="success">/login_success.jsp</result>

           <result name="error">/login_error.jsp</result>

       </action>

 

 

Action

FlexigridAction.java

public String flexigridShow() {

       String infoString= iStudentBO2.getAllStudent();

       log.info("student studentString: "+infoString);

 

       ActionContext.getContext().getSession().put("stuListString", infoString);

      

       return SUCCESS;

    }

 

Bo

StudentBO2.java使用工具类将Student List转换为json格式:

public String getAllStudent() {

       List studentList = iStudentDAO2.findAll();

       ToJsonType toJsonType=new ToJsonType();

       String string=toJsonType.ListToJsonString(studentList, new HashMap());

       if (studentList != null) {

           return string;

       } else {

           return "";

       }

    }

 

工具类:

/**

     * list类型转变为json类型 <br>

     * {"rows":[{"id":0,"cell":[0,"11","11"]},{"id":1,"cell":[1,"22","22"]}]}

     *

     * @param studentList

     * @param map

     * @return

     */

    public String ListToJsonString(List studentList, Map map) {

 

       List mapList = new ArrayList();

       for (int i = 0; i < studentList.size(); i++) {

           Student s = (Student) studentList.get(i);

           Map cellMap = new LinkedHashMap();

           cellMap.put("id", s.getId());

           cellMap.put("cell", new Object[] { s.getId(), s.getFirstname(),

                  s.getLastname() });

           mapList.add(cellMap);

       }

       map.put("rows", mapList);

       JSONObject jsonObject = new JSONObject(map);

       return jsonObject.toString();

    }

 

 

Dao

StudentDAO2.java是用Hibernate生成:

public List findAll() {

           log.debug("finding all Student instances");

           try {

              String queryString = "from Student";

              return getHibernateTemplate().find(queryString);

           } catch (RuntimeException re) {

              log.error("find all failed", re);

              throw re;

           }

       }

 

Action执行成功后的跳转页面为login_success.jsp,action类中通过session获得已经转换为json格式的字符串,将其显示在jsp页面中,当flexigrid中的url指向flexigridAction.action时执行成功将会跳转到此jsp页面,从而将数据在flexigrid表格中显示【注意:显示json数据的jsp页面中不能有其他标签如<html>等,不然不能显示】:

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%@page import="com.opensymphony.xwork2.ActionContext"%>

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

<%

String s=(String)ActionContext.getContext().getSession().get("stuListString");

response.getWriter().write(s);

%>

 

 

Struts2中数据转换为Json格式

Jar包:Jsonplugin.jarjsonplugin.jar

 

Struts.xml:

<package name="flexigridJson" extends="json-default">

       <action name="getAllStudentJsonAction" class="getAllStudentJsonAction"

           method="getAllStudetJson">

           <result name="jsonres" type="json">

              <param name="contentType">text/json</param>

              <param name="root">studentList </param>

           </result>

       </action>

    </package>

ApplicationContext.xml:

<!-- hibernate dao注入service -->

    <bean id="studentBO2" class="bo.StudentBO2">

    <property name="IStudentDAO2" ref="StudentDAO2"></property>

    </bean>

<!-- json -->

    <bean id="getAllStudentJsonAction" class="action.FlexigridAction">

    <property name="IStudentBO2" ref="studentBO2"></property>

    </bean>

 

 

Action:

private List studentList ;

//get,set方法省略

public String getAllStudetJson() {

       //通过get,set方法和struts.xml中配置root studentListlist类型转换为json格式

       studentList= iStudentBO2.getAllStudent();

 

       log.info(studentList);

       return "jsonres";

    }

 

Flexigridjs中设置url:

$(document).ready( function() {

 

    $(".flex2").flexigrid( {

       // url :'jsp/query/json.json',

       //url :'flexigridAction.action',

       url:'getAllStudentJsonAction.action',

       dataType :'json',

       colModel : [ {

           display :'编号',

           name :'id',

           width :60,

           sortable :true,

           align :'center'

 

显示结果:

 

 

 

 

 

 

 

Struts2返回Json类型,分页显示在flexigrid表中

flexigrid能显示的类型为Map,在BO中加上rows,cell等属性,然后在struts.xml中配置json类型,返回map显示在flexigrid中。

 

条件筛选查询时使用的:

Form id=search;

查询按钮的iddosearch:

<input name="" type="button" class="btn-search2" value="查询"

                     id="dosearch" />

 

Struts.xml中配置json类型

    <!-- 使用json配置显示数据 -->

    <package name="flexigridJson" extends="json-default">

       <action name="getPaginationAction" class="getPaginationAction"

           method="getPagination">

           <result name="jsonres" type="json">

           <param name="root">map</param>

          

           </result>

       </action>

    </package>

applicationContext.xml中配置:

DAO注入BO,BO注入Action

FormBean类:

public class StudentFormBean {

    private Integer id;

    private String firstname;

    private String lastname;

    private Integer total;// 总记录数

    private String query;

    private Integer page;// 当前第page

    private Integer rp;// 每页记录数

    private String sortname;

    private String sortorder;

//省略get,set方法。。。

Action类:

private Map map;

//get,set方法省略

/**

     * 查询所有的student表数据以及条件查询

     *

     * @return

     * @throws Exception

     */

    public String getPagination() throws Exception {

       try {

           // 将条件查询字段所组成的json字符串拆解为Map类型

           String queryString = URLDecoder.decode(studentFormBean.getQuery(),

                  "UTF-8");

           log.info(studentFormBean.getQuery()

                  + "========studentFormBean.getQuery()");

           Map paramMap = new HashMap();

           // 去掉开头结尾的{}

           if (queryString.startsWith("{")) {

              queryString = queryString.substring(1);

           }

           if (queryString.endsWith("}")) {

              queryString = queryString

                     .substring(0, queryString.length() - 1);

           }

           if (!queryString.equals("")) {

 

              String[] pairs = queryString.trim().split("(?<!////)" + ",");

 

              String[] pair;

              for (String onePair : pairs) {

                  if (onePair.contains(":")) {

                     pair = onePair.split("(?<!////):");

                     if (pair.length == 2 && pair[0].trim().length() > 0

                            && pair[1].trim().length() > 0) {

                         paramMap.put(pair[0], pair[1]);

                     }

                  } else {

                     continue;

                  }

              }

           }

           // 将页面formBean以及拆解后的字段Map传给BO处理

           this.map = iStudentBO2.getPagination(studentFormBean, paramMap);

 

           return "jsonres";

       } catch (Exception e) {

           throw new Exception(e);

       }

    }

BO类:

/**

     * 将数据库查询出的Student List转换为Map类型(这样可以通过struts.xml配置的action

     * type="json"使用jsonplugin.jar包自动转换为json格式)

     */

    public Map getPagination(StudentFormBean formBean, Map paramMap) {

       List list = iStudentDAO2.getPagination(formBean, paramMap);

       List mapList = new ArrayList();

       Map map = new LinkedHashMap();

       for (int i = 0; i < list.size(); i++) {

           Student s = (Student) list.get(i);

           Map cellMap = new LinkedHashMap();

 

           cellMap.put("id", s.getId());

           cellMap.put("cell", new Object[] { s.getId(), s.getFirstname(),

                  s.getLastname() });

           mapList.add(cellMap);

       }

       map.put("page", formBean.getPage());// 从前台获取当前第page

       map.put("total", iStudentDAO2.count());// 从数据库获取总记录数

       map.put("rows", mapList);

 

       return map;

    }

DAO类:

    /**

     * 查询数据库表总记录数

     */

    public Long count() {

       try {

           String countString = "select count(*) from Student as s where 1=1 ";

           List list = getHibernateTemplate().find(countString);

           Iterator iter = list.iterator();

           Long count = 0L;

           while (iter.hasNext()) {

              count = (Long) iter.next();

           }

           log.info("count:" + count);

           return count;

 

       } catch (RuntimeException re) {

           throw re;

       }

    }

 

 

    /**

     * 使用条件查询数据库,可以查询所有数据,也可按ID,firstname查询

     */

    public List getPagination(StudentFormBean formBean, Map paramMap) {

 

       StringBuffer sb = new StringBuffer();

 

       sb.append("from Student as s where 1=1");

       if (paramMap.get("id") != null) {

           sb.append(" and s.id="

                  + Integer.parseInt(paramMap.get("id").toString()));

       }

       if (paramMap.get("firstname") != null) {

           sb.append(" and s.firstname='"

                  + paramMap.get("firstname").toString() + "'");

       }

       Session session = getHibernateTemplate().getSessionFactory()

              .openSession();

       Query query = session.createQuery(sb.toString());

       query.setFirstResult((formBean.getPage() - 1) * formBean.getRp());// 从页面获取查询开始数据下标

       query.setMaxResults(formBean.getRp());// 从页面获取每页显示的行数

       List resultList = query.list();

 

       log.info("条件查询字段paramMap:" + paramMap + " sql:" + sb.toString());

 

       return resultList;

    }

输出:

 

Json应该是下面的样式,否则不能显示:

 

 

条件查询:

 

 

 

 

Jquery操作

右下方工具条删除按钮删除单条数据:

获取所选行的id$('.trSelected',grid)[0].id—>得到“row+行号”,

$('.trSelected',grid)[0].id.substr(3)获取到id号,然后将id通过xxx.action?id=123传给action进行删除操作。

 

 

/**

 * buttons右下方工具条按钮

 * @param com

 * @param grid

 * @return

 */

function test(com, grid) {

    if (com == "Delete") {

       if ($('.trSelected', grid).length == 0) {

           alert("请选择要删除的数据");

       } else {

           if (confirm('是否删除这 ' + $('.trSelected', grid).length + ' 条记录吗?')) {

              var id = "";

              for (var i = 0; i < $('.trSelected', grid).length; i++) {

                  if (i == $('.trSelected', grid).length - 1) {

                     id += "id="

                            + $('.trSelected', grid).find("td:first").eq(i)

                                   .text();

                  } else {

                     id += "id="

                            + $('.trSelected', grid).find("td:first").eq(i).text() + "&";

                  }

                  alert("id:" + $('.trSelected', grid)[0].id.substr(3));

                  tb_show(

                         "这是查询操作",

                         // 'flexigrid_DeleteInitAction.action?model.'

                         'deleteStudentByIdAction.action?model.id='

                                + $('.trSelected',grid)[0].id.substr(3)

                                + '&KeepThis=true&TB_iframe=true&height=420&width=580&modal=true',

                         false);

              }

           }

       }

    } else if (com == "Add") {

       // $("#dialog_form input[name=id]")[0].value = "";

       // $("#dialog_div").dialog("open");

       alert("增加。。。。");

 

    }

}

 

点击右下方工具条删除按钮来删除单条数据:

 

阅读更多
个人分类: 编程开发
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭