核心代碼
import com.opensymphony.xwork2.ActionContext;
import org.apache.struts2.ServletActionContext;
import javax.servlet.http.HttpServletRequest;
public String getFullRequestUrl() {
HttpServletRequest request = ServletActionContext.getRequest();
// 1. 獲取請求 URI (不含參數) 例:/myapp/user/login
String requestUri = request.getRequestURI();
// 2. 獲取查詢字符串 例:id=100&name=test
String queryString = request.getQueryString();
// 3. 組裝完整路徑
String fullPath = requestUri;
if (queryString != null && !queryString.isEmpty()) {
fullPath += "?" + queryString;
}
// 4. 如需包含協議+域名+端口
// StringBuffer fullUrl = request.getRequestURL(); // 已含協議域名端口+URI
// if (queryString != null) fullUrl.append("?").append(queryString);
// 5. 存入 Session 供後續使用
ActionContext.getContext().getSession().put("PRE_PATH", fullPath);
return fullPath;
}
關鍵 API 對照
| 方法 | 返回示例 | 說明 |
getRequestURI() | /myapp/user/login | 不含協議域名、不含參數 |
getRequestURL() | https://host:8080/myapp/user/login | 含協議域名端口、不含參數 |
getQueryString() | id=100&name=test | 原始查詢字符串 |
getServletPath() | /user/login | 去除 context-path |
常見場景
- 登錄攔截器:保存當前 URL,登錄成功後重定向回原頁
- 審計日誌:記錄用戶完整訪問路徑含參數
- 異常處理:錯誤頁面顯示「返回上一頁」鏈接
注意事項
- 編碼:
getQueryString() 返回 ISO-8859-1 編碼字符串,中文參數需手動 new String(qs.getBytes("ISO-8859-1"), "UTF-8") 或配置 Tomcat URIEncoding="UTF-8"
- 安全:URL 參數可能包含敏感信息(token、密碼),日誌記錄前需脫敏
- Struts2 內建:
ServletActionContext.getRequest() 實際委託給 ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST)