Struts2存在一个东西ActionContext(素质是Map),,可以获得原生的request,response,ServletContext
还可以获得四大域东西(Map),以及param参数(Map)等等
ActionContext生命周期:每次请求城市创建一个与请求对应的ActionContext东西
绑定当前线程(ThreadLocal),直接从ThreadLocal中获得即可
请求措置惩罚惩罚完后,ActionContext东西销毁
第一种获得方法:
public String execute() throws Exception { //request域=> map (struts2并不保举使用原生request域) //不保举 Map<String, Object> requestScope = (Map<String, Object>) ActionContext.getContext().get("request"); //保举 ActionContext.getContext().put("name", "requestTom"); //session域 => map Map<String, Object> sessionScope = ActionContext.getContext().getSession(); sessionScope.put("name", "sessionTom"); //application域=>map Map<String, Object> applicationScope = ActionContext.getContext().getApplication(); applicationScope.put("name", "applicationTom"); return SUCCESS; }
注意:直接挪用put要领在jsp中取值时候直接取即可${name},其他的(例如session):${sessionScope.name}
第二种获取方法(不保举):
//不保举 public String execute() throws Exception { //原生request HttpServletRequest request = ServletActionContext.getRequest(); //原生session HttpSession session = request.getSession(); //原生response HttpServletResponse response = ServletActionContext.getResponse(); //原生servletContext ServletContext servletContext = ServletActionContext.getServletContext(); return SUCCESS; }
看过源码发明,这里还是挪用了ActionContext中的要领
不保举的原因:Struts2缔造的目的就是制止原生的servlet
第三种:
实现接口
package api; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.interceptor.ServletRequestAware; import com.opensymphony.xwork2.ActionSupport; //如安在action中获得原生ServletAPI public class Demo extends ActionSupport implements ServletRequestAware { private HttpServletRequest request; public String execute() throws Exception { System.out.println("原生request:"+request); return SUCCESS; } @Override public void setServletRequest(HttpServletRequest request) { this.request = request; } }
response等等都是实现相应的接口即可
道理:servletConfig拦截器的intercept要领中获取了原生的servletAPI,素质上还是挪用了ActionContext中的要领
实际开发中,常用的其实是第一种方法