转自:http://blog.sina.com.cn/s/blog_6c9bac050100y9iw.html

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

我们需要在Action中取得request请求参数"username"的值:

ActionContext context = ActionContext.getContext();Map params = context.getParameters();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();

再看看怎么通过ServletActionContext取得我们的HttpSession:

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

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里取得JavaServlet的相关对象:

1, 取得HttpServletRequest对象:

HttpServletRequest request = ServletActionContext. getRequest();

2, 取得HttpSession对象:

HttpSession session = ServletActionContext. getRequest().getSession();

ServletActionContext 和ActionContext有着一些重复的功能,在我们的Action中,该如何去抉择呢?

我们遵循的原则是:

(1)如果ActionContext能够实现我们的功能,那最好就不要使用ServletActionContext,让我们的Action尽量不要直接去访问JavaServlet的相关对象.

(2)在使用ActionContext时有一点要注意:不要在Action的构造函数里使用ActionContext.getContext(),因为这个时候ActionContext里的一些值也许没有设置,这时通过ActionContext取得的值也许是null.

如果我要取得Servlet API中的一些对象,如request,response或session等,应该怎么做?

在Strutx 2.0你可以有两种方式获得这些对象:IoC方式IoC(控制反转Inversion of Control)方式.

A、非IoC方式

 要获得上述对象,关键Struts 2.0中com.opensymphony.xwork2.ActionContext类.我们可以通过它的静态方法getContext()获取当前 Action的上下文对象. 另外,org.apache.struts2.ServletActionContext作为辅助类(Helper Class),可以帮助您快捷地获得这几个对象.

HttpServletRequest request = ServletActionContext.getRequest();HttpServletResponse response = ServletActionContext.getResponse();HttpSession session = request.getSession();

例6 classes/tutorial/NonIoCServlet.java

 1 package tutorial;2 3 import javax.servlet.http.HttpServletRequest;4 5 import javax.servlet.http.HttpServletResponse;6 7 import javax.servlet.http.HttpSession;8 9 import org.apache.struts2.ServletActionContext;
