推薦使用 Struts2 Action 處理 AJAX 請求,無需單獨寫 Servlet。Struts2 內建 JSON 插件或配合 Fastjson/Gson 即可優雅返回數據。
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-json-plugin</artifactId>
<version>2.5.30</version> // 與 struts2-core 版本一致
</dependency>
<package name="ajax" extends="json-default">
<action name="userAjax" class="com.example.UserAction" method="list">
<result type="json">
<param name="root">userList</param> // 要序列化的屬性
<param name="includeProperties">userList\[\d+\]\.(id|name)</param> // 精確控制字段
</result>
</action>
</package>
public class UserAction extends ActionSupport {
private List<User> userList = new ArrayList<>();
public String list() {
userList = userService.findAll();
return SUCCESS; // json-default 會自動序列化 root 對象
}
public List<User> getUserList() { return userList; }
}
public class UserAction extends ActionSupport {
@Autowired private UserService userService;
public void listJson() {
List<User> list = userService.findAll();
String json = JSON.toJSONString(list); // Fastjson
// String json = new Gson().toJson(list); // Gson
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("application/json;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
out.write(json);
} catch (IOException e) {
e.printStackTrace();
}
// 返回 null/void,Struts2 不再查找 result
}
}
<action name="userJson" class="com.example.UserAction" method="listJson">
<!-- 無 result 配置 -->
</action>
| 維度 | JSON Plugin | Fastjson/Gson 手動 |
|---|---|---|
| 配置複雜度 | 需 extends json-default、配置 root/includeProperties | 無需配置 result,極簡 |
| 字段控制 | 靜態配置 includeProperties(正則),動態較難 | 代碼層面完全可控,可根據參數動態過濾 |
| 性能 | 反射序列化,稍慢 | 直接序列化,快 2-3 倍 |
| 異常處理 | 統一由 Struts2 異常攔截器處理 | 需自行 try-catch 寫錯誤 JSON |
| 適用場景 | 簡單 CRUD、字段固定 | 複雜嵌套、動態字段、高併發、需統一錯誤碼格式 |
$.ajax({
url: '${pageContext.request.contextPath}/userJson.action', // 或 .do 視 struts.action.extension
type: 'GET',
dataType: 'json',
success: function(data) {
// data 為數組 [{id:1,name:"Tom"},...]
renderTable(data);
}
});