ITeye博客

struts2源码分析获取request response session

wysaijun1314 · 2011-11-17 12:59 · java · struts2 · s2sh · 编程语言 · Markdown

网上介绍有两种获取request,response和session的方法,一种是ioc方式的,通过实现SessionAware,ServletRequestAware, ServletResponseAware接口就可以 而另一种则是非ioc方式的,我这主要介绍一下非ioc方式的 1.获取request


HttpServletRequest req1 = ServletActionContext.getRequest();
HttpServletRequest req2= (HttpServletRequest)ActionContext.getContext().get(ServletActionContext. HTTP_REQUEST ); 		
HttpServletRequest req4= (HttpServletRequest)ActionContext.getContext().get(StrutsStatics. HTTP_REQUEST ); 	
HttpServletRequest req5= (HttpServletRequest)ActionContext.getContext().get("com.opensymphony.xwork2.dispatcher.HttpServletRequest"); 

其实它们最终是走的一个方法,因为ServletActionContext 继承了ActionContext 而且因为ServletActionContext.getRequest()的方法是调用了ActionContext里的方法 同时ServletActionContext. HTTP_REQUEST,StrutsStatics. HTTP_REQUEST常量都是字符串com.opensymphony.xwork2.dispatcher.HttpServletRequest, 它的定义在StrutsStatics接口中,ServletActionContext也继承了接接口,所有也能直接使用这个常量

2.同理获取response


HttpServletResponse res1 = ServletActionContext.getResponse();
HttpServletResponse res2= (HttpServletResponse)ActionContext.getContext().get(ServletActionContext.HTTP_RESPONSE); 		
HttpServletResponse res3= (HttpServletResponse)ActionContext.getContext().get(StrutsStatics.HTTP_RESPONSE ); 	
HttpServletResponse res4= (HttpServletResponse)ActionContext.getContext().get("com.opensymphony.xwork2.dispatcher.HttpServletResponse"); 

3.获取session 只需要先获取到request就可以通过request.getSession()来获取

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。