在struts2的Action中,操作域对象一共有三种方式:
1.ActionContext(与servelt API无关联):
1 //相当于request 2 ActionContext.getContext().put("userName", user.getUserName()); 3 //相当于session 4 ActionContext.getContext().getSession().put("userName", user.getUserName()); 5 //相当于Application 6 ActionContext.getContext().getApplication().put("userName", user.getUserName()); 7 //parameter 8 String name = (String) ActionContext.getContext().getParameters().get("userName");
2.实现ServletRequestAware,ServletResponseAware接口,通过注入的方式,获取request、response:
1 private HttpServletResponse response; 2 3 private HttpServletRequest request; 4 5 @Override 6 public void setServletResponse(HttpServletResponse response) { 7 this.response = response; 8 } 9 10 @Override 11 public void setServletRequest(HttpServletRequest request) { 12 this.request = request; 13 }
3.通过ServletActionContext提供的静态方法获得request、response:
1 HttpServletRequest request = ServletActionContext.getRequest();