若是要取得Servlet API 中的一些對象,如request、response或session,在struts2 中能夠有兩種方式得到這些對象:session
① 非IoC(Inversion of Contorl)方式this
HttpServletRequest request = ServletActionContext.getRequest();對象
HttpServletResponse response = ServletActionContext.getResponse();接口
HttpSession session = request.getSession();get
若是你只想訪問session的屬性(Attribute)或添加session的屬性,你能夠經過下面的方式。io
Map session = ActionContext.getContext().getSession();class
session.put("username", "joe");容器
String username = (String)session.get("username");struts2
② IoC方式變量
要使用IoC方式,首先要告訴IoC容器(Container)想要取得摸個對象的意願,經過實現相應的接口作到這點。包括 SessionAware、ServletRequestAware、ServletResponseAware,這樣就能夠在該類中定義對應的變量了。
public class IoCServlet extends ActionSupport implements SessionAware,ServletRequestAware,ServletResponseAware{
private Map att;
private HttpServletRequest request;
private HttpServletResponse response;
public void setSession(Map att){
this.att = att;
}
public void setServletRequest(HttpServletRequest request){
this.request = request;
}
public void setServletResponse(HttpServletResponse response){
this.response = response;
}
public String execute(){ } }