10
11 import com.opensymphony.xwork2.ActionContext; 12 13 import com.opensymphony.xwork2.ActionSupport; 14 15 Public class NonIoCServletextends ActionSupport { 16 17   private String message; 18 19 20 21   public String getMessage() { 22 23     return message; 24 25   } 26 27   HttpServletRequest request = ServletActionContext.getRequest(); 28 29   HttpServletResponse response = ServletActionContext.getResponse(); 30 31   HttpSession session = request.getSession(); 32 33 34 35   @Override 36 37   public String execute() { 38 39     ActionContext.getContext().getSession().put("msg", "Hello World from Session!");[A2] 40 41 42 43     StringBuffer sb =new StringBuffer("Message from request: "); 44 45     sb.append(request.getParameter("msg")); 46 47 48 49     sb.append("<br>Response Buffer Size: "); 50 51     sb.append(response.getBufferSize()); 52 53 54 55     sb.append("<br>Session ID: "); 56 57     sb.append(session.getId());[A3] 58 59 60 61     message = sb.toString(); //转换为字符串。 62 63     return SUCCESS; 64 65   } 66 67 } //与LoginAction类似的方法。

如果你只是想访问session的属性(Attribute),你也可以通过ActionContext.getContext().getSession()获取或添加session范围(Scoped)的对象.[A1]

B、IoC方式

要使用IoC方式,我们首先要告诉IoC容器(Container)想取得某个对象的意愿,通过实现相应的接口做到这点.具体实现,请参考例6 IocServlet.java.

例6 classes/tutorial/IoCServlet.java

 1 package tutorial;
 2
 3 import java.util.Map;
 4
 5 import javax.servlet.http.HttpServletRequest;
 6
 7 import javax.servlet.http.HttpServletResponse;
 8
 9 import javax.servlet.http.HttpSession;
10
11 import org.apache.struts2.interceptor.ServletRequestAware;
12
13 import org.apache.struts2.interceptor.ServletResponseAware;
14
15 import org.apache.struts2.interceptor.SessionAware;
16
17 import com.opensymphony.xwork2.ActionContext;
18
19 import com.opensymphony.xwork2.ActionSupport;
20
21 public class IoCServlet extends ActionSupport implements SessionAware,  ServletRequestAware, ServletResponseAware {
22
23   private String message;
24
25   private Map att;
26
27   private HttpServletRequest request;
28
29   private HttpServletResponse response;
30
31
32
33   public String getMessage() {
34
35     return message;
36
37   }
38
39   public void setSession(Map att) {
40
41     this.att = att;
42
43   }[A5]
44
45   publicvoid setServletRequest(HttpServletRequest request) {
46
47     this.request = request;
48
49   }
50
51   publicvoid setServletResponse(HttpServletResponse response) {
52
53     this.response = response;
54
55   }[A5]
56
57
58
59   @Override
60
61   public String execute() {
62
63     att [A6]  .put("msg", "Hello World from Session!");
64
65
66
67     HttpSession session = request.getSession();
68
69
70
71     StringBuffer sb =new StringBuffer("Message from request: ");
72
73     sb.append(request.getParameter("msg"));
74
75     sb.append("<br>Response Buffer Size: ");
76
77     sb.append(response.getBufferSize());
78
79     sb.append("<br>Session ID: ");
80
81     sb.append(session.getId());
82
83
84
85     message = sb.toString();
86   
87     return SUCCESS;
88
89   }
90
91 }

例6 Servlet.jsp

<%@ page contentType="text/html; charset=UTF-8" %><%@ taglib prefix="s" uri="/struts-tags"%><html><head><title>Hello World!</title></head><body><h2><s:property value="message" escape="false"/><br>Message from session: <s:property value="#session.msg"/></h2></body></html>

例6 classes/struts.xml中NonIocServlet和IoCServlet Action的配置

<action name="NonIoCServlet" class="tutorial.NonIoCServlet"><result>/Servlet.jsp</result></action><action name="IoCServlet" class="tutorial.IoCServlet"><result>/Servlet.jsp</result></action>

 运行Tomcat,在浏览器地址栏中键入http://localhost:8080/Struts2_Action /NonIoCServlet.action?msg=Hello World! 或http://localhost:8080/Struts2_Action/IoCServlet.action?msg=Hello World!

 在Servlet.jsp中,我用了两次property标志,第一次将escape设为false为了在JSP中输出<br>转行,第二次的value中的OGNL为"#session.msg",它的作用与session.getAttribute("msg")等同.

 

附:ActionContext的常用方法(来自Struts2.0  API)

(一)get

public Object get(Object key)

Returns a value that is stored in the current ActionContext by doing a lookup using the value's key.

Parameters:

key- the key used to find the value.

Returns:

the value that was found using the key or null if the key was not found.

(二)put

public void put(Object key, Object value)

Stores a value in the current ActionContext. The value can be looked up using the key.

Parameters:

key- the key of the value.

value- the value to be stored.

(三)getContext

public static ActionContext getContext()

Returns the ActionContext specific to the current thread.

Returns:

the ActionContext for the current thread, is never null.

(四)getSession

public Map getSession()

Gets the Map of HttpSession values when in a servlet environment or a generic session map otherwise.

Returns:

the Map of HttpSession values when in a servlet environment or a generic session map otherwise.

 ()setSession

public void setSession(Map session)

Sets a map of action session values.

Parameters:

session- the session values.

 

 

Struts2action类继承

com.opensymphony.xwork2.ActionSupport类的常用方法

 

addFieldError  //该方法主要用于验证的方法之中

public void addFieldError(String fieldName,  String errorMessage)

Description copied from interface: ValidationAware

Add an error message for a given field.

Specified by:

addFieldErrorin interface ValidationAware

Parameters:

fieldName- name of field

errorMessage- the error message

validate[A7]

public void validate()

A default implementation that validates nothing. Subclasses should override this method to provide validations.

Specified by:

validatein interface Validateable


这一点比较的重要,例如:ActionContext.getContext().getSession().put("user", "value");

与右上角的是一个模式。

Java语法基础,使用stringBuffer。

对属性(实例)设置setter方法。

方法的来源,见后面补充的常用方法:

public void setSession(Map session)

Sets a map of action session values. 设置session值,

Parameters:

session- the session values.

为当前的session,所以可以调用put方法。详细信息见补充的知识。

常用于校验登陆程序的账号和密码是否为空,可以加入addFieldError方法。例如public void validate() {

if (null == login.getUserID() || "".equals(login.getUserID())) {         this.addFieldError("login.userID", "学号不能为空");       }

if (null == login.getUserPassword()              ||"".equals(login.getUserPassword())) {         this.addFieldError("login.userPassword", "密码不能为空");    }

}

转载于:https://www.cnblogs.com/x_wukong/p/3887737.html

Struts2中ActionContext和ServletActionContext相关推荐

  1. Struts2中ActionContext介绍

    来源:http://blog.csdn.net/alex197963/article/details/2219912 在Web应用程序开发中,除了将请求参数自动设置到Action的字段中,我们往往也需 ...

  2. java actioncontext_关于struts2中ActionContext的实现原理

    北京,雾霾天气阻止了今天的马拉松之行,蜗居一天.为一个问题"struts2如何保证ActionContext每次取的都是本次请求所对应的实例?",给一个网友解释了半天. 首先,我们 ...

  3. struts2中 ServletActionContext与ActionContext区别

    1. ActionContext 在Struts2开发中,除了将请求参数自动设置到Action的字段中,我们往往也需要在Action里直接获取请求(Request)或会话(Session)的一些信息, ...

  4. 在Struts2中使用ValueStack、ActionContext、ServletContext、request、session等

    目录(?) [-] ValueStack 如何得到值栈: 如何将对象存入值栈: 让值栈执行表达式来获得值: 在JSP中跳过栈顶元素直接访问第二层: 在JSP中访问值栈对象本身(而不是它们的属性) Ac ...

  5. Struts2中action获取request、response、session的方式

    2019独角兽企业重金招聘Python工程师标准>>> 第一种方式,非IoC(Spring中的控制反转)方式: package com.action; import java.uti ...

  6. 在struts2中訪问servletAPI

    在struts2中訪问servletAPI,通俗点也就是使用servlet中的两个对象request对象和response对象. 前几天看到一个CRM项目的源代码,里面使用request对象和resp ...

  7. Struts2 中的数据传输的几种方式

    原文地址:http://blog.csdn.net/li_tengfei/article/details/6098126 1.     如何将参数从界面传递到Action? 你可以把Struts2中的 ...

  8. Struts2中的action类

    Struts2中的action类 action类在Struts2中承担了Model(模型)的角色,主要用于处理业务逻辑并存放HTTP请求处理过程中各个变量的值. 在Struts2里面,Action充当 ...

  9. struts2中实现文件的上传

    struts2中实现文件的上传 文件上传的action,同时过滤上传的文件格式只对满足要求的格式支持上传 package com.inspur.action; import java.io.File; ...

最新文章

  1. python中文软件-Python
  2. 阿里云python面试题_Python金典面试题
  3. [蓝桥杯][2015年第六届真题]生命之树(树形dp)
  4. H5开发中常用的js方法
  5. angular jwt_Angular5 JWT身份验证(Spring Boot安全性)
  6. 内部类访问局部变量的时候,为什么变量必须加上final修饰
  7. 深圳不完全启示录之初来乍到----1
  8. Sonar6.0应用之一:基于centos7.2安装
  9. 一个老程序员对数据库的一点纠结
  10. Ubuntu下vsftp安装和配置
  11. mysql update textl类型_MySQL 字段类型参考
  12. 域账户登录时提示“你的账户配置不允许使用这台电脑。请试一下其他电脑” 解决方案
  13. android抖音布局,Android快速集成抖音分享
  14. CS客户端渗透测试(二)信息收集与流量分析
  15. SQLite System.DllNotFoundException for SQLite.Interop.dll
  16. 霹雳吧啦Wz语义分割学习笔记P8
  17. postgresql-9.5.5数据库安装教程
  18. 我的世界服务器上次死亡位置,我的世界怎么传送到上次死的地方
  19. 复印机维修保养的常识
  20. php+创建微信标签,微信公众号——创建标签,给粉丝打标签。

热门文章

  1. linux nginx 代理iis,nginx 系列 linux下安装以及配置IIS分发
  2. dos启动盘访问硬盘
  3. 微信小程序 子组件调用父组件方法
  4. 手写的奇怪vector
  5. 吃货莫跑小小程序冲刺07
  6. C# 之 6.0 新特性
  7. 程序人生之回顾大学前两年----第二篇
  8. LeetCode Combination Sum
  9. step1 . day5 C语言基础练习之日历(使用函数调用,优化至元年开始时间)
  10. Intellij IDEA + Maven + Cucumber 项目 (三):简单解释RunCukesTest.java