前端有一全局變量 cha = 10,需在 chongChouQu() 中攜帶此值跳轉至 suiJi.action,後端 Struts2 Action 含 private Integer cha 及 Getter/Setter。
var cha = 10;
function chongChouQu() {
window.location = "suiJi.action"; // 如何帶上 cha?
}
function chongChouQu() {
window.location = "suiJi.action?cha=" + encodeURIComponent(cha);
}
後端自動注入:private Integer cha; + getCha()/setCha()
function chongChouQu() {
const form = document.createElement('form');
form.method = 'POST';
form.action = 'suiJi.action';
const input = document.createElement('input');
input.type = 'hidden';
input.name = 'cha';
input.value = cha;
form.appendChild(input);
document.body.appendChild(form);
form.submit();
}
function chongChouQu() {
$.post('suiJi.action', { cha: cha }, function(res) {
if (res.success) window.location = res.redirectUrl;
}, 'json');
}
後端返回 JSON:{success: true, redirectUrl: 'nextPage.action'}
params 會根據請求參數名 cha 調用 setCha(Integer)String → Integercha 保持 null,可通過 validation 攔截器校驗| 現象 | 原因 | 解決 |
|---|---|---|
| 後端 cha 為 null | 參數名不匹配(大小寫、拼寫) | 檢查 name="cha" 與屬性名一致 |
| 類型轉換異常 | 傳了非數字字符串 | 前端 parseInt 或後端自定義 TypeConverter |
| GET 請求中文亂碼 | Tomcat 8+ 默認 ISO-8859-1 | URIEncoding="UTF-8" 或改 POST |
global-exception-mappings 導向友好錯誤頁@Validate 或 XML 驗證,避免髒數據入庫JavaScript 向後端傳值本質是「構造 HTTP 請求參數」。掌握 GET QueryString、POST Form、AJAX JSON 三種載體,配合 Struts2 params 攔截器自動裝箱特性,即可靈活應對各種業務場景。