当前位置: 首页 > 教程 > Struts2 >

Struts2获取HttpServletRequest实例

精华
小牛编辑
209浏览
2023-03-14
在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