对数据操作的3种方法(把数据保存到域中):
方式1:直接获取servletApi
核心类:ServletActionContext提供的静态方法
/** * 方式1:拿到servletApi,执行操作 */ HttpServletRequest request = ServletActionContext.getRequest(); // 拿到request对象 HttpSession session = request.getSession();
// 拿到session对象
方式2:通过ActionContext类获取不同(代表 request/session/application)的map
/** * * 方式2:通过ActionContext类: [解耦的方式实现对数据的操作] */ ActionContext context = ActionContext.getContext(); // 得到Struts对HttpServletRequest对象进行了封装,封装为一个map Map<String, Object> request1 = context.getContextMap(); // 拿到request对象的map Map<String, Object> session2 = context.getSession(); // 拿到session对象map Map<String, Object> application = context.getApplication(); // 拿到servletContext对象的map
方式3:通过实现接口的方式(RequestAware, SessionAware, ApplicationAware):
public class Struts_dataDemo1 extends ActionSupport implements RequestAware, SessionAware, ApplicationAware private Map<String, Object> application; private Map<String, Object> session; private Map<String, Object> request; /** * Struts运行时,会把application的map对象注入 * * @param arg0 */ public void setApplication(Map<String, Object> application) { this.application = application; } /** * Struts运行时,会把session的map对象注入 * * @param arg0 */ public void setSession(Map<String, Object> session) { this.session = session; } /** * Struts运行时,会把request的map对象注入 * * @param arg0 */ public void setRequest(Map<String, Object> request) { this.request = request; }