Struts2返回json

來源:互聯網
上載者:User

標籤:type   註解   格式   add   mode   root   param   plugin   eth   

<span style="font-size:18px;">package com.insuper.action;import com.insuper.service.UserService;import com.insuper.vo.User;import com.opensymphony.xwork2.ActionSupport;import com.opensymphony.xwork2.ModelDriven;/** * 注冊使用者 *  * @author seawind *  */public class UserAction extends ActionSupport implements ModelDriven<User> {private String re;private User user = new User();@Overridepublic User getModel() {return user;}public String getRe() {return re;}public void setRe(String re) {this.re = re;}public String register() throws Exception {System.out.println("注冊使用者 action 運行... ");userService.addUser(user);this.re="使用者注冊成功";return SUCCESS;}private UserService userService;public void setUserService(UserService userService) {this.userService = userService;}}</span>

這是以使用者注冊為例。須要注意的是一定要有傳回值。不能用void方法。否則無法進入Struts攔截器

<span style="font-size:18px;"><package name="default" namespace="/" extends="json-default"><!-- 方式一,自己主動向Action 裝配 Service --><action name="register" class="com.insuper.action.UserAction"method="register"><result type="json"><param name="root">re</param></result></action></span>
這裡須要注意extends="json-default"
<result type="json"><!-- 這裡指定將被Struts2序列化的屬性,該屬性在action中必須有相應的getter方法 --><!-- 預設將會序列全部有傳回值的getter方法的值,而不管該方法是否有相應屬性 --><param name="root">dataMap</param><!-- 指定是否序列化空的屬性 --><param name="excludeNullProperties">true</param><!-- 這裡指定將序列化re中的那些屬性 --><param name="includeProperties">userList.*</param><!-- 這裡指定將要從re中排除那些屬性,這些排除的屬性將不被序列化,一般不與上邊的參數配置同一時候出現 --><param name="excludeProperties">SUCCESS</param></result>
須要注意的是,假設用JSON外掛程式把返回結果定為JSON。

而JSON的原理是在ACTION中的get方法都會序列化,所曾經面是get的方法僅僅要沒指定不序列化,都會運行。假設該方法一定要命名為get*(比方實現了什麼介面),那麼能夠在該方法的前面加註解聲明該方法不做序列化。

註解的方式為:@JSON(serialize=false)除此之外。JSON凝視還支援例如以下幾個域:serialize:設定是否序列化該屬性deserialize:設定是否還原序列化該屬性。format:設定用于格式化輸出、解析日期表單域的格式。

比如"yyyy-MM-dd‘T‘HH:mm:ss"。//使用凝視文法來改變該屬性序列化後的屬性名稱@JSON(name="newName")public String getName(){return this.name;}須要引入 import com.googlecode.jsonplugin.annotations.JSON;@JSON(serialize=false)public User getUser() {return this.User;}@JSON(format="yyyy-MM-dd")public Date getStartDate() {return this.startDate;}






Struts2返回json

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.