当前位置: 首页 > 编程日记 > 正文

struts2中 ServletActionContext与ActionContext区别

1. ActionContext

在Struts2开发中,除了将请求参数自动设置到Action的字段中,我们往往也需要在Action里直接获取请求(Request)或会话(Session)的一些信息,甚至需要直接对JavaServlet Http的请求(HttpServletRequest),响应(HttpServletResponse)操作. 我们需要在Action中取得request请求参数"username"的值:

  1. ActionContext context = ActionContext.getContext();
  2. Map params = context.getParameters();
  3. String username = (String) params.get("username");

ActionContext(com.opensymphony.xwork.ActionContext)是Action执行时的上下文,上下文可以看作是一个容器(其实我们这里的容器就是一个Map而已),它存放的是Action在执行时需要用到的对象. 一般情况, 我们的ActionContext都是通过: ActionContext context = (ActionContext) actionContext.get();来获取的.我们再来看看这里的actionContext对象的创建:

static ThreadLocal actionContext = new ActionContextThreadLocal();

ActionContextThreadLocal是实现ThreadLocal的一个内部类.ThreadLocal可以命名为"线程局部变量",它为每一个使用该变量的线程都提供一个变量值的副本,使每一个线程都可以独立地改变自己的副本,而不会和其它线程的副本冲突.这样,我们ActionContext里的属性只会在对应的当前请求线程中可见,从而保证它是线程安全的.

通过ActionContext取得HttpSession: Map session = ActionContext.getContext().getSession();

2. ServletActionContext

ServletActionContext(com.opensymphony.webwork. ServletActionContext),这个类直接继承了我们上面介绍的ActionContext,它提供了直接与Servlet相关对象访问的功能,它可以取得的对象有:

(1)javax.servlet.http.HttpServletRequest : HTTPservlet请求对象

(2)javax.servlet.http.HttpServletResponse : HTTPservlet相应对象

(3)javax.servlet.ServletContext : Servlet上下文信息

(4)javax.servlet.ServletConfig : Servlet配置对象

(5)javax.servlet.jsp.PageContext : Http页面上下文

如何从ServletActionContext里取得Servlet的相关对象:

<1>取得HttpServletRequest对象: HttpServletRequest request = ServletActionContext. getRequest();

<2>取得HttpSession对象: HttpSession session = ServletActionContext. getRequest().getSession();

3. ServletActionContext和ActionContext联系

ServletActionContext和ActionContext有着一些重复的功能,在我们的Action中,该如何去抉择呢?我们遵循的原则是:如果ActionContext能够实现我们的功能,那最好就不要使用ServletActionContext,让我们的Action尽量不要直接去访问Servlet的相关对象.

注意:在使用ActionContext时有一点要注意: 不要在Action的构造函数里使用ActionContext.getContext(),因为这个时候ActionContext里的一些值也许没有设置,这时通过ActionContext取得的值也许是null;同样,HttpServletRequest req = ServletActionContext.getRequest()也不要放在构造函数中,也不要直接将req作为类变量给其赋值。至于原因,我想是因为前面讲到的static ThreadLocal actionContext = new ActionContextThreadLocal(),从这里我们可以看出ActionContext是线程安全的,而ServletActionContext继承自ActionContext,所以ServletActionContext也线程安全,线程安全要求每个线程都独立进行,所以req的创建也要求独立进行,所以ServletActionContext.getRequest()这句话不要放在构造函数中,也不要直接放在类中,而应该放在每个具体的方法体中(eg:login()、queryAll()、insert()等),这样才能保证每次产生对象时独立的建立了一个req。

4. struts2中获得request、response和session

(1)非IoC方式

方法一:使用org.apache.struts2.ActionContext类,通过它的静态方法getContext()获取当前Action的上下文对象。

[java] view plain copy
  1. <pre name="code" class="java">ActionContext ctx = ActionContext.getContext();  
  2. ctx.put("liuwei", "andy"); //request.setAttribute("liuwei", "andy");  
  3. Map session = ctx.getSession(); //session  
  4. HttpServletRequest request = ctx.get(org.apache.struts2.StrutsStatics.HTTP_REQUEST);
  5. HttpServletResponse response = ctx.get(org.apache.struts2.StrutsStatics.HTTP_RESPONSE);</pre><br>
  6. <p></p>
  7. <pre></pre>
  8. <br>
  9. <br>
  10. <p></p>
  11. <p><span style="font-size:16px">细心的朋友可以发现这里的session是个Map对象, 在Struts2中底层的session都被封装成了Map类型.  
  12. <br>
  13. </span></p>
  14. <p><span style="font-size:16px">我们可以直接操作这个Map对象进行对session的写入和读取操作, 而不用去直接操作HttpSession对象.</span></p>  
  15. <p><span style="font-size:16px">方法二:使用org.apache.struts2.ServletActionContext类</span></p>  
  16. <p><strong></strong></p><pre name="code" class="java">    public class UserAction extends ActionSupport {  
  17. //其他代码片段  
  18. private HttpServletRequest req;   
  19. //  private HttpServletRequest req = ServletActionContext.getRequest(); 这条语句放在这个位置是错误的,同样把这条语句放在构造方法中也是错误的。  
  20. public String login() {  
  21. req = ServletActionContext.getRequest(); //req的获得必须在具体的方法中实现  
  22. user = new User();  
  23. user.setUid(uid);
  24. user.setPassword(password);
  25. if (userDAO.isLogin(user)) {  
  26. req.getSession().setAttribute("user", user);  
  27. return SUCCESS;  
  28. }
  29. return LOGIN;  
  30. }
  31. public String queryAll() {  
  32. req = ServletActionContext.getRequest(); //req的获得必须在具体的方法中实现  
  33. uList = userDAO.queryAll();
  34. req.getSession().setAttribute("uList", uList);  
  35. return SUCCESS;  
  36. }
  37. //其他代码片段  
  38. }</pre><br>
  39. <br>
  40. <p></p>
  41. <p><span style="font-size:16px"><strong>(2)IoC方式(即使用Struts2 Aware拦截器)</strong></span></p>  
  42. <p>要使用IoC方式,我们首先要告诉IoC容器(Container)想取得某个对象的意愿,通过实现相应的接口做到这点。</p>
  43. <pre name="code" class="java">    public class UserAction extends ActionSupport implements SessionAware, ServletRequestAware, ServletResponseAware {  
  44. private HttpServletRequest request;   
  45. private HttpServletResponse response;   
  46. public void setServletRequest(HttpServletRequest request) {  
  47. this.request = request;   
  48. }
  49. public void setServletResponse(HttpServletResponse response) {  
  50. this.response = response;   
  51. }
  52. public String execute() {   
  53. HttpSession session = request.getSession();
  54. return SUCCESS;   
  55. }
  56. }</pre><br>
  57. <br>
  58. <link rel="stylesheet" href="http://static.blog.csdn.net/public/res-min/markdown_views.css?v=2.0">  

转载于:https://www.cnblogs.com/shixf/p/7789082.html

相关文章:

[记录]calculate age based on date of birth

calculate age based on date of birth know one new webiste:eval.in run php code转载于:https://www.cnblogs.com/fsong/p/5190273.html

有抱负的Web开发人员应考虑的6件事

Becoming a web developer can be as challenging as working out every day.成为网络开发人员就像每天锻炼一样具有挑战性。 It’s important to know what it will take to succeed as a web developer.重要的是要知道要成为一名Web开发人员要取得成功。 Here are 6 things…

阿里云OSS上传图片实现流程

前置&#xff0c;在阿里云开通OSS对象储存。然后在下图文件管理配置文件储存目录和图中传输管理配置访问域名。 1.复制 uploadFileUtil 文件夹和 uploadFile.js 文件在 util 文件夹 2.在使用的页面 引入 uploadFile 效果图&#xff1a; 实现代码 <template><view c…

修改远程桌面连接3389端口号

修改注册表&#xff1a; HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Terminal Server\Wds\Repwd\Tds\Tcp 键&#xff1a;PortNumber&#xff0c;以十进制显示&#xff1a;3389&#xff0c;修改成55555&#xff0c;保存刷新注册表。 HKEY_LOCAL_MACHINE\SYSTEM\Curre…

