Struts2 ActionContext类操作属性的方法(请求、会话、上下文)

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>




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值