In Struts 2 , you can use the following two methods to get the HttpServletRequest object.
1. ServletActionContext
Get the HttpServletRequest object directly from org.apache.struts2.ServletActionContext.
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
Make your class implements the org.apache.struts2.interceptor.ServletRequestAware.
When Struts 2 ‘servlet-config‘ interceptor is seeing that an Action class is implemented the
ServletRequestAware interface, it will pass a HttpServletRequest reference to the requested Action class via the
setServletRequest() method.
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; } }
Struts 2 documentation is recommended ServletRequestAware instead of
ServletActionContext.
Reference
- http://struts.apache.org/2.x/docs/how-can-we-access-the-httpservletrequest.html
- http://struts.apache.org/2.0.6/struts2-core/apidocs/org/apache/struts2/interceptor/ServletRequestAware.html
转自:http://www.mkyong.com/struts2/how-to-get-the-httpservletrequest-in-struts-2/