struts2-通過action從後臺將json集合傳到前臺的方法(一)

本方法通過Struts2的攔截器自動將數據轉換成json數據後傳給頁面。

需要導入的jar包:struts2-json-plugin-2.3.20.jar

前臺jsp頁面:

<table id="dg" title="My Users" class="easyui-datagrid" style="width:700px;height:250px"
       url="get_user"
       toolbar="#toolbar" pagination="true"
       rownumbers="true" fitColumns="true" singleSelect="true">
  <thead>
  <tr>
    <th field="firstname" width="50">First Name</th>
    <th field="lastname" width="50">Last Name</th>
    <th field="phone" width="50">Phone</th>
    <th field="email" width="50">Email</th>
  </tr>
  </thead>
</table>

其中url是action。URL的返回值必須是json類型。

struts.xml配置文件

<package name="b" namespace="/" extends="struts-default">
        <result-types>
                <result-type name="json" class="org.apache.struts2.json.JSONResult"/>
        </result-types>
        <interceptors>
                <interceptor name="json" class="org.apache.struts2.json.JSONInterceptor"/>
                <interceptor-stack name="p1">
                        <interceptor-ref name="defaultStack"/>
                        <interceptor-ref name="json"/>
                </interceptor-stack>
        </interceptors>
        
        <action name="get_user" class="com.action.SyohinGetAction">
                <result type="json">
                        <param name="root">list</param>
                </result>
        </action>
</package>
其中result-type 就是從struts2-json-plugin-2.3.20.jar中引用的。

<action name="get_user" class="com.action.SyohinGetAction">
                <result type="json">
                        <param name="root">list</param>
                </result>
</action>
這個action將list直接轉成json數據。(list在後臺就是java.util.List)

在初始化jsp頁面時會自動調get_user的action顯示內容。

json數據的順序可以與前臺不同,但項目必須一致。

發佈了10 篇原創文章 · 獲贊 6 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章