Struts2 中使用注解配置 Action 路徑,重定向時如何傳遞參數?
重定向通常在攔截器或 Action 方法返回結果碼時處理,不在類級注解上硬編碼重定向 URL。
struts.xml 或注解 @Results 中定義重定向結果:
@Action(value = "login", results = {
@Result(name = "success", type = "redirect", location = "/welcome.jsp?user=${username}"),
@Result(name = "error", location = "/login.jsp")
})
${username} 會自動取 Action 的 getUsername() 值(OGNL 表達式)。
public String intercept(ActionInvocation invocation) {
if (!loggedIn) return "loginRedirect"; // 在 struts.xml 定義 loginRedirect 為 redirect 類型
return invocation.invoke();
}
ServletActionContext.getResponse().sendRedirect("/welcome.jsp?user=" + username);
return null; // 告訴框架不再處理結果
@Namespace、@Action 僅定義映射路徑,**不寫死重定向 URL**。${property} 自動注入,避免手動拼接字符串。Struts2 設計哲學:**Action 處理業務返回邏輯結果名,結果視圖決定如何渲染/重定向**。