開發者習慣在前台頁面傳遞單一 ID,再由後台查詢資料庫取得完整物件,導致程式碼冗餘且效能不佳。期望能直接將前台物件(如表單資料)傳遞至後台 Action。
<a href="action.do?id=123&name=abc&age=20">提交</a>
使用 <form> 以 POST 方式送出,Struts2 會自動將表單欄位對應至 Action 的屬性(或 ModelDriven 物件)。
<form action="saveUser" method="post">
<input type="hidden" name="user.id" value="123"/>
<input type="text" name="user.name" value="張三"/>
<input type="text" name="user.age" value="25"/>
<button type="submit">儲存</button>
</form>
Action 類別:
public class UserAction extends ActionSupport implements ModelDriven<User> {
private User user = new User();
@Override public User getModel() { return user; }
public String save() {
userService.save(user);
return SUCCESS;
}
}
前端以 JSON 格式送出,後端以 @RequestBody 或 Struts2 JSON Plugin 接收。
// JavaScript (jQuery)
$.ajax({
url: 'saveUser',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({id:123, name:'張三', age:25}),
success: function(resp) { console.log('成功'); }
});
雖然「傳 ID 再查 DB」在某些情境下(如資料極大、需權限檢查)仍有其必要性,但對於一般表單提交,直接傳遞物件屬性能大幅簡化代碼並提升可維護性。