使用Struts2和jQuery EasyUI實現簡單CRUD系統(三)——ajax,struts2使用json格式的互動
繼上篇:《使用Struts2和jQuery EasyUI實現簡單CRUD系統(二)——ajax與struts2的互動》講了這兩者的互動之後,接下來要通過json的格式進行傳輸資料。
這裡有3中方法:
1、像上篇在最後說的方法,特定內容只要先轉換成json格式後,再發送到頁面,其實不難。
2、用ServletActionContext.getResponse().getWriter().println(content),content的內容為json格式也可以,然後return Action.NONE這種方式也是可以的。
3、使用struts的json外掛程式。
準備好struts2-json-plugin-2.3.16.3.jar包。
還有json格式的轉換類JSONObject包以及所需要的jar包:
本身需要:
但是這部分和struts的包有重複去除掉重複部分即可。
struts.xml中的
在開發的時候最好去掉,一個commons-lang的包忘記匯入之後報了異常跳轉到error頁面讓我根本就不知道哪裡出錯或者報異常了。
其實官方文檔有簡單的例子:
https://struts.apache.org/docs/json-plugin.html
首先是AjaxAction.java
package action;import java.util.HashMap;import java.util.Map;import net.sf.json.JSONObject;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.Action;public class AjaxAction implements Action{private String jsonresult;public String getJsonresult() {return jsonresult;}public void setJsonresult(String jsonresult) {this.jsonresult = jsonresult;}public String json() throws Exception {System.out.println(action execute);Map map = new HashMap();map.put(b,b);System.out.println(map);JSONObject json = null;json = JSONObject.fromObject(map);System.out.println(json);jsonresult = json.toString();System.out.println(jsonresult);return SUCCESS;}@Overridepublic String execute() throws Exception {return null;}}
struts.xml中需要修改一些東西。原來的struts-default改為json-default
result 需要聲明json的type。
/hello.jsp
輸出的結果
原理是怎樣的呢,再改一下AjaxAction。
package action;import java.util.HashMap;import java.util.Map;import net.sf.json.JSONObject;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.Action;public class AjaxAction implements Action{private String jsonresult;private String jsonsecond;private String jsonthird;public String json() throws Exception {System.out.println(action execute);Map map = new HashMap();map.put(b,b);System.out.println(map);JSONObject json = null;json = JSONObject.fromObject(map);System.out.println(json);jsonresult = json.toString();System.out.println(jsonresult);return SUCCESS;}@Overridepublic String execute() throws Exception {return null;}public String getJsonsecond() {return jsonsecond;}public void setJsonsecond(String jsonsecond) {this.jsonsecond = jsonsecond;}public String getJsonresult() {return jsonresult;}public void setJsonresult(String jsonresult) {this.jsonresult = jsonresult;}}
先看輸出結果:
jsonsecond是null,jsonresult是json格式,竟然這兩個都有,jsonthird為什麼沒有,因為沒有相對應的get和set方法結果,jsonsecond是null是因為沒有賦值。
struts就這樣幫你將聲明了的並且具有get、set方法的屬性幫你輸出了。
JSONObject幫你將map對象轉化成json串。
為什麼轉成json串,因為有些前端需求特定的資料格式進行互動,例如後面寫到的EasyUI。
有了前面兩篇的基礎,使用一下struts內建的外掛程式還有JSONObject類就解決了
ajax與struts間使用json資料互動的問題了。