Structs2 Action访问Servlet API的三种方式

本文详细介绍了Struts2 Action如何直接或间接地访问Servlet API的三种方法,包括使用ServletActionContext、继承HttpServlet抽象类以及通过RequestDispatcher进行转发,帮助开发者更好地整合Struts2框架和Servlet功能。
摘要由CSDN通过智能技术生成
第一种:使用Structs2框架提供的内置类
Class ActionContext


java.lang.Object
com.opensymphony.xwork2.ActionContext
All Implemented Interfaces:
Serializable
Direct Known Subclasses:
ServletActionContext


The ActionContext is the context in which an Action is executed. Each context is basically a container of objects an action needs for execution like the session, parameters, locale, etc.


The ActionContext is thread local which means that values stored in the ActionContext are unique per thread. See the ThreadLocal class for more information. The benefit of this is you don't need to worry about a user specific action context, you just get it:


ActionContext context = ActionContext.getContext();
Finally, because of the thread local usage you don't need to worry about making your actions thread safe.


大体来说,就是ActionContext类是线程安全的。


Structs提供了一个ActionContext类,可以通过该类来访问ServletAPI。


此类的获取方法:ActionContext context = ActionContext.getContext();
下面是其常用的几个方法:


Object get(String key):该方法类似于调用HttpServletRequest的getAttribute(String)方法。
Map<String,Object> getApplication():返回一个Map对象,该方法模拟了该应用的ServletContext实例
Map getParameters():获取所有的请求参数。类似于调用HttpServletRequest的getParametersMap的方法
Map getSession():返回一个Map对象,该Map对象模拟了HttpSession对象。
void setApplication(Map application):直接传入一个Map实例,将该Map实例里的key-value值对转换成application的属性名属性值
void setSession(Map session):如上




第二种:Action实现访问ServletAPI的接口
ServletContextAware,ServletRequestAware,ServletResponseAware
实现了以上接口的Action将会由框架传入Servlet对象。

例如:

pulic class LoginAction
					implements Action,ServletResponseAware
{
	/**************************/
	private HttpServletResponse response;
	public void setServletRequest(HttpServletResponse response)
	{
		this.response=response;
	}
	/**************************这些是需要实现的方法和属性
	public String execute() throws Exception
	{//向客户端增加cookie
		Cookie c=new Cookie("aa","bb");
		c.setMaxAge(60*60);
		response.addCookie(c);
		return SUCCESS;
	}
}

第三种:;利用ServletActionContext直接访问ServletAPI
static javax.servlet.http.HttpServletRequest getRequest()
static javax.servlet.http.HttpServletResponse getResponse()
static javax.servlet.ServletContext            getServletContext()
例如:

pulic class LoginAction
					implements Action
{
	public String execute() throws Exception
	{//向客户端增加cookie
		Cookie c=new Cookie("aa","bb");
		c.setMaxAge(60*60);
		response=ServletActionContext.getResponse().addCookie(c);
		return SUCCESS;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值