1、操作请求范围的属性
public void put(Object key, Object value):向ActionContext中存属性,该属性存在于请求范围。
public Object get(Object key):从ActionContext中获取属性。
public String execute(){
ActionContext ctxt = ActionContext.getContext();
ctxt.put("reqattr","请求属性");
System.out.println("ActionContext.get:"+ctx.get("reqattr"));
return "success";
}
jsp页面获取属性值
<body>
${requestScope.reqattr}
<body>
2、操作会话范围的属性
public Map getSession():该方法返回值是一个Map对象,该Map对象与会话相关。通过调用返回值Map的put(Object key,Object value)方法,可以向会话范围存属性;通过调用Map的Object get(Object key)方法,可以从会话范围获取属性。
public String execute(){
ActionContext ctxt = ActionContext.getContext();
Map session = ctxt.getSession();
session.put("sessionattr","会话属性");
System.out.println("ActionContext.getSession().get:"+session.get("sessionattr"));
return "success";
}
jsp页面获取属性值
<body>
${sessionScope.sessionattr}
<body>
3、操作上下文范围的属性
public Map getApplication():该方法返回值是一个与上下文相关的Map对象,通过调用Map对象的put(Object key, Object value)方法,可以向上下文范围存属性;通过Map接口的Object get(Object key)方法,可以从上下文范围获取属性。
public String execute(){
ActionContext ctxt = ActionContext.getContext();
Map application = ctxt.getApplication();
application.put("applicationattr","上下文属性");
System.out.println("ActionContext.getApplication().get:"+application.get("applicationattr"));
return "success";
}
jsp页面获取属性值
<body>
${applicationScope.applicationattr}
<body>
实例
Action类ViewAllAction.java
package Action;
import java.util.List;
import com.opensymphony.xwork2.ActionContext;
import dao.Impl.CustomerDAOImpl;
import Service.CustomerServiceImpl;
import VO.Customer;
public class ViewAllAction {
public String execute(){
CustomerServiceImpl cs = new CustomerServiceImpl();
cs.setDao(new CustomerDAOImpl());
List<Customer> list = cs.viewAll();
ActionContext ctxt = ActionContext.getContext();
ctxt.put("allcustomers", list);
return "success";
}
}
welcom.jsp页面
<body>
Welcome,${param.pwd}
<a href="ViewAll.action">View All Customers.</a>
</body>
allcustomers.jsp显示页面
<body>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
All Customers:<br>
<table width="200" border="1">
<tbody>
<tr>
<td> Custname</td>
<td> age</td>
<td>address </td>
</tr>
<c:forEach items="${allcustomers}" var="c">
<tr>
<td>${c.custname}</td>
<td>${c.age}</td>
<td>${c.address}</td>
</tr>
</c:forEach>
</tbody>
</table><br>
</body>