How to use ActionContext in Struts2?
In Struts2, ActionContext is a class used to store context information for Actions. It is a thread-safe class that can be accessed from anywhere.
With ActionContext, you can access and manipulate various details regarding the Action, such as request parameters, session information, response details, and more.
Here are some common operations using ActionContext:
- Retrieve the ActionContext object:
ActionContext context = ActionContext.getContext();
- Accessing and setting request parameters:
// 获取请求参数
Map<String, Object> parameters = context.getParameters();
// 获取单个请求参数的值
String parameterValue = context.getParameters().get("paramName");
// 设置请求参数的值
context.getParameters().put("paramName", "paramValue");
- Retrieve and update session information:
// 获取会话信息
Map<String, Object> session = context.getSession();
// 获取单个会话属性的值
Object attributeValue = context.getSession().get("attributeName");
// 设置会话属性的值
context.getSession().put("attributeName", attributeValue);
- Accessing and setting context information.
// 获取上下文信息
Map<String, Object> contextMap = context.getContextMap();
// 获取单个上下文属性的值
Object attributeValue = context.getContextMap().get("attributeName");
// 设置上下文属性的值
context.getContextMap().put("attributeName", attributeValue);
- Get and set response information.
// 获取响应信息
HttpServletResponse response = (HttpServletResponse) context.get(StrutsStatics.HTTP_RESPONSE);
// 设置响应头
response.setHeader("headerName", "headerValue");
// 设置响应状态码
response.setStatus(HttpServletResponse.SC_OK);
These are just some common operations of ActionContext, there are many other methods available that can be used based on specific needs.