struts2访问servletAPI

本文详细介绍了在Struts2框架中通过三种不同的方式访问Servlet API的方法:使用ActionContext、ServletActionContext以及实现特定接口。文章深入探讨了每种方式的实现细节和应用场景,为开发者提供了丰富的实践指导。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、原理

三种访问方式,后面两种本质都是调用的第一种

2、通过ActionContext访问

ActionContext中是通过map<String,Object>存放Servlet原来的request、response、session等对象以及域对象。

servlet中的request域、response域、session域存值的本质是使用map。

ActionContext的生命周期和request对象的一样,所以不建议使用request域,而使用ActionContext.getContext().put(key,value);的方式,

//通过ActionContext访问ServletApi
public String exectue() {
		
	//session——>map
	Map<String, Object> session = ActionContext.getContext().getSession();
	session.put("name", "session");
		
	//applictiong——>map
	Map<String, Object> application = ActionContext.getContext().getApplication();
	application.put("name", "application");
		
	//不推荐使用request——>map
	Map<String, Object> requestScope = (Map<String, Object>) ActionContext.getContext().get("request");
	requestScope.put("name", "request");
		
	//重写了request的setA,getA等方法,改变了request的取值的位置
	ActionContext.getContext().put("name2", "ActionContext");
		
	return "success";
}

3、通过ServletActionContext访问

//通过ServletActionContext访问ServletApi
public String exectue2() {
		
	//原生request
	HttpServletRequest request = ServletActionContext.getRequest();
		
	//先获得request,再获得session
	HttpSession session = request.getSession();
		
	//原生response
	HttpServletResponse response = ServletActionContext.getResponse();
		
	//原生servletContext
	ServletContext servletContext = ServletActionContext.getServletContext();
		
	return "success";
}

4、通过实现接口方式访问

public class AwareApi extends ActionSupport implements ServletRequestAware {

	private HttpServletRequest request;

	public String execute() {
		return SUCCESS;
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		// TODO Auto-generated method stub
		this.request = request;
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值