在Struts2中,可以使用以下兩種方法來獲取HttpServletRequest物件。
1. ServletActionContext
直接從 org.apache.struts2.ServletActionContext 獲取 HttpServletRequest 物件。
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
public class LocaleAction{
//business logic
public String execute() {
HttpServletRequest request = ServletActionContext.getRequest();
return "SUCCESS";
}
}
2. ServletRequestAware
讓你的類實現org.apache.struts2.interceptor.ServletRequestAware。
當 Struts2 的 「servlet-config」 攔截器的一個Action類實現ServletRequestAware介面,它會通過一個 HttpServletRequest 的參照請求,通過Action類的setServletRequest()方法完成。
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ServletRequestAware;
public class LocaleAction implements ServletRequestAware{
HttpServletRequest request;
//business logic
public String execute() {
String param = getServletRequest().getParameter("param");
return "SUCCESS";
}
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
public HttpServletRequest getServletRequest() {
return this.request;
}
}
Struts2 文件中建議使用 ServletRequestAware 代替 ServletActionContext。
參考
-
http://struts.apache.org/2.x/docs/how-can-we-access-the-httpservletrequest.htmll
-
http://struts.apache.org/2.0.6/struts2-core/apidocs/org/apache/struts2/interceptor/ServletRequestAware.htmll