Struts2 的一个重要特性就是Struts2的Action可以不与Servlet API耦合,更具有独立性,便于测试和代码复用。
Struts2提供了两种方式访问Servlet API
1. 避免代码污染,借助ActionContext对象模拟访问Session和Application,不与Servlet耦合
(1)通过ActionContext的getSession方法,模拟访问Http Session
(2)通过ActionContext的getApplication方法,模拟访问application
代码如下:
ActionContext actCtx = ActionContext.getContext();
//使用一个Map对象模拟HTTP Session
Map<String, Object> sess = actCtx.getSession();
//下面表面上只是向Map对象存入key-value键值对,实际上由于这个Map对象是模拟HTTP Session,因此下面存入的key-value对,实际会真实存入HTTP Session中
sess.put("userId", id);
2. 代码耦合污染,借助ServletActionContext真实访问Servlet,由于与Servlet API 耦合因此代码被污染。
ServletActionContext的提供如下静态方法:
- static PageContext getPageContext()
- static HttpServletRequest getRequest()
- static HttpServletResponse getResponse()
- static ServletContext getServletContext()
例如:
//由于访问Cookie必须用HttpServletResponse对象,所以Action不得不与Servlet API耦合
HttpServletResponse response = ServletActionContext.getResponse();
Cookie cookie = new Cookie("userName", user.getName());
cookie.setMaxAge(300000);
//添加Cookie
response.addCookie(cookie);
Struts2提供了两种方式访问Servlet API
1. 避免代码污染,借助ActionContext对象模拟访问Session和Application,不与Servlet耦合
(1)通过ActionContext的getSession方法,模拟访问Http Session
(2)通过ActionContext的getApplication方法,模拟访问application
代码如下:
ActionContext actCtx = ActionContext.getContext();
//使用一个Map对象模拟HTTP Session
Map<String, Object> sess = actCtx.getSession();
//下面表面上只是向Map对象存入key-value键值对,实际上由于这个Map对象是模拟HTTP Session,因此下面存入的key-value对,实际会真实存入HTTP Session中
sess.put("userId", id);
2. 代码耦合污染,借助ServletActionContext真实访问Servlet,由于与Servlet API 耦合因此代码被污染。
ServletActionContext的提供如下静态方法:
- static PageContext getPageContext()
- static HttpServletRequest getRequest()
- static HttpServletResponse getResponse()
- static ServletContext getServletContext()
例如:
//由于访问Cookie必须用HttpServletResponse对象,所以Action不得不与Servlet API耦合
HttpServletResponse response = ServletActionContext.getResponse();
Cookie cookie = new Cookie("userName", user.getName());
cookie.setMaxAge(300000);
//添加Cookie
response.addCookie(cookie);

深入探讨Struts2中Action的独立性与耦合性,介绍如何利用ActionContext实现与ServletAPI的隔离访问,同时阐述直接访问ServletAPI可能导致的代码污染问题。文章详细对比了两种访问方式的优缺点,旨在帮助开发者更好地理解和实践Struts2框架。
1903

被折叠的 条评论
为什么被折叠?



