Struts2的Action类获取ServletAPI

Struts2中对HttpServletRequest、HttpSession、ServletContext进行了封装解耦,并构造了三个Map对象用于替换列举的对象。


获取方式:

① 通过ActionContext获取(以下获取方式仅获取ServletAPI的域空间,并非真正具体的ServletAPI)

    向Request域空间中放入数据:ActionContext.getContext().put(“req”, “req_value”);

    向Session域空间中放入数据:ActionContext.getContext().getSession().put(“ses”, “ses_value”);

    向Application域空间中放入数据:ActionContext.getContext().getApplication().put(“app”, “app_value”);


② 通过ServletActionContext获取(获取真正具体的ServletAPI)

    向Request域空间中放入数据:ServletActionContext.getRequest().setAttribute(“req”, “req_value”);

    向Session域空间中放入数据:ServletActionContext.getRequest().getSession().setAttribute(“ses”, “ses_value”);

    向Application域空间中放入数据:ServletActionContext.getServletContext().setAttribute(“app”, “app_value”);


③ 通过实现特定接口获取(action类实现RequestAware、SessionAware、ApplicationAware接口)

// 三大成员变量
private Map<String, Object> req;
private Map<String, Object> ses;
private Map<String, Object> app;

// 三大成员属性
public void setRequest(Map<String, Object> request) {
	this.req = request;
}

public void setSession(Map<String, Object> session) {
	this.ses = session;
}

public void setApplication(Map<String, Object> application) {
	this.app = application;
}

public String execute() {
	req.put("req", "req_value");
	ses.put("ses", "ses_value");
	app.put("app", "app_value");
	return "success";
}

猜你喜欢

转载自blog.csdn.net/qq_44965393/article/details/111268695
今日推荐