理解 : UDID、UUID、IDFA、IDFV

iOS获取设备唯一标识的各种方法&#xff1f;IDFA、IDFV、UDID分别是什么含义&#xff1f;iOS获取设备ID总结IDFA解释 关于UUID的理解 : 英文名称是&#xff1a;Universally Unique Identifier,翻译过来就是通用唯一标识符。 UUID是指在一台机器上生成的数字&#xff0c;它保证对…

推箱子2-向右推!_保持冷静,砍箱子-me脚

推箱子2-向右推!Hack The Box (HTB) is an online platform allowing you to test your penetration testing skills. It contains several challenges that are constantly updated. Some of them simulating real world scenarios and some of them leaning more towards a C…

H5面试题---介绍js的基本数据类型

js的基本数据类型 Undefined、Null、Boolean、Number、String 转载于:https://www.cnblogs.com/songchunmin/p/7789582.html

Node.js express 之mongoose 从异步回调函数返回值,类似于同步

http://my.oschina.net/antianlu/blog/187023转载于:https://www.cnblogs.com/cylblogs/p/5192314.html

小程序登录、用户信息相关接口调整说明

为&#xfeff;优化用户的使用体验&#xff0c;平台将进行以下调整&#xff1a; 2021年2月23日起&#xff0c;若小程序已在微信开放平台进行绑定&#xff0c;则通过wx.login接口获取的登录凭证可直接换取unionID2021年4月13日后发布的小程序新版本&#xff0c;无法通过wx.getU…

小程序 reduce_使用Reduce制作的10个JavaScript实用程序功能

小程序 reduceThe multi-tool strikes again. 多功能工具再次触击。 In my last article I offered you a challenge to recreate well-known functions using reduce. This article will show you how some of them can be implemented, along with some extras! 在上一篇文章…

流媒体,hls

所谓流媒体是指采用流式传输的方式在Internet播放的媒体格式。流媒体又叫流式媒体&#xff0c;它是指商家用一个视频传送服务器把节目当成数据包发出&#xff0c;传送到网络上。用户通过解压设备对这些数据进行解压后&#xff0c;节目就会像发送前那样显示出来。流媒体&#xf…

uniapp实现页面左右滑动,上下滑动事件

实现代码&#xff1a; <view class"" touchstart"touchstart" touchend"touchend"> </view> data() {return {touchData: {}, //滑动事件数据} } methods: {touchstart(e) {this.touchData.clientX e.changedTouches[0].clientX;…

android逆向分析概述_Android存储概述

android逆向分析概述Storage is this thing we are all aware of, but always take for granted. Not long ago, every leap in storage capacity was incremental and appeared to be impossible. Nowadays, we don’t give a second thought when contemplating how much of …

小程序地图的使用笔记

这两天在看小程序的地图&#xff0c;写写笔记记录一下 小程序官方文档提供的方法 https://mp.weixin.qq.com/debug/wxadoc/dev/api/location.html 腾讯地图提供的jssdk http://lbs.qq.com/qqmap_wx_jssdk/qqmapwx.html 根据提示使用腾讯地图jssdk需要申请&#xff0c;在实例化的…

JS 实现可停顿的垂直滚动

1 var ScrollMiddle {2 Odiv:document.getElementById(comment), // 目标DOM 3 Oli: document.getElementById(comment).getElementsByTagName(li), 4 times:30, // 配置滚动时间 …

uniapp 上拉加载更多完整实现源码

直接上代码 <template><view class"searchList"><!-- 搜索框 --><Search></Search><img class"top_img" src"/static/image/dataDelivery.png" /><view class"menus p_r"><view class&…

todoist 无法登陆_通过构建Todoist克隆将您的React技能提升到一个新的水平

todoist 无法登陆In this intermediate React course from Karl Hadwen, you will learn how to create the popular Todoist application from scratch using React, Custom Hooks, Firebase & the React Testing Library. You will lean how to use SCSS to style the ap…

w3cscholl的在线代码编辑工具

https://www.w3cschool.cn/tryrun/runcode?langc转载于:https://www.cnblogs.com/jhj117/p/7804133.html

点击事件加锁封装

看代码 // 提交答案 btnReply() {if (!this.$clickLock) returnthis.changeClickLock() } 封装代码 // 点击事件加锁 使用方式&#xff0c;在点击时加入以下代码// if (!this.$clickLock) return// this.changeClickLock()that.changeClickLock () > {that.$clickLock f…

WinCE 7 Mouse HOOK

WinCE 5.0&6.0 的鼠标 HOOK&#xff0c;偶在本博客中已经写过文章。WinCE7.0 的下的鼠标 HOOK 实现&#xff0c;完全和 WinCE 6 是一样的。 效果&#xff1a;在 WinCE 系统界面可以 HOOK 住鼠标的操作。 但是在 Silverlight 应用的界面&#xff0c;HOOK 功能失效。转载于:h…

devops和docker_通过免费的2小时Docker课程学习DevOps基础知识

devops和dockerDocker is a powerful DevOps tool for putting your apps into "containers." Docker是功能强大的DevOps工具&#xff0c;可将您的应用程序放入“容器”中。 You can run these same containers anywhere - on your laptop, on a server - even on a…

生成24位字符串ID__IdGenerator.java

此工具类用于生成24位字符串ID&#xff0c;唯一不重复。 直接通过 IdGenerator.get() 获取。 源码如下&#xff1a;(点击下载源码 - IdGenerator.java ) 1 import java.net.NetworkInterface;2 import java.nio.ByteBuffer;3 import java.nio.ByteOrder;4 import java.util.Enu…

IDEA构建一个mybatis项目

目录结构如下&#xff1a; 在pom.xml中配置需要的jar包 <dependencies><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.3.0</version></dependency><dependency><gro…

小程序在canvas上层做图片滚动

实现该功能踩过的坑 1.swiper的swiper-item中image图片无法在canvas的上层显示&#xff0c;会被canvas 覆盖 2.swiper的swiper-item 里面放 cover-image 会样式错乱 3.scroll-view里面放 cover-image 会样式错乱 解决方案&#xff1a;使用CSS样式实现&#xff0c;超出部分隐…

React是如何在后台运行的

React is a very popular JavaScript library. With over 5.5 million weekly downloads, React is enjoying great popularity. But not a lot of React developers know how React works under the hood. React是一个非常流行JavaScript库。 每周的下载量超过550万&#xff0…

H5播放视频流

代码 <html> <head> <title>视频直播</title> <meta charset"utf-8"> <link href"http://vjs.zencdn.net/5.5.3/video-js.css" rel"stylesheet"> <!-- If youd like to support IE8 --> <!-…

获取Java系统相关信息

1 package com.test;2 3 import java.util.Properties;4 import java.util.Map.Entry;5 6 import org.junit.Test;7 8 public class SystemTest {9 10 /** 11 * 获取Java系统相关信息 12 * throws Exception 13 */ 14 Test 15 public void testSys…

如何使用FaunaDB + GraphQL

I have one or two projects I maintain on Netlify, in addition to hosting my blog there. It’s an easy platform to deploy to, and has features for content management (CMS) and lambda functions (by way of AWS).除了在其中托管我的博客外&#xff0c;我在Netlify上…

POJ 1414 Life Line(搜索)

题意&#xff1a; 给定一块正三角形棋盘&#xff0c;然后给定一些棋子和空位&#xff0c;棋子序号为a&#xff08;1<a<9)&#xff0c;group的定义是相邻序号一样的棋子。 然后到C&#xff08;1<N<9&#xff09;棋手在空位放上自己序号C的棋子&#xff0c; 放完后&a…

MySQL_数据库操作语句

ZC&#xff1a;数据库名/表名/字段名 都使用小写字母 1、 创建 数据库 和 表 的时候&#xff0c;都要指定 编码方式为 utf-8 ! ! ! 因为 执行命令“show variables like char%;”后可以看到 character_set_database 的值为 latin1&#xff0c;即 默认创建数据库是使用的 字符编…