網頁

2009年4月14日 星期二

Strus2 json plugin + jquery.getJSON()

Struts2其中之一的優點,是可以直接擴充別人寫好的plugin,簡化自己動手做的步驟。以下是簡單的範例。

Step 1:
請將基本strtus2環境架設完畢。

Step 2:
下載strus2 json plugin,放置於 %WEBROOT%/WEB-INF/lib/ 中
連結:http://cwiki.apache.org/S2PLUGINS/json-plugin.html
(官網有很詳盡的說明,建議有空看看)

Step 3:
編輯struts.xml,加入以下資訊...
<result-types>
 <result-type name="json" class="com.googlecode.jsonplugin.JSONResult">
 </result-type>
</result-types>

請注意,若你的struts.xml已經新增了其他的result-type,那麼請直接將內的xml加入你的result-types中即可。

step 4:
宣告欲使用json result的action於strtus.xml中..
<action name="JsonAction" class="tw.foo.JsonAction">
 <result name="success" type="json">
  <param name="contentType">text/html</param>
 </result>
</action>

(設定contentType為text/html,可以讓你利用瀏覽器進行debug)

step 5:
撰寫action...
package tw.foo;

import java.util.*;
import com.opensymphony.xwork2.ActionSupport;

public class JsonAction extends ActionSupport{
 private List<map<string,string>> li = null;
 public String execute() throws Exception{
  li = new ArrayList<map<string, string>>();
  Map<string, string> map = new Hashtable<string, string>();
  map.put("name", "Jay");
  map.put("age", "28");
  li.add(map);
  map = new Hashtable<string, string="">();
  map.put("name", "Jolin");
  map.put("age", "27");
  map.put("skill", "dance");
  li.add(map);
  return SUCCESS;
 }

 public List<map<string, string>> getMyList(){
  return li;
 }
}



Step 6:
現在,你可以在瀏覽器打開action測試,會出現如下json資訊...

{"myList":[{"age":"28","name":"Jay"},{"skill":"dance","age":"27","name":"Jolin"}]}


Step 7:
現在開始用jquery對json資訊進行處理,jsp範例如下:
<%@ page language="java" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
  <script type="text/javascript" src="js/jquery-1.3.2.js"></script>
  <script type="text/javascript">
  $(document).ready(function(){
    $.getJSON("JsonAction.action", function(json){
    var table = "<table border='1' cellpedding='1'>";
      table+="<thead><tr><th>name</th><th>age</th><th>skill</th></tr></thead>";
      table += "<tbody>";
      for(i = 0; i < json.myList.length; i++){
        table += "<tr>";
        table += "<td>" + json.myList[i].name + "</td>";
        table += "<td>" + json.myList[i].age + "</td>";
        table += "<td>" + json.myList[i].skill + "</td>";
        table += "</tr>";
      }
      table += "</tbody></table>";
      $('#jsonresult').html(table);
    });
  });
  </script>
 </head>
 <body>
   <div id="jsonresult">test</div>
 </body>
</html>



Step 8:
恭喜完成!看看你的頁面是不是如下所示:

nameageskill
Jay28undefined
Jolin27dance

沒有留言:

張貼留言