位置:首頁 > Java技術 > Struts2教學 > Struts2獲取HttpServletRequest實例

Struts2獲取HttpServletRequest實例

在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。

參考

  1. http://struts.apache.org/2.x/docs/how-can-we-access-the-httpservletrequest.htmll
  2. http://struts.apache.org/2.0.6/struts2-core/apidocs/org/apache/struts2/interceptor/ServletRequestAware.htmll