Struts2获取request、session、application的三种方法

2024-06-10 00:32

本文主要是介绍Struts2获取request、session、application的三种方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1、使用ActionContext访问Servlet API

      Struts2提供了一个ActionContext类,该类被称为Action上下文或者Action环境,Action可以通过该类来访问最常用的Servlet API。

①、getContext():静态方法,获取当前的ActionContext对象。

②、getSession():返回一个Map对象,该对象模拟了session作用域。

③、getApplication:返回一个Map对象,该对象模拟了Application作用域。

④、get(String key):对该方法传入“request”参数,即可返回一个Object对象,该对象模拟了request作用域。

⑤、getParameters():返回一个Map对象,该对象中保存了浏览器上传的参数。

特点:作用域都是由Action自己获取的,获取对象和使用对象的代码放在一个类中。

public class UserAction extends ActionSupport {private User user;public User getUser() {return user;}public void setUser(User user) {this.user = user;}public String Login(){HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get("request");request.setAttribute("username", user.getUserName());
		//也可以转Map哦
		//Map<String,Object> request2 = 
		//	    (Map<String, Object>) ActionContext.getContext().get("request");
	      //request2.put("username", user.getUserName());
		return "success";}
}

2、以IoC的方式访问Servlet API

      Action类中只保留使用这些对象的代码,而获取对象的代码由Struts2来实现。

public class UserAction extends ActionSupport implements RequestAware,SessionAware,ApplicationAware {private Map<String, Object> request;private Map<String, Object> session;private Map<String, Object> application;public void setApplication(Map application) {this.application = application;}public void setSession(Map session) {this.session = session;		}public void setRequest(Map request) {this.request = request;		}public String Login(){//转换成HttpServletRequest,根据需要来HttpServletRequest req=(HttpServletRequest)request;String name = req.getParameter("username");req.setAttribute("username", "张三");return "success";}}
        在上面代码中,Action实现了 RequestAware,SessionAware,ApplicationAware接口,这样Struts2就可以为Action注入request、session、application对象了。

以session为例,Struts2取得session对象,当UserAction被创建时,Struts2会判断UserAction是否实现了SessionAware接口,若实现,就会调用UserAction的setSession()

方法,并把session作为参数传入该方法。该方法的"this.session = session;"代码会把session保存为一个成员变量,这样就实现了session对象注入。


3、以耦合方式访问Servlet API

      即ServletActionContext类,这个类继承了ActionContext类,它提供了直接与Servlet相关对象访问的功能,它可以取得的对象有:
(1)javax.servlet.http.HttpServletRequest : HTTPservlet请求对象
(2)javax.servlet.http.HttpServletResponse : HTTPservlet相应对象
(3)javax.servlet.ServletContext : Servlet上下文信息
(4)javax.servlet.jsp.PageContext : Http页面上下文

ServletActionContext源码:

package org.apache.struts2;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.struts2.dispatcher.mapper.ActionMapping;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.PageContext;
import java.util.Map;/*** Web-specific context information for actions. This class subclasses <tt>ActionContext</tt> which* provides access to things like the action name, value stack, etc. This class adds access to* web objects like servlet parameters, request attributes and things like the HTTP session.*/
public class ServletActionContext extends ActionContext implements StrutsStatics {private static final long serialVersionUID = -666854718275106687L;public static final String STRUTS_VALUESTACK_KEY = "struts.valueStack";public static final String ACTION_MAPPING = "struts.actionMapping";@SuppressWarnings("unused")private ServletActionContext(Map context) {super(context);}/*** Gets the current action context** @param req The request* @return The current action context*/public static ActionContext getActionContext(HttpServletRequest req) {ValueStack vs = getValueStack(req);if (vs != null) {return new ActionContext(vs.getContext());} else {return null;}}/*** Gets the current value stack for this request** @param req The request* @return The value stack*/public static ValueStack getValueStack(HttpServletRequest req) {return (ValueStack) req.getAttribute(STRUTS_VALUESTACK_KEY);}/*** Gets the action mapping for this context** @return The action mapping*/public static ActionMapping getActionMapping() {return (ActionMapping) ActionContext.getContext().get(ACTION_MAPPING);}/*** Returns the HTTP page context.** @return the HTTP page context.*/public static PageContext getPageContext() {return (PageContext) ActionContext.getContext().get(PAGE_CONTEXT);}/*** Sets the HTTP servlet request object.** @param request the HTTP servlet request object.*/public static void setRequest(HttpServletRequest request) {ActionContext.getContext().put(HTTP_REQUEST, request);}/*** Gets the HTTP servlet request object.** @return the HTTP servlet request object.*/public static HttpServletRequest getRequest() {return (HttpServletRequest) ActionContext.getContext().get(HTTP_REQUEST);}/*** Sets the HTTP servlet response object.** @param response the HTTP servlet response object.*/public static void setResponse(HttpServletResponse response) {ActionContext.getContext().put(HTTP_RESPONSE, response);}/*** Gets the HTTP servlet response object.** @return the HTTP servlet response object.*/public static HttpServletResponse getResponse() {return (HttpServletResponse) ActionContext.getContext().get(HTTP_RESPONSE);}/*** Gets the servlet context.** @return the servlet context.*/public static ServletContext getServletContext() {return (ServletContext) ActionContext.getContext().get(SERVLET_CONTEXT);}/*** Sets the current servlet context object** @param servletContext The servlet context to use*/public static void setServletContext(ServletContext servletContext) {ActionContext.getContext().put(SERVLET_CONTEXT, servletContext);}
}


eg:

public class UserAction extends ActionSupport{private HttpServletRequest request;public String Login(){request = ServletActionContext.getRequest();//request的获得必须在具体的方法中实现  String name = request.getParameter("username");request.setAttribute("username", "张三");return "success";}}

ServletActionContext和ActionContext有着一些重复的功能,在我们的Action中,该如何去抉择呢? 我们遵循的原则是:如果ActionContext能够实现我们的功能,那最好就不要使用ServletActionContext,让我们的Action尽量不要直接去访问Servlet的相关对象.
注意:在使用ActionContext时有一点要注意: 不要在Action的构造函数里使用ActionContext.getContext(),因为这个时候ActionContext里的一些值也许没有设置,这时通过ActionContext取得的值也许是null;同样,HttpServletRequest req = ServletActionContext.getRequest()也不要放在构造函数中,也不要直接将req作为类变量给其赋值。至于原因,在ActionContext类中actionContext对象的创建为:   static ThreadLocal actionContext = new ActionContextThreadLocal(),ActionContextThreadLocal是实现ThreadLocal的一个内部类.ThreadLocal可以命名为"线程局部变量",它为每一个使用该变量的线程都提供一个变量值的副本,使每一个线程都可以独立地改变自己的副本,而不会和其它线程的副本冲突.这样,我们ActionContext里的属性只会在对应的当前请求线程中可见,从而保证它是线程安全的。ActionContext是线程安全的,而ServletActionContext继承自ActionContext,所以ServletActionContext也线程安全,线程安全要求每个线程都独立进行,所以req的创建也要求独立进行,所以ServletActionContext.getRequest()这句话不要放在构造函数中,也不要直接放在类中,而应该放在每个具体的方法体中(eg:login()、query()、insert()等),这样才能保证每次产生对象时独立的建立了一个req。 

 

这篇关于Struts2获取request、session、application的三种方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1046743

相关文章

Java 方法重载Overload常见误区及注意事项

《Java方法重载Overload常见误区及注意事项》Java方法重载允许同一类中同名方法通过参数类型、数量、顺序差异实现功能扩展,提升代码灵活性,核心条件为参数列表不同,不涉及返回类型、访问修饰符... 目录Java 方法重载(Overload)详解一、方法重载的核心条件二、构成方法重载的具体情况三、不构

SQL中如何添加数据(常见方法及示例)

《SQL中如何添加数据(常见方法及示例)》SQL全称为StructuredQueryLanguage,是一种用于管理关系数据库的标准编程语言,下面给大家介绍SQL中如何添加数据,感兴趣的朋友一起看看吧... 目录在mysql中,有多种方法可以添加数据。以下是一些常见的方法及其示例。1. 使用INSERT I

Python中反转字符串的常见方法小结

《Python中反转字符串的常见方法小结》在Python中,字符串对象没有内置的反转方法,然而,在实际开发中,我们经常会遇到需要反转字符串的场景,比如处理回文字符串、文本加密等,因此,掌握如何在Pyt... 目录python中反转字符串的方法技术背景实现步骤1. 使用切片2. 使用 reversed() 函

Python中将嵌套列表扁平化的多种实现方法

《Python中将嵌套列表扁平化的多种实现方法》在Python编程中,我们常常会遇到需要将嵌套列表(即列表中包含列表)转换为一个一维的扁平列表的需求,本文将给大家介绍了多种实现这一目标的方法,需要的朋... 目录python中将嵌套列表扁平化的方法技术背景实现步骤1. 使用嵌套列表推导式2. 使用itert

Python使用pip工具实现包自动更新的多种方法

《Python使用pip工具实现包自动更新的多种方法》本文深入探讨了使用Python的pip工具实现包自动更新的各种方法和技术,我们将从基础概念开始,逐步介绍手动更新方法、自动化脚本编写、结合CI/C... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

在Linux中改变echo输出颜色的实现方法

《在Linux中改变echo输出颜色的实现方法》在Linux系统的命令行环境下,为了使输出信息更加清晰、突出,便于用户快速识别和区分不同类型的信息,常常需要改变echo命令的输出颜色,所以本文给大家介... 目python录在linux中改变echo输出颜色的方法技术背景实现步骤使用ANSI转义码使用tpu

Conda与Python venv虚拟环境的区别与使用方法详解

《Conda与Pythonvenv虚拟环境的区别与使用方法详解》随着Python社区的成长,虚拟环境的概念和技术也在不断发展,:本文主要介绍Conda与Pythonvenv虚拟环境的区别与使用... 目录前言一、Conda 与 python venv 的核心区别1. Conda 的特点2. Python v

Spring Boot中WebSocket常用使用方法详解

《SpringBoot中WebSocket常用使用方法详解》本文从WebSocket的基础概念出发,详细介绍了SpringBoot集成WebSocket的步骤,并重点讲解了常用的使用方法,包括简单消... 目录一、WebSocket基础概念1.1 什么是WebSocket1.2 WebSocket与HTTP

Python使用OpenCV实现获取视频时长的小工具

《Python使用OpenCV实现获取视频时长的小工具》在处理视频数据时,获取视频的时长是一项常见且基础的需求,本文将详细介绍如何使用Python和OpenCV获取视频时长,并对每一行代码进行深入解析... 目录一、代码实现二、代码解析1. 导入 OpenCV 库2. 定义获取视频时长的函数3. 打开视频文

SQL Server配置管理器无法打开的四种解决方法

《SQLServer配置管理器无法打开的四种解决方法》本文总结了SQLServer配置管理器无法打开的四种解决方法,文中通过图文示例介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的... 目录方法一:桌面图标进入方法二:运行窗口进入检查版本号对照表php方法三:查找文件路径方法四:检查 S