一、準備好jar包,不要小看這一步,萬事開頭難。。總結起來有以下三種搭配。
1. xwork-core-2.1.6.jar和struts2-json-plugin-2.1.8.jar。如果你想使用struts2-json-plugin-2.1.8.jar這種支援方式,你的xwork-core-*.jar不能選擇2.2.1及以上版本,因為xwork-core-*.jar的2.2.1及以上版本中沒有了org.apache.commons.lang等包。啟動tomcat的時候會出現:java.lang.NoClassDefFoundError: org.apache.commons.lang.xwork.StringUtils。
2. xwork-2.1.2.jar和jsonplugin-0.34.jar。如果想用jsonplugin-0.34.jar這種支援方式,那需要切換你的xwork-core-*.jar為xwork-2.1.2.jar。因為jsonplugin-0.34.jar需要com.opensymphony.xwork2.util.TextUtils
這個類的支援。而xwork-core-*.jar的2.2.1以上版本均為找到該類,且在xwork-core-2.1.6.jar中也沒有該類。
3 .struts2.3.7的版本,適合struts2-json-plugin-2.3.4.1.jar與json-lib-2.3-jdk15.jar
二、下面看下action是啥吧。
public String editProblem(){question=(Question) this.getSession().get("QUESTION_INFO");this.pid=String.valueOf(question.getId());question.setContent(this.newContent);question.setModifyDateTime(this.getCurrentDate());showProblemsLogic.updateProblem(question);//更新資料庫記錄return SUCCESS;}
很簡單,是個編輯問題的方法,筆者正在做一個互動問答平台,使用者在提問之後,還可以編輯自己的問題。
上面就是實現這個功能的action代碼。可以注意到,這個action裡面有很多屬性,struts.xml可以這樣寫。
<action name="editProblem" class="problemsAction" method="editProblem"> <result name="input">/problems.jsp</result> <result type="json"> <param name="includeProperties">newContent</param> </result> </action>
includeProperties這個參數的配置對應的是下面這段ajax提交代碼中的success回呼函數中的data,如果data需要更多的內容,則可以在includeProperties參數裡面添加更多的屬性。 這個參數的配置很關鍵,配置錯了,success回呼函數就不會執行了,所以一定要注意。
三、再來看下ajax函數是怎麼寫的吧
<script>$(document).ready(function(){ $("#edit_content_button").click(function() { var params = $("#edit_form").serialize();//講指定表單中的參數轉換為查詢字串//使用jQuery中的$.ajax({});Ajax方法$.ajax({url:"editProblem",//這個是對應的action名稱type:"POST",data:params,dataType:"json",success:function(data){ajax請求提交成功後的回呼函數$("#qcontent").css("display","none");$("#newqContent").empty();$("#newqContent").append(data.newContent);$('#edit_form').toggle();alert("修改成功。");},error:function(data){alert(arguments[1]);}}); });});</script>
這樣,整合就算初具規模了,可以實現在struts2下,頁面無重新整理的表單提交了~