Struts2中ActionContext和ServletActionContext
转自:http://blog.sina.com.cn/s/blog_6c9bac050100y9iw.html
在Web应用程序开发中,除了将请求参数自动设置到Action的字段中,我们往往也需要在Action里直接获取请求(Request)或会话 (Session)的一些信息, 甚至需要直接对JavaServlet Http的请求(HttpServletRequest),响应(HttpServletResponse)操作。
我们需要在Action中取得request请求参数"username"的值:
ActionContext context = ActionContext.getContext(); Map params = context.getParameters(); String username = (String) params.get("username");
ActionContext(com.opensymphony.xwork.ActionContext)是Action执行时的上下文,上下文可以看作是一个容器(其实我们这里的容器就是一个Map而已),它存放放的是Action在执行时需要用到的对象
一般情况,我们的ActionContext都是通过:ActionContext context = (ActionContext) actionContext.get();来获取的.
我们再来看看这里的actionContext对象的创建:
static ThreadLocal actionContext = new ActionContextThreadLocal();
ActionContextThreadLocal是实现ThreadLocal的一个内部类.ThreadLocal可以命名为"线程局部变量",它为每一个使用该变量的线程都提供一个变量值的副本,使每一个线程都可以独立地改变自己的副本, 而不会和其它线程的副本冲突.这样,我们ActionContext里的属性只会在对应的当前请求线程中可见,从而保证它是线程安全的.
下面我们看看怎么通过ActionContext取得我们的HttpSession:
Map session = ActionContext.getContext().getSession();
再看看怎么通过ServletActionContext取得我们的HttpSession:
ServletActionContext(com.opensymphony.webwork. ServletActionContext),这个类直接继承了我们上面介绍的ActionContext,它提供了直接与JavaServlet相关对象访问的功能,它可以取得的对象有:
1, javax.servlet.http.HttpServletRequest:HTTPservlet请求对象
2, javax.servlet.http.HttpServletResponse;:HTTPservlet相应对象
3, javax.servlet.ServletContext:Servlet 上下文信息
4, javax.servlet.ServletConfig:Servlet配置对象
5, javax.servlet.jsp.PageContext:Http页面上下文
下面我们看看几个简单的例子,让我们了解如何从ServletActionContext里取得JavaServlet的相关对象:
1, 取得HttpServletRequest对象:
HttpServletRequest request = ServletActionContext. getRequest();
2, 取得HttpSession对象:
HttpSession session = ServletActionContext. getRequest().getSession();
ServletActionContext 和ActionContext有着一些重复的功能,在我们的Action中,该如何去抉择呢?
我们遵循的原则是:
(1)如果ActionContext能够实现我们的功能,那最好就不要使用ServletActionContext,让我们的Action尽量不要直接去访问JavaServlet的相关对象.
(2)在使用ActionContext时有一点要注意:不要在Action的构造函数里使用ActionContext.getContext(),因为这个时候ActionContext里的一些值也许没有设置,这时通过ActionContext取得的值也许是null.
如果我要取得Servlet API中的一些对象,如request,response或session等,应该怎么做?
在Strutx 2.0你可以有两种方式获得这些对象:非IoC方式和IoC(控制反转Inversion of Control)方式.
A、非IoC方式
要获得上述对象,关键Struts 2.0中com.opensymphony.xwork2.ActionContext类.我们可以通过它的静态方法getContext()获取当前 Action的上下文对象. 另外,org.apache.struts2.ServletActionContext作为辅助类(Helper Class),可以帮助您快捷地获得这几个对象.
HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); HttpSession session = request.getSession();
例6 classes/tutorial/NonIoCServlet.java
1 package tutorial;
2
3 import javax.servlet.http.HttpServletRequest;
4
5 import javax.servlet.http.HttpServletResponse;
6
7 import javax.servlet.http.HttpSession;
8
9 import org.apache.struts2.ServletActionContext;
10
11 import com.opensymphony.xwork2.ActionContext;
12
13 import com.opensymphony.xwork2.ActionSupport;
14
15 Public class NonIoCServletextends ActionSupport {
16
17 private String message;
18
19
20
21 public String getMessage() {
22
23 return message;
24
25 }
26
27 HttpServletRequest request = ServletActionContext.getRequest();
28
29 HttpServletResponse response = ServletActionContext.getResponse();
30
31 HttpSession session = request.getSession();
32
33
34
35 @Override
36
37 public String execute() {
38
39 ActionContext.getContext().getSession().put("msg", "Hello World from Session!");[A2]
40
41
42
43 StringBuffer sb =new StringBuffer("Message from request: ");
44
45 sb.append(request.getParameter("msg"));
46
47
48
49 sb.append("<br>Response Buffer Size: ");
50
51 sb.append(response.getBufferSize());
52
53
54
55 sb.append("<br>Session ID: ");
56
57 sb.append(session.getId());[A3]
58
59
60
61 message = sb.toString(); //转换为字符串。
62
63 return SUCCESS;
64
65 }
66
67 } //与LoginAction类似的方法。
如果你只是想访问session的属性(Attribute),你也可以通过ActionContext.getContext().getSession()获取或添加session范围(Scoped)的对象.[A1]
B、IoC方式
要使用IoC方式,我们首先要告诉IoC容器(Container)想取得某个对象的意愿,通过实现相应的接口做到这点.具体实现,请参考例6 IocServlet.java.
例6 classes/tutorial/IoCServlet.java
package tutorial; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts2.interceptor.ServletRequestAware; import org.apache.struts2.interceptor.ServletResponseAware; import org.apache.struts2.interceptor.SessionAware; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; public class IoCServlet extends ActionSupport implements SessionAware, ServletRequestAware, ServletResponseAware { private String message; private Map att; private HttpServletRequest request; private HttpServletResponse response; public String getMessage() { return message; } public void setSession(Map att) { this.att = att; }[A5] publicvoid setServletRequest(HttpServletRequest request) { this.request = request; } 51 publicvoid setServletResponse(HttpServletResponse response) { this.response = response; }[A5] @Override public String execute() { att [A6] .put("msg", "Hello World from Session!"); HttpSession session = request.getSession(); StringBuffer sb =new StringBuffer("Message from request: "); sb.append(request.getParameter("msg")); sb.append("<br>Response Buffer Size: "); sb.append(response.getBufferSize()); sb.append("<br>Session ID: "); sb.append(session.getId()); message = sb.toString();
return SUCCESS; } }
例6 Servlet.jsp
<%@ page contentType="text/html; charset=UTF-8" %> <%@ taglib prefix="s" uri="/struts-tags"%> <html> <head> <title>Hello World!</title> </head> <body> <h2> <s:property value="message" escape="false"/> <br>Message from session: <s:property value="#session.msg"/> </h2> </body> </html>
例6 classes/struts.xml中NonIocServlet和IoCServlet Action的配置
<action name="NonIoCServlet" class="tutorial.NonIoCServlet"> <result>/Servlet.jsp</result> </action> <action name="IoCServlet" class="tutorial.IoCServlet"> <result>/Servlet.jsp</result> </action>
运行Tomcat,在浏览器地址栏中键入http://localhost:8080/Struts2_Action /NonIoCServlet.action?msg=Hello World! 或http://localhost:8080/Struts2_Action/IoCServlet.action?msg=Hello World!
在Servlet.jsp中,我用了两次property标志,第一次将escape设为false为了在JSP中输出<br>转行,第二次的value中的OGNL为"#session.msg",它的作用与session.getAttribute("msg")等同.
附:ActionContext的常用方法(来自Struts2.0 API)
(一)get
Returns a value that is stored in the current ActionContext by doing a lookup using the value's key.
Parameters:
key- the key used to find the value.
Returns:
the value that was found using the key or null if the key was not found.
(二)put
public void put(Object key, Object value)
Stores a value in the current ActionContext. The value can be looked up using the key.
Parameters:
key- the key of the value.
value- the value to be stored.
(三)getContext
public static ActionContext getContext()
Returns the ActionContext specific to the current thread.
Returns:
the ActionContext for the current thread, is never null.
(四)getSession
public Map getSession()
Gets the Map of HttpSession values when in a servlet environment or a generic session map otherwise.
Returns:
the Map of HttpSession values when in a servlet environment or a generic session map otherwise.
(五)setSession
public void setSession(Map session)
Sets a map of action session values.
Parameters:
session- the session values.
Struts2的action类继承
com.opensymphony.xwork2.ActionSupport类的常用方法
addFieldError //该方法主要用于验证的方法之中
public void addFieldError(String fieldName, String errorMessage)
Description copied from interface: ValidationAware
Add an error message for a given field.
Specified by:
addFieldErrorin interface ValidationAware
Parameters:
fieldName- name of field
errorMessage- the error message
public void validate()
A default implementation that validates nothing. Subclasses should override this method to provide validations.
Specified by:
validatein interface Validateable
这一点比较的重要,例如:ActionContext.getContext().getSession().put("user", "value");
与右上角的是一个模式。
Java语法基础,使用stringBuffer。
对属性(实例)设置setter方法。
方法的来源,见后面补充的常用方法:
public void setSession(Map session)
Sets a map of action session values. 设置session值,
Parameters:
session- the session values.
为当前的session,所以可以调用put方法。详细信息见补充的知识。
常用于校验登陆程序的账号和密码是否为空,可以加入addFieldError方法。例如public void validate() {
if (null == login.getUserID() || "".equals(login.getUserID())) { this.addFieldError("login.userID", "学号不能为空"); }
if (null == login.getUserPassword() ||"".equals(login.getUserPassword())) { this.addFieldError("login.userPassword", "密码不能为空"); }
}
Struts2中ActionContext和ServletActionContext的更多相关文章
- Struts2中ActionContext及ServletActionContext介绍(转载)
1. ActionContext 在Struts2开发中,除了将请求参数自动设置到Action的字段中,我们往往也需要在Action里直接获取请求(Request)或会话(Session)的一些信息, ...
- 关于struts2中ActionContext类的作用
关于struts2中ActionContext类的作用有三个: 1.获取三大作用域对象及页面参数 2.是struts标签的上下文对象 3.ThreadLocal内装的就是ActionContext 怎 ...
- 【struts2】ActionContext与ServletActionContext
1 再探ActionContext 我们知道,ActionContext是Action执行时的上下文,里面存放着Action在执行时需要用到的对象,也称之为广义值栈.Struts2在每次执行Actio ...
- Struts中ActionContext和ServletActionContext的比较
一.ActionContext在Struts2开发中除了将请求参数自动设置到Action的字段中,往往也需要在Action里直接获取请求(Request)或会话(Session)的一些信息,甚至需要直 ...
- struts2中 ServletActionContext与ActionContext区别
1. ActionContext 在Struts2开发中,除了将请求参数自动设置到Action的字段中,我们往往也需要在Action里直接获取请求(Request)或会话(Session)的一些信息, ...
- ActionContext介绍(在Struts2中)
一种属性的有序序列,它们为驻留在环境内的对象定义环境.在对象的激活过程中创建上下文,对象被配置为要求某些自动服务,如同步.事务.实时激活.安全性等等.多个对象可以存留在一个上下文内.也有根据上下文理解 ...
- Struts2中的ActionContext、OGNL及EL的使用
文章分类:Java编程 本文基于struts2.1.8.1,xwork2.1.6 1.EL EL(Expression Language)源于jsp页面标签jstl,后来被jsp2.0 ...
- 在Struts2中使用ValueStack、ActionContext、ServletContext、request、session等 .
笔者不知道该用哪个词来形容ValueStack.ActionContext等可以在Struts2中用来存放数据的类.这些类使用的范围不同,得到的方法也不同,下面就来一一介绍. 声明:本文参考Strut ...
- ActionContext和ServletActionContext区别
1. ActionContext 在Struts2开发中,除了将请求参数自动设置到Action的字段中,我们往往也需要在Action里直接获取请求(Request)或会话(Session)的一些信息, ...
随机推荐
- SQL Server 2005 数据库复制(转载)
对于一个地域分散的大型企业组织来说,构建具有典型的分布式计算机特征的大型企业管理信息系统时,总要解决一个很重要的问题:如何在多个不同数 据库服务器之间保证共享数据的一致性.之所以有这个重要的问题在于企 ...
- WPF 操作键盘
#region 打开键盘的键 const uint KEYEVENTF_EXTENDEDKEY = 0x1; const uint KEYEVENTF_KEYUP = 0x2; [DllImport( ...
- 安装lnmp后,忘记phpmyadmin的root密码,怎么办
如果忘记MySQL root密码,如何重设密码?执行如下命令:wget http://soft.vpser.net/lnmp/ext/reset_mysql_root_password.sh;sh r ...
- Mac下部署Android开发环境附加NDK
作为开发者,我们深有体会,不管是进行什么开发,为了部署开发环境,我们往往需要折腾很长时间.查阅很多资料才能完成,而且这次折腾完了,下次到了另一台新电脑上又得重新来过,整个部署过程记得还好,要是不记得又 ...
- HDU 1025 Constructing Roads In JGShining's Kingdom(求最长上升子序列nlogn算法)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1025 解题报告:先把输入按照r从小到大的顺序排个序,然后就转化成了求p的最长上升子序列问题了,当然按p ...
- NGUI例子Scroll View场景中item添加点击后自动滑到终点
http://blog.csdn.net/luyuncsd123/article/details/22914497 最近在做一个项目的UI,需求是1.拖动items后当永远有一个item保存在中间位置 ...
- cocos2d 如何优化内存使用
如何优化内存使用 内存优化原理 为优化应用内存使用,开发人员首先应该知道什么最耗应用内存,答案就是纹理! 纹理几乎会占据90%应用内存.所以尽量最小化应用的纹理内存使用,否则应用很有可能会因为低内存而 ...
- [BZOJ2303][Apio2011]方格染色
[BZOJ2303][Apio2011]方格染色 试题描述 Sam和他的妹妹Sara有一个包含n × m个方格的 表格.她们想要将其的每个方格都染成红色或蓝色. 出于个人喜好,他们想要表格中每个2 × ...
- Aptana插件安装到eclipse和myeclipse的详细过程
刚开始学习Jquery,为了搭建好的环境是很重要的,所以我尝试了很多方式,下面之一. 一.要下载好Aptana 插件 官网: http://update1.aptana.org/studio/3.2/ ...
- BZOJ 1058
服气!我果然就是个傻逼. 傻兮兮地感觉两个数之间的差距无需删除一些答案,妈个鸡就只加入了一些新的答案忘记了去掉无效的答案.我果然是傻逼,经验不足脑子笨... 这么水的题...不说了,说多了都是泪. 自 ...