关于struts2访问servlet API一共有三种方式:
1.通过ActionContext接口去访问,例如以下代码:
ActionContext context=ActionContext.getContext(); //此时context相当于request对象
context.getApplication().put(key,value); //获取Application并插入值
context.getSession.put(key,value); //获取session值并插入值
缺点:虽然这种方法可以访问其API但是无法访问其实例
2.通过特定接口访问API元素
特定接口分别为:ServletRequestAware; ServletResponseAware; ServletContextAware;例如如下代码:
public class Demo2ServletAction extends ActionSupport implements ServletRequestAware{
private HttpServletRequest request;
@Override
public String execute() throws Exception {
request.setAttribute("gf", "request_aware");
return SUCCESS;
}
@Override
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
}
第三种方式是通过使用ServletActionContext工具类(此方式虽好,但与servlet api耦合)例如如下代码:
public class Demo1ServletAction extends ActionSupport{
@Override
public String execute() throws Exception {
ServletActionContext.getRequest().setAttribute("gf", "request");
return SUCCESS;
}
}
缺点:此方式虽好,但与servlet api耦合