標籤:style blog color io os ar java for sp
接連以上1到4的struts架構,本次是關於json
因為要用json所以要加組件
載入struts2-json-plugin-2.3.16.3.jar 開啟它的struts-plugin.xml,
會發現<package name="json-default" extends="struts-default">
即它繼承了struts-default,所以struts.xml裡的extends="json-default"
如:
1 struts.xml: 2 3 <package name="news" namespace="/news" extends="json-default"> 4 <action name="newsAction_*" class="action.NewsAction" method="{1}"> 5 <result name="news_list_json" type="json"> 6 <param name="root">newsLsit</param> 7 <param name="excludeNullProperties">true</param> 8 <!-- <param name="excludeProperties"></param> --> 9 <param name="includeProperties">10 <!--json為實體時,直接寫屬性名稱,多個逗號分隔: name,id -->11 <!--list時: \[\d\]相當於一個實體-->12 \[\d\]\.newsId,13 \[\d\]\.newsTitle14 </param>15 </result>16 </action>17 </package>
先瞭解下面幾個的含義
<param name="excludeNullProperties">true</param>排除值為null的
<param name="excludeProperties"></param>json裡包含哪些屬性
<param name="includeProperties"></param>json裡不包含哪些屬性
不是所有的都轉換為json,所以要加限制,即<param name="root">newsLsit</param>
同時在action裡將list聲明為屬性 private List<News> newsLsit;,並且加入set,get方法
代碼:
1 NewsAction.java: 2 3 package action; 4 import java.util.List; 5 import service.NewsService; 6 import com.opensymphony.xwork2.ActionSupport; 7 import entity.News; 8 public class NewsAction extends ActionSupport{ 9 private List<News> newsLsit; 10 private NewsService newsService=new NewsService(); 11 public String findNewsList(){12 newsLsit=newsService.getNewsList(); 13 return "news_list_json";14 }15 16 public List<News> getNewsLsit() {17 return newsLsit;18 }19 public void setNewsLsit(List<News> newsLsit) {20 this.newsLsit = newsLsit;21 } 22 }
各個代碼如下:
展示層:jsp頁面
<form action="/practice_struts2/news/newsAction_findNewsList.action" method="post"> <input type="submit" value="獲得NewsList的json"/> </form>
業務層:service組件和action
service方法:
1 package service; 2 import java.util.List; 3 import dao.NewsDao; 4 import entity.News; 5 public class NewsService extends NewsDao{ 6 public List<News> getNewsList(){ 7 //jdbc,調用dao裡的相應方法 8 return super.findNews(); 9 }10 }
action上面已有NewsAction 代碼
資料訪問層:Dao組件:
省略簡單的實體和dao方法
簡單的struts2架構(五)---json