用一个例子来说明
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<a href="TestActionContext.action?name=csdn" >TestActionContext</a>
<%
if(application.getAttribute("date")==null)
{
application.setAttribute("date",new Date());
}
%>
</body>
</html>
struts.xml
<struts>
<package name="Test" extends="struts-default">
<action name="TestActionContext" class="com.liuzhen.action.ActionTest" method="execute">
<result name="success">result.jsp</result>
</action>
</package>
</struts>
ActionTest.java
package com.liuzhen.action;
import java.util.Map;
import com.opensymphony.xwork2.ActionContext;
public class ActionTest {
public String execute()
{
//0.获取ActionContext
//可以通过ActionContext获取一切信息
ActionContext actionContext = ActionContext.getContext();
//1.获取application信息,并向其中添加信息
Map<String,Object> applicationMap = actionContext.getApplication();
applicationMap.put("applicationKey", "applicationValue");
//获取信息
Object date = applicationMap.get("date");
System.out.println("date: "+date);
//2.获取session的信息,并将其中放入信息
Map<String,Object> sessionMap = actionContext.getSession();
sessionMap.put("sessionKey", "sessionValue");
//3.获取request的信息,并将信息放入其中
Map<String, Object> requestMap = (Map<String, Object>) actionContext.get("request");
requestMap.put("requestKey", "requestValue");
//4.获取请求参数对应的Map,并获取制定参数值
//键:请求参数的名字,值:请求参数所对应字符串数组
//注意: getParamters的返回值为Map<String,Object>,而不是Map<String,String[]>
Map<String, Object> paramters = actionContext.getParameters();
System.out.println("name : "+((String[])paramters.get("name"))[0]);
//parameters只能读不能写,写不出错,但也不起作用
paramters.put("age", 20);
return "success";
}
}
result.jsp
<body>
application : ${applicationScope.applicationKey }
<br><br/>
session: ${sessionScope.sessionKey}
<br><br>
request: ${requestScope.requestKey}
<br><br>
parameters: ${parameters.age }
</body>