問題:
通過ajax訪問action,value stack中沒有任何的數據。原因未知,可能是因爲ajax請求跟普通的http請求還是有區別的,不會把所有的信息都返回回來吧。如果有知道的,歡迎告訴我啊!!解決方案:
1.將需要返回的信息封裝到request\session中。2.將返回的信息通過json的格式返回。這裏主要說一下第二種。
解決步驟:
1. 引入struts2-spring-plugin包
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-spring-plugin</artifactId>
<version>${struts2.version}</version>
</dependency>
2. struts中配置 <result name="success" type="json"></result>
在實驗的過程中發現,如果action中有多個屬性,如User user,String str...等,返回的json字符串並不完全,只是其中一個的。如:
返回的json串爲{'name':'11','code':'22'...}。即只是把material這個屬性給轉換爲json字符串了,而str丟失了。private Material material; private String str;
這個問題的解決方案:把所有方案整合到一個map中。
private Map<String, Object> resultMap = new HashMap<String, Object>(); /** * @return the resultMap */ public Map<String, Object> getResultMap() { return resultMap; } /** * @param resultMap * the resultMap to set */ public void setResultMap(Map<String, Object> resultMap) { this.resultMap = resultMap; }
然後讓struts將resultMap轉換爲json,需要配置如下<result name="success" type="json"> <param name="root">resultMap</param> </result>
3. 通過interceptor處理resultMap(當然這一步可以省略,如果你不嫌麻煩,每個action中的方法都多resultmap處理)
@Override
public String intercept(ActionInvocation invocation) throws Exception {
String msg = Action.SUCCESS;
// 對所有的方法進行攔截,並把結果放到resultMap中
Object action = invocation.getAction();
Method getMethod = action.getClass().getMethod("getResultMap");
@SuppressWarnings("unchecked")
Map<String,Object> resultMap = (Map<String, Object>) getMethod.invoke(action);
try{
resultMap.put("result", Action.SUCCESS); // 這個必須得寫在invoke之前
msg = invocation.invoke();
}catch(Exception e){
resultMap.put("result", Action.ERROR);
resultMap.put("message", e.getMessage());
}
Method setMethod = action.getClass().getMethod("setResultMap", Map.class);
setMethod.invoke(action, resultMap);
return msg;
}
這裏遇到一個問題,弄了半天------到現在也沒搞明白,估計跟action的new時機以及其屬性的創建時機有關係,有知道的請指教啊
resultMap.put("result", Action.SUCCESS); // 這個必須得寫在invoke之前
如果大家對struts2和ajax的整合有更好的方式,歡迎指出啦。
參考:http://blog.csdn.net/zhqingyun163/article/details/5208766