Struts2访问ServletAPI

前言

Servlet API就是HttpServletRequest(Request)、HttpSession(Session)、ServletContext(Application)

通过ActionContext类访问

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
ActionContext ctx = ActionContext.getContext();//单例模式
//访问application
Map<String, Object> application = ctx.getApplication();//Map对象模拟ServletContext实例
application.put("key", value);
Object value = application.get("key");
ctx.setApplication(map);//传入一个新的Map
//访问Session
Map<String, Object> session= ctx.getSession();//Map对象模拟ServletContext实例
application.put("key", value);
Object value = application.get("key");
ctx.setSession(map);//传入一个新的Map
//访问Request
ctx.put("key", value);//类似调用request.putAttribute("key", value)
Object value = ctx.get("key");//类似调用request.getAttribute("key")
Map<String, Object> request = ctx.getParameters();//类似调用request.getParameterMap()

实现XxxAware接口

  1. ServletContextAware :直接访问ServletContext(application) 实例
  2. ServletRequestAware :直接访问HttpServletRequest(request) 实例
  3. ServletResponseAware:直接访问HttpServletResponse(response)实例

通过ServletActionContext类访问

1
2
3
4
PageContext pageContext      = ServletActionContext.getPageContext();
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
ServletContext application = ServletActionContext.getServletContext();