Structs2 Action访问Servlet API的三种方式

来源:互联网 发布:tensorflow官网镜像 编辑:程序博客网 时间:2024/06/05 00:41
第一种:使用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 LoginActionimplements Action,ServletResponseAware{/**************************/private HttpServletResponse response;public void setServletRequest(HttpServletResponse response){this.response=response;}/**************************这些是需要实现的方法和属性public String execute() throws Exception{//向客户端增加cookieCookie 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 LoginActionimplements Action{public String execute() throws Exception{//向客户端增加cookieCookie c=new Cookie("aa","bb");c.setMaxAge(60*60);response=ServletActionContext.getResponse().addCookie(c);return SUCCESS;}}


0 0