In Struts 2 , you can use the following two methods to get the HttpServletRequest object.However
Struts 2 documentation is recommended second method ServletRequestAware instead of ServletActionContext.
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 theServletRequestAware 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://www.mkyong.com/struts2/how-to-get-the-httpservletrequest-in-struts-2/
No comments:
Post a Comment