标签:
在struts的Action中,有三种方法可以得到request、session、servletContext域。
HttpServletRequest request = ServletActionContext.getRequest(); HttpSession session = request.getSession(); ServletContext servletContext = ServletActionContext.getServletContext(); //操作 request.setAttribute("request_data","request_data_servlet"); session.setAttribute("session_data","session_data_servlet"); servletContext.setAttribute("servletcontext_data","servletcontext_data_servlet");
ActionContext context = ActionContext.getContext(); Map<String, Object> request = context.getContextMap(); Map<String, Object> session = context.getSession(); Map<String, Object> application = context.getApplication(); //操作 request.put("request_data","request_data_struts"); session.put("session_data","session_data_struts"); application.put("servletcontext_data","servletcontext_data_struts");
public class DataAction extends ActionSupport implements RequestAware,
SessionAware,ApplicationAware{ Map<String,Object> request; Map<String,Object> session; Map<String,Object> application; public String execute()throws Exception{ request.put("request_data","request_data_注入"); session.put("session_data","session_data注入"); application.put("servletcontext_data","servletcontext_data_注入"); return SUCCESS; } @Override public void setRequest(Map<String, Object> map) { this.request = map; } @Override public void setApplication(Map<String, Object> map) { this.application = map; } @Override public void setSession(Map<String, Object> map) { this.session = map; } }
方法1:使用servlet API,需要额外引入servlet包,但是可以调用getContextPath()等对象方法;
方法2:struts方式,使用解耦的方式实现对数据的操作,不需要引入额外的包,但是只能设置和获取值;
方法3:比较复杂,但是可以在优化时使用;
方法2需要使用ActionContext对象获取其他域,ActionContext无法放在构造函数中初始化。而方法3使用动态注入的方式获取其他域对象,一旦Action对象创建,域值也存在了。
标签:
原文地址:http://www.cnblogs.com/juaner767/p/5524399.html