在 Struts2、Spring、Hibernate 整合環境中,可利用 jQuery Ajax 呼叫後端 Action,完成即時帳號驗證。前端在輸入框失去焦點時,先檢查格式,再送出非同步請求。
Action 透過 JSON 外掛回傳結果。若 Action 中注入 Service 物件,建議使用 @JSON(serialize=false) 避免序列化非必要屬性,否則可能造成 Ajax 回傳錯誤。
@JSON(serialize=false)
public StudentControl getStudentControl() {
return studentControl;
}
Struts 設定中,action 需繼承 json-default,並指定 result type 為 json。
前端使用 bind() 處理 focus 與 blur,在 blur 時驗證格式,再呼叫 loginAjax。可加入隨機參數避免快取影響非同步結果。
$.ajax({
url: "loginAjax",
dataType: "json",
data: { username: $(this).val(), time: Math.random() * 1000 },
success: function (data) { alert("成功" + data.username); },
error: function () { alert("錯誤"); }
});
此做法能提升表單驗證的即時性,但正式環境仍應加入後端驗證與安全性檢查。