简单实现,不用对TMD的一堆的js的api了解,俺还不是js专员,写的太烂,还是java比较贴心啊。
实现流程:页面new Ajax.Request()==》action中获得page对象==》转换为json对象,保存到response中==》在页面中处理返回对象var data = res.responseText.evalJSON();(prototype1.5.1支持)==》调用jstemplate模板引擎对页面进行重组$("output").innerHTML = TrimPath.processDOMTemplate("template_jst", data) ,翻页完成了。
具体代码:
页面请求:
- function ajaxpage(pno){
- var url = "${ctx}/admin/usergroup.do?actionMethod=pageAjaxUser";
- var pars = "pageno="+pno;
- var myAjax = new Ajax.Request(url, {method: 'get', parameters: pars, onComplete: showResult});
- }
- function showResult(res){
- var data = res.responseText.evalJSON();
- $("output").innerHTML = TrimPath.processDOMTemplate("template_jst", data);
- }
action:
- public ActionForward pageAjaxUser(ActionMapping mapping, ActionForm form,
- HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- try {
- String pno = request.getParameter("pageno");
- int pageNo = 1;
- if ( pno != null || !"".equals(pno)){
- pageNo = Integer.parseInt(pno);
- }
- Page page = userManager.query(pageNo, 10);
- Object o = page.getResult();
- if ( o != null ){
- List l = (List)o;
- JSONObject json = new JSONObject();
- json.put("users", ToJSONArray(l));
- json.put("page", ToJSONObject(page));
- saveJSON(response, json);
- }
- } catch (Exception e) {
- logger.error("pageAjaxUser", e);
- }
- return null;
- }
其中对持久化对象装化为jsonobject对象,对list转化为jsonarray对象,保存到response中。
持久化对象转化为jsonObject(类似dwr中对dwr.xml定义),对对象中的set/list只进行第一层转化,再转化容易出现死循环(比如user对象含有roles,roles为role对象聚集,对roles循环处理时,role对象含有users聚集....无限死循环)
- /**
- * 将实体对象转化为json对象(类似dwr中dwr.xml定义文件),对对象中的set,list,map不做处理,容易产生死循环
- */
- protected JSONObject ToJSONObject(Object obj) throws NoSuchFieldException{
- Field[] fields = obj.getClass().getDeclaredFields();
- JSONObject json = new JSONObject();
- for ( int i = 0 ; i < fields.length ; i++){
- Field field = fields[i];
- Object objValue = com.at21.pm.util.BeanUtils.forceGetProperty(obj, field.getName());
- if ( objValue instanceof Collection ){
- if ( objValue != null && !((Collection)objValue).isEmpty()){
- Collection col = (Collection)objValue;
- JSONArray jsarray = new JSONArray();
- for (Iterator iter = col.iterator(); iter.hasNext();) {
- Object element = iter.next();
- Field[] efields = element.getClass().getDeclaredFields();
- JSONObject jsonobj = new JSONObject();
- for( int j=0;j<efields.length;j++){
- Field efield = efields[j];
- Object evalue = com.at21.pm.util.BeanUtils.forceGetProperty(element, efield.getName());
- if ( !(evalue instanceof Collection || evalue instanceof Map
- || evalue instanceof Object[] || evalue instanceof Clob
- || evalue instanceof Blob )){
- // logger.debug("=====>"+field.getName() + " <> " + efield.getName()+" <> "+ evalue);
- if ( evalue instanceof Date ){
- if ( evalue == null ){
- evalue = "";
- }else{
- SimpleDateFormat formate = new SimpleDateFormat("yyyy-MM-dd");
- evalue = formate.format(evalue);
- }
- }
- jsonobj.put(efield.getName(), evalue);
- }
- }
- jsarray.add(jsonobj);
- }
- json.put(field.getName(), jsarray);
- }
- }else if (!(objValue instanceof Collection || objValue instanceof Map || objValue instanceof Object[]
- || objValue instanceof Clob || objValue instanceof Blob)) {
- //logger.debug("=====>"+field.getName()+" <> "+ objValue);
- if ( objValue instanceof Date ){
- if ( objValue == null ){
- objValue = "";
- }else{
- SimpleDateFormat formate = new SimpleDateFormat("yyyy-MM-dd");
- objValue = formate.format(objValue);
- }
- }
- json.put(field.getName(), objValue);
- }
- }
- return json;
- }
将list转化为jsonarray
- /**
- * 将Collection转换为json对象
- */
- protected JSONArray ToJSONArray(Collection c) throws NoSuchFieldException{
- JSONArray jsarray = new JSONArray();
- for (Iterator iter = c.iterator(); iter.hasNext();) {
- Object object = iter.next();
- if (object instanceof Map) {
- Map map = (Map) object;
- JSONObject jsonobj = new JSONObject();
- for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();) {
- Map.Entry entry = (Map.Entry) iterator.next();
- jsonobj.put(entry.getKey(), entry.getValue());
- }
- jsarray.add(jsonobj);
- }else{
- JSONObject jsobj = ToJSONObject(object);
- jsarray.add(jsobj);
- }
- }
- return jsarray;
- }
最后是保存json对象
- /**
- * 保存JSON到respose中
- */
- protected void saveJSON(HttpServletResponse response,JSONObject object){
- logger.debug("JSONObject:"+object);
- response.setContentType("text/html");
- response.setCharacterEncoding("utf-8");
- try {
- PrintWriter pw = response.getWriter();
- pw.print(object);
- pw.flush();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
页面处理返回对象
- var data = res.responseText.evalJSON();
- $("output").innerHTML = TrimPath.processDOMTemplate("template_jst", data);
jstemplate脚本模版(需要对jstemplate.js修改下,将标示符号$替换成#,否则与好多东西冲突的不成了,比如说jstl),我将尖括号变成*了
- *textarea name="template_jst" id="template_jst" style="display:none;"*
- *table width="90%" border="0" align="center" cellpadding="5" cellspacing="0" class="table6"*
- *tr class="td1" *
- *td**fmt:message key="list.number" /**/td*
- *td**fmt:message key="userReg.usernameCN" /**/td*
- *td*E-mail*/td*
- *td**fmt:message key="userReg.usernameCN" /**/td*
- */tr*
- {var varName = 1}
- {for user in users}
- *tr {if varName%2 == 0} {cdata} class="td1" {/cdata}{/if}*
- *td**input type="checkbox" value="#{user.id}" id="ids" οnclick="addUser(this,'#{user.id}','#{user.usernameCN}')"* #{varName++ }*/td*
- *td*#{user.usernameCN}*/td*
- *td*#{user.email}*/td*
- *td*#{user.createdate}*/td*
- */tr*
- {forelse}
- *tr **td colspan="4"*No find*/td**/tr*
- {/for}
- *tr align="center" *
- *td colspan="4"*共#{page.totalCount}条 第#{page.currentPageNo}/#{page.totalPageCount}页
- {if page.hasPreviousPage}*input type="button" value="上一页" οnclick="ajaxpage(#{page.currentPageNo-1})"*{/if}
- {if page.hasNextPage}*input type="button" value="下一页" οnclick="ajaxpage(#{page.currentPageNo+1})"*{/if}*/td*
- */tr*
- */table*
- */textarea*