0%

struts2访问web资源

Struts2访问web资源

有两种方式

  • 和Servlet Api解耦的方式 只能访问有限的Servlet Api对象(读取请求参数,读取域对象属性,使用session等)
    • 使用ActionContext
    • 实现XxxAware
  • 和Servlet Api耦合的方式,可以使用更多的Servlet Api对象,且可以调用原生方法
    • 使用ServletActionContext
    • 实现ServletXxxAware接口

解耦的方式

使用ActionContext

1
2
3
4
5
6
7
8
ActionContext actionContext = ActionContext.getContext();
// 获取application对应的map
Map<String,Object> application = actionContext.getApplication();
// 获取seesion对应的map
Map<String,Object> session = actionContext.getSession();
// 获取request对应的map
Map<String,Object> request = (Map<String, Object>) actionContext.get("reuqest");

使用XxxAware

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class TestAwareAction implements ApplicationAware, SessionAware, RequestAware {
private Map<String,Object> application;

private Map<String,Object> session;

private Map<String,Object> request;
@Override
public void setApplication(Map<String, Object> application) {
this.application = application;
}

@Override
public void setRequest(Map<String, Object> request) {
this.request = request;
}

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

耦合的方式

使用ServletActionContext

1
2
3
4
5
HttpSession session = ServletActionContext.getRequest().getSession();

HttpServletRequest request = ServletActionContext.getRequest();

HttpServletResponse response = ServletActionContext.getResponse();

使用ServletXxxAware

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class TestServletAwareAction implements ServletRequestAware, ServletResponseAware, ServletContextAware {

private HttpServletResponse httpServletResponse;

private HttpServletRequest httpServletRequest;

private ServletContext servletContext;
@Override
public void setServletRequest(HttpServletRequest httpServletRequest) {
this.httpServletRequest = httpServletRequest;
}

@Override
public void setServletResponse(HttpServletResponse httpServletResponse) {
this.httpServletResponse = httpServletResponse;
}

@Override
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
}

欢迎关注我的其它发布渠道