08 03Struts 2.x與Ajax

1 Struts 2.x與Ajax

如果說現在要想使用Struts 2.x的Action利用異步處理實現數據輸出,那麼必然這個輸出的方法裏面是不應該有返回路徑的,不會跳轉。

如果要處理Ajax建議使用jQuery,將jQuery的開發包配置到項目之中。
範例:建立一個新的Action——CityAction.java


package org.lks.action;

import java.io.IOException;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@SuppressWarnings("serial")
public class CityAction extends ActionSupport{

	public void list(){
		JSONObject all = new JSONObject();
		JSONArray array = new JSONArray();
		for(int i = 0; i < 10; i++){
			JSONObject temp = new JSONObject();
			temp.put("cid", i);
			temp.put("cname", "City我-" + i);
			array.add(temp);
		}
		all.put("citys", array);
		try {
			ServletActionContext.getResponse().getWriter().print(all);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

現在的Action之中只負責了核心操作的處理,當然本次是減少了業務層的使用。
範例:在struts.xml文件中配置

<package name="front" namespace="/pages/front" extends="struts-default">
	<action name="CityAction" class="org.lks.action.CityAction">
	</action>
</package>

此處沒有所謂的跳轉,並且也建立了相應的子目錄。所以這個時候CityAction的完整訪問路徑是/pages/front/CityAction

隨後在頁面之中建立相應的顯示的JS程序。
範例:定義pages/front/city_list.jsp頁面

<%@ page language="java" pageEncoding="UTF-8"%>

<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<html>
<head>
	<base href="<%=basePath%>">
	<meta charset="UTF-8">
	<title>JQuery + Struts 2.x</title> 
	<script type="text/javascript" src="js/jquery-3.5.1.min.js"></script>
	<script type="text/javascript" src="js/city_list.js"></script>
</head>
<body>
	<div id="cityDiv">
		<table border="1" id="cityTab">
			<tr>
				<th>編號</th>
				<th>名稱</th>
			</tr>
		</table>
	</div>
</body>
</html>

隨後的重點就是在city_list.js文件的使用上。
範例:編寫city_list.js文件

$(function(){
	$.post("pages/front/CityAction!list.action",{},function(data){
		for(var i=0; i < data.citys.length; i++){
			$("#cityTab").append("<tr><td>" + data.citys[i].cid + "</td><td>" + data.citys[i].cname + "</td></tr>");
		}
	},"json");
})

以上已經完成了最基本的異步加載操作。

通過本程序可以發現如下需要注意的問題:
(1)路徑的訪問問題,使用完整路徑;
(2)分發處理在Struts 2.x實現很輕鬆;
(3)亂碼問題處理麻煩,主要是因爲Struts 2.x使用過濾器完成處理。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章