一、ActionContext简述
ActionContext是Struts2中一种非常重要的概念,它是将程序中的所有请求及其他信息存储在一个Map中,以便在程序的不同部分中进行访问。ActionContext维护了与当前线程相关的信息,包括HTTP请求对象、HTTP响应对象、会话数据和HTTP Servlet上下文等信息。
二、ActionContext的作用
1、获取Servlet相关的信息
获取HTTP请求绑定的Session对象、查询HTTP请求的参数、获取HTTP请求绑定的ServletContext对象,都可以通过ActionContext来访问。
public class MyAction extends ActionSupport {
public String execute() {
// 获取HttpSession对象
HttpSession session = ServletActionContext.getRequest().getSession();
// 获取ServletContext对象
ServletContext context = ServletActionContext.getServletContext();
// 获取查询参数
String name = ServletActionContext.getRequest().getParameter("name");
return SUCCESS;
}
}
2、获取当前请求相关的Action、Interceptor和Result
ActionContext中提供了getActionInvocation()方法,可以获取到当前请求对应的ActionInvocation对象,该对象中中还包含了本次请求经过的Interceptor和执行的Result信息。
public class MyAction extends ActionSupport {
public String execute() {
ActionInvocation invocation = ActionContext.getContext().getActionInvocation();
// 获取当前请求对应的Action
Action action = invocation.getAction();
// 获取当前请求经过的Interceptor
List interceptors = invocation.getInterceptors();
// 获取当前执行的Result
Result result = invocation.getResult();
return SUCCESS;
}
}
3、获取值栈对象
ActionContext维护了一个值栈(ValueStack)对象,用于存储Action执行过程中的数据,在JSP页面中可以很方便的获取这些数据。
public class MyAction extends ActionSupport {
public String execute() {
ValueStack stack = ActionContext.getContext().getValueStack();
// 向值栈中添加数据
stack.push("hello world");
return SUCCESS;
}
}
三、ActionContext的使用
1、在Action中使用ActionContext
在Action中,可以直接通过ActionContext对象获取Servlet的相关信息,一般在Action的execute()方法的代码中使用,示例如下:
public class MyAction extends ActionSupport {
public String execute() {
HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(StrutsStatics.HTTP_REQUEST);
return SUCCESS;
}
}
2、在Interceptor中使用ActionContext
在Interceptor中,可以通过ActionInvocation获取ActionContext对象,一般在Interceptor的intercept方法中使用,示例如下:
public class MyInterceptor extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation invocation) throws Exception {
// 获取当前ActionContext对象
ActionContext context = invocation.getInvocationContext();
return invocation.invoke();
}
}
3、在JSP页面中使用ActionContext
在JSP页面中,可以通过ActionContext对象和值栈对象非常方便的获取Action执行时存储在值栈中的数据。在JSP页面中使用%{…}的EL表达式即可访问值栈中的数据,示例如下:
<s:property value="%{username}"/>
四、小结
本文详细阐述了ActionContext的定义、作用及使用方法,主要包括在Action、Interceptor和JSP页面中的使用方法。ActionContext是Struts2框架的一个重要组成部分,通过它可以方便地访问Servlet相关的信息和值栈中的数据。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/236924.html
微信扫一扫
支付宝扫一扫