歡迎光臨郝學(xué)武的blog。

          JSON實(shí)例(AJAX+STRUTS )

          Posted on 2008-06-02 13:11 陜西BOY 閱讀(14779) 評(píng)論(9)  編輯  收藏

          前段時(shí)間做項(xiàng)目用到了json,今天我抽時(shí)間寫了一個(gè)struts+ajax+json的例子.
          個(gè)人感覺ajax+json在很大程度上降低了網(wǎng)絡(luò)和服務(wù)器的IO,是一個(gè)很不錯(cuò)的組合!
          1:json的lib我用的是json-lib-2.1-jdk15.jar,它可以在
          2:struts用的是1.2
          3:用到了js第三方prototype.js,主要用它包裝的ajax對(duì)象,大家也沒必要用這個(gè),可以直接在js里用XMLHttpRequest。


          以下是例子中所用到的相關(guān)文件:
          /////////////////////////////////////// toolhxw.js
          /**
          @hxw  20080602
          */
          //回調(diào)函數(shù)  簡單回調(diào)函數(shù)
          function showesay(dataResponse)
          {
           var data = eval('(' + dataResponse.responseText + ')');
           var str='';
           str+='<ul>';
           str+='<li>'+data.param1;+'</li>';
           str+='<li>'+data.param2;+'</li>';
           str+='</ul>';
           document.getElementById("content").innerHTML=str;
          }
          //回調(diào)函數(shù)  復(fù)雜回調(diào)函數(shù)
          function showcomplex(dataResponse)
          {
           var data = eval('(' + dataResponse.responseText + ')');
           var str='';
           for(var i=0;i<data.js.length;i++)
           {
           str+='<ul>';
           str+='<li>'+data.js[i].id+'</li>';
           str+='<li>'+data.js[i].age+'</li>';
           str+='<li>'+data.js[i].name+'</li>';
           str+='<li>'+data.js[i].address+'</li>';
           str+='</ul>';
           }
           document.getElementById("content").innerHTML=str;
          }
          //獲取簡單的json數(shù)據(jù)
          function getesay(){
           var url = 'test.do';
            var pars = 'method=getEasy';
            var ajax = new Ajax.Request(
             url,
             {method:'post',parameters:pars,onComplete:showesay}
            );  
          }
          //獲取對(duì)象級(jí)復(fù)雜數(shù)據(jù)
          function getcomplex(){
           var url = 'test.do';
            var pars = 'method=getComplex';
            var ajax = new Ajax.Request(
             url,
             {method:'post',parameters:pars,onComplete:showcomplex}
            );  
          }

          ///////////////////////////////////////struts-config.xml

          <?xml version="1.0" encoding="UTF-8"?>
          <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">

          <struts-config>
            <data-sources />
            <form-beans />
            <global-exceptions />
            <global-forwards />
            <action-mappings >
              <action path="/test" parameter="method" type="com.json.struts.action.TestAction">
             </action>
             
            </action-mappings>

            <message-resources parameter="com.json.struts.ApplicationResources" />
          </struts-config>

           ////////////////////////////////TestAction.java

          /*
           * Generated by MyEclipse Struts
           * Template path: templates/java/JavaClass.vtl
           */
          package com.json.struts.action;

          import java.io.PrintWriter;

          import javax.servlet.http.HttpServletRequest;
          import javax.servlet.http.HttpServletResponse;
          import org.apache.struts.action.ActionForm;
          import org.apache.struts.action.ActionForward;
          import org.apache.struts.action.ActionMapping;
          import org.apache.struts.actions.DispatchAction;
          import net.sf.json.*;

          /**
           * @author hxw
           *
           */
          public class TestAction extends DispatchAction {
           

           /**
            * 獲取簡單組合數(shù)據(jù)
            */
           public ActionForward getEasy(ActionMapping mapping, ActionForm form,
             HttpServletRequest request, HttpServletResponse response) {
            response.setContentType("text/html; charset=GBK");
            try
            {
             PrintWriter out = response.getWriter();
             //這里的數(shù)據(jù)拼裝一般是從數(shù)據(jù)庫查詢來的
             JSONObject jsonObject = new JSONObject();
                jsonObject.put("param1", "變量一");
                jsonObject.put("param2", "變量二");
             out.print(jsonObject.toString());
             out.flush();
             out.close();
             return null;
            }catch(Exception e)
            {
             e.printStackTrace();
             return null;
            }
            }
           /**
            * 獲取復(fù)雜組合數(shù)據(jù)
            */
           public ActionForward getComplex(ActionMapping mapping, ActionForm form,
             HttpServletRequest request, HttpServletResponse response) {
            response.setContentType("text/html; charset=GBK");
            try
            {
             PrintWriter out = response.getWriter();
             JSONObject obj = new JSONObject();
             JSONArray js = new JSONArray();
             //這里的數(shù)據(jù)拼裝一般是從數(shù)據(jù)庫查詢來的
              for(int i=0;i<3;i++)
              {
               JSONObject objtemp = new JSONObject();
               objtemp.put("id", i);
               objtemp.put("age", "23");
               objtemp.put("name", "test"+i);
               objtemp.put("address", "test");
               js.add(objtemp);
              }
             obj.put("js",js);
                   out.print(obj.toString());
            }catch(Exception e)
            {
             e.printStackTrace();
             System.out.print("消費(fèi)明細(xì)json存儲(chǔ)異常");
            }
            return null;
           }
          }

          ////////////////////////////test.jsp
          <%@ page language="java" import="java.util.*" contentType="text/html;charset=gbk"%>
          <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
          <html>
            <head>
              <title>json練習(xí)</title>
             
           <meta http-equiv="pragma" content="no-cache">
           <meta http-equiv="cache-control" content="no-cache">
           <meta http-equiv="expires" content="0">   
           <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
           <meta http-equiv="description" content="This is my page">
           <script type="text/javascript"  src="js/prototype.js"></script>
              <script type="text/javascript"  src="js/toolhxw.js"></script>
              </head>
           
            <body>
            <div id="func" >
            <a href='javascript:getesay()'>獲取簡單組合數(shù)據(jù)</a>
            <a href='javascript:getcomplex()'>獲取復(fù)雜組合數(shù)據(jù)</a>
            </div>
              <div id="content">
              正在獲取內(nèi)容...
              </div>
            </body>
          </html>
          大家將這幾個(gè)文件拷貝到你的myeclipse的web項(xiàng)目中,發(fā)布運(yùn)行即可。

          Feedback

          # re: JSON例子(struts+ajax+json)  回復(fù)  更多評(píng)論   

          2008-06-02 17:00 by 隔葉黃鶯
          請(qǐng)教個(gè)簡單的問題,當(dāng) Java 給 JS 生成的字符串中含有單引號(hào)或雙引號(hào)是如何處理的。

          比如:out.println("var str='"+name+"'");

          name 可能包含單引號(hào)也可能包含雙引號(hào),這個(gè)要交給 js 的輸出一般如何寫的,單引號(hào)或雙引號(hào)怎么轉(zhuǎn)義更簡潔些。

          # re: JSON例子(struts+ajax+json)[未登錄]  回復(fù)  更多評(píng)論   

          2008-06-03 09:12 by 陜西boy
          json里面的數(shù)據(jù)全是鍵-值對(duì),它和java有對(duì)應(yīng)的數(shù)據(jù)類型。比如String,你在數(shù)據(jù)填裝的時(shí)候全是按照java的規(guī)則,json只不過做為一種包裝容器,暫時(shí)把你填裝的東西放進(jìn)來,比如:
          JSONObject jsonObject = new JSONObject();
          jsonObject.put("param1", "\'變量一\"");
          jsonObject.put("param2", "變量二");
          out.print(jsonObject.toString());
          你可以看一下運(yùn)行結(jié)果,和java中的輸出是一模一樣的,也就是說對(duì)于逗號(hào)等操作完全由你的業(yè)務(wù)類負(fù)責(zé),滿足java語法。

          # re: JSON實(shí)例(AJAX+STRUTS )  回復(fù)  更多評(píng)論   

          2008-06-27 15:38 by young.jiandong
          我現(xiàn)在碰到個(gè)問題,照你的代碼改寫我的程序時(shí),如果中文信息是雙數(shù)的話,正常,單數(shù)時(shí),最后一個(gè)字就花了。

          # re: JSON實(shí)例(AJAX+STRUTS )  回復(fù)  更多評(píng)論   

          2008-06-30 16:12 by 陜西BOY
          不會(huì)哪樣的,我剛做了一個(gè)奇數(shù)和偶數(shù)漢字的例子,完全正常,你再看看你是否是其他設(shè)置而引起了這個(gè)問題~~~~~

          # re: JSON實(shí)例(AJAX+STRUTS )  回復(fù)  更多評(píng)論   

          2008-07-01 17:20 by young.jiandong
          我的環(huán)境:tomcat5.5.23,struts1.2(采用了expresso5.5),jdk1.5,采用GBK過濾器。
          頁面:
          var p = $('theId').value;
          var pas = "theId=" + p;
          new Ajax.Request('<html:rewrite page="/util/namelookup.do?state=NameLookup"/>', {
          parameters: pas,
          method:'post',
          //encoding: 'GBK',
          onComplete: function(dataResponse){
          var data = eval('(' + dataResponse.responseText + ')');
          alert(data.fullName);
          $('fullName').value = data.fullName;
          }
          });

          程序處理部分:
          String theId = request.getParameter("theId");
          ServletControllerRequest sr = (ServletControllerRequest) request;
          HttpServletResponse hres = (HttpServletResponse) sr.getServletResponse();
          hres.setContentType("text/html;charset=GBK");
          try{
          String ss = new String(theId.getBytes("GBK"),"UTF-8");
          //到了這步,如果中文信息為單數(shù)時(shí),最后一個(gè)漢字就花了。
          PrintWriter out = hres.getWriter();
          JSONObject json = new com.jsite.json.JSONObject();
          json.put("fullName", "Input : "+ss);
          out.print(json.toString());
          out.flush();
          out.close();
          }catch(Exception e){
          e.printStackTrace();
          }

          # re: JSON實(shí)例(AJAX+STRUTS )  回復(fù)  更多評(píng)論   

          2008-07-01 17:23 by young.jiandong
          不好意思,我沒講明白,我的意思是通過ajax得到提交信息時(shí)才會(huì)出現(xiàn)這個(gè)情況。

          # re: JSON實(shí)例(AJAX+STRUTS )  回復(fù)  更多評(píng)論   

          2008-07-01 17:45 by young.jiandong
          參考 http://blog.csdn.net/zhangyunbo1116/archive/2007/04/29/1589684.aspx ,已解決。
          謝謝。

          # re: JSON實(shí)例(AJAX+STRUTS )[未登錄]  回復(fù)  更多評(píng)論   

          2008-07-21 22:55 by 陜西BOY
          哦,最近忙,沒時(shí)間上blog,解決了就好。

          # re: JSON實(shí)例(AJAX+STRUTS )[未登錄]  回復(fù)  更多評(píng)論   

          2009-03-31 15:41 by dada
          不知道為什么按這么操作在頁面上點(diǎn)了連接他跳不到action里面去

          只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。


          網(wǎng)站導(dǎo)航:
           

          posts - 17, comments - 65, trackbacks - 0, articles - 28

          Copyright © 陜西BOY

          主站蜘蛛池模板: 科技| 察哈| 玉山县| 稻城县| 虹口区| 定州市| 鹤山市| 渭南市| 阿图什市| 禹城市| 岗巴县| 蒲城县| 全椒县| 广饶县| 彭泽县| 贵溪市| 开原市| 鹤庆县| 盐津县| 永康市| 西青区| 扶绥县| 鹿邑县| 乌什县| 金乡县| 顺义区| 新丰县| 台南市| 兴国县| 龙海市| 临泽县| 新巴尔虎右旗| 惠安县| 金昌市| 廉江市| 永定县| 台东县| 思茅市| 望奎县| 清徐县| 桐乡市|