如何在Struts 2操作中获取Servlet会话,请求,响应,上下文属性

Struts 2 Action classes doesn’t provide any methods to get Servlet API Request, Response, Session and attributes. But sometimes we need to access these in action classes, for example checking HTTP method or to work with session attributes or to set cookies or headers in response.

Struts 2 Action类不提供任何获取Servlet API请求,响应,会话和属性的方法。 但是有时我们需要在操作类中访问它们,例如检查HTTP方法或使用会话属性或设置cookie或标头作为响应。

That’s why Struts 2 API provides a bunch of interfaces that we can implement in action classes to inject these objects in Action classes. All of these interfaces end with “Aware” and defined in org.apache.struts2.interceptor package.

这就是为什么Struts 2 API提供了许多接口的原因,我们可以在操作类中实现这些接口,以将这些对象注入到操作类中。 所有这些接口均以“ Aware”结尾,并在org.apache.struts2.interceptor程序包中定义。

All of these interfaces declares setter methods through which Struts 2 API injects Servlet API components in action classes. It’s a great example of Dependency Injection in Java EE frameworks.

所有这些接口都声明了setter方法,Struts 2 API通过这些方法将Action类中的Servlet API组件注入。 这是Java EE框架中依赖注入的一个很好的例子。

These *Aware interfaces are:

这些* Aware接口为:

  1. SessionAware: This interface provides access to session attributes in action classes and declare a single method setSession(Map<String, Object> sessionAttributes). Note that we can’t get HttpSession by implementing this interface, this is just to get access to the session attributes.

    SessionAware :此接口提供对操作类中的会话属性的访问,并声明单个方法setSession(Map<String, Object> sessionAttributes) 。 请注意,我们无法通过实现此接口来获取HttpSession,这仅仅是为了访问会话属性。
  2. ApplicationAware: This interface provides access to context attributes in action classes as Map. We can add attributes to application context by putting values in the context map. This interface declares single method setApplication(Map<String, Object> applicationAttributes).

    ApplicationAware :此接口提供对操作类中的上下文属性(如Map)的访问。 我们可以通过将值放在上下文映射中来向应用程序上下文添加属性。 此接口声明单个方法setApplication(Map<String, Object> applicationAttributes)
  3. RequestAware: This interface provides access to request attributes in action classes, it contains single method setRequest(Map<String, Object> requestAttr). This interface is only applicable if Action classes are used in Servlet environment. Since this interface makes the Action tied to a servlet environment, so it should be avoided if possible since things like unit testing will become more difficult.

    RequestAware :此接口提供对操作类中的请求属性的访问,它包含单个方法setRequest(Map<String, Object> requestAttr) 。 仅当在Servlet环境中使用Action类时,此接口才适用。 由于此接口将Action绑定到Servlet环境,因此应尽可能避免这样做,因为单元测试之类的事情将变得更加困难。
  4. ServletRequestAware: We can implement this interface in action classes to get access to HttpServletRequest object. This interface is only relevant if the Action is used in a servlet environment. It defines a single method as setServletRequest(HttpServletRequest request).

    ServletRequestAware :我们可以在操作类中实现此接口,以访问HttpServletRequest对象。 仅当在Servlet环境中使用Action时,此接口才有意义。 它定义了一个方法作为setServletRequest(HttpServletRequest request)
  5. ServletResponseAware: Struts 2 action classes can implement this interface to get access to the HttpServletResponse object. We can then use response object to add headers or cookies. It defines a single method as setServletResponse(HttpServletResponse response).

    ServletResponseAware :Struts 2动作类可以实现此接口来访问HttpServletResponse对象。 然后,我们可以使用响应对象添加标题或cookie。 它定义了一个方法作为setServletResponse(HttpServletResponse response)
  6. CookiesAware: This interface is intended to provide access to cookies in request in the form of Map. It contains single method setCookiesMap(Map<String,String> cookies). To work with this interface, there are two interceptors defined in struts-default package as:
    <interceptor name="cookie" class="org.apache.struts2.interceptor.CookieInterceptor"/>
    <interceptor name="cookieProvider" class="org.apache.struts2.interceptor.CookieProviderInterceptor"/>

    But they are not part of defaultStack interceptors stack, so we need to include them for action class like below.

    However these interceptors are very new and in my testing with Struts 2 version 2.3.15.1, I didn’t find it to be working. I looked into Struts 2 API docs but didn’t find any help on this. I will update the post if I find anything or if you know what is missing, please let us know through comments. The workaround is to use ServletRequestAware and ServletResponseAware interface to get the request cookies or to set cookies in response.

    CookiesAware :此接口旨在以请求的形式提供对Map形式的cookie的访问。 它包含单个方法setCookiesMap(Map<String,String> cookies) 。 要使用此接口,在struts-default包中定义了两个拦截器:
    <interceptor name="cookie" class="org.apache.struts2.interceptor.CookieInterceptor"/>
    <interceptor name="cookieProvider" class="org.apache.struts2.interceptor.CookieProviderInterceptor"/>

    但是它们不是defaultStack拦截器堆栈的一部分,因此我们需要将它们包括在动作类中,如下所示。

    但是这些拦截器是非常新的,在我对Struts 2版本2.3.15.1的测试中,我发现它没有起作用。 我查看了Struts 2 API文档,但没有找到任何帮助。 如果我发现任何问题,或者如果您知道缺少什么,我将更新该帖子,请通过评论告知我们。 解决方法是使用ServletRequestAware和ServletResponseAware接口获取请求cookie或设置cookie作为响应。

  7. PrincipalAware: We can implement this interface in action class to get Principal information from HttpServletRequest object. This interface works with PrincipalProxy to provide user id, principal details.

    PrincipalAware :我们可以在操作类中实现此接口,以从HttpServletRequest对象获取Principal信息。 此接口与PrincipalProxy一起使用以提供用户ID和主体详细信息。

Let’s see all these interfaces in action with a simple Struts 2 project. Our final project structure looks like below image.

让我们通过一个简单的Struts 2项目查看所有这些接口。 我们的最终项目结构如下图所示。

Struts2配置文件 (Struts2 Configuration Files)

web.xml

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
	xmlns="https://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>Struts2Example</display-name>

	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
	</filter>

	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
</web-app>

pom.xml

pom.xml

<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>Struts2Example</groupId>
	<artifactId>Struts2Example</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	
	<dependencies>
		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-core</artifactId>
			<version>2.3.15.1</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.3</version>
				<configuration>
					<warSourceDirectory>WebContent</warSourceDirectory>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
		</plugins>
		<finalName>${project.artifactId}</finalName>
	</build>
</project>

struts.xml

struts.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"https://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
	<constant name="struts.convention.result.path" value="/"></constant>
	<package name="user" namespace="/" extends="struts-default">
		<action name="login">
			<result>/login.jsp</result>
		</action>
		<action name="home" class="com.journaldev.struts2.actions.HomeAction">
			<interceptor-ref name="cookie"></interceptor-ref>
			<interceptor-ref name="cookieProvider"></interceptor-ref>
			<interceptor-ref name="defaultStack"></interceptor-ref>
			<result name="success">/home.jsp</result>
		</action>

	</package>

</struts>

The configuration files are self explanatory and easy to understand.

配置文件不言自明,易于理解。

Struts2 JSP页面 (Struts2 JSP Pages)

login.jsp

login.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Login Page</title>
</head>
<body>
<s:form action="home" method="post">
<s:textfield label="User Name" name="user"></s:textfield>
<s:textfield label="Password" name="password"></s:textfield>
<s:submit label="Login"></s:submit>
</s:form>
</body>
</html>

home.jsp

home.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Home Page</title>
</head>
<body>
<h3>Welcome <s:property value="user"/></h3>
</body>
</html>

JSP pages are also very simple and just used to send some data in request and then use them in result page.

JSP页面也非常简单,仅用于在请求中发送一些数据,然后在结果页面中使用它们。

Struts2动作类 (Struts2 Action Class)

HomeAction.java

HomeAction.java

package com.journaldev.struts2.actions;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.interceptor.ApplicationAware;
import org.apache.struts2.interceptor.CookiesAware;
import org.apache.struts2.interceptor.PrincipalAware;
import org.apache.struts2.interceptor.PrincipalProxy;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;

public class HomeAction extends ActionSupport implements SessionAware,
		ApplicationAware, CookiesAware, RequestAware, ServletRequestAware,
		ServletResponseAware, PrincipalAware {

	private static final long serialVersionUID = 1L;

	@Override
	public String execute() {
		System.out.println("Request Method: " + request.getMethod());
		System.out.println("Using HTTPS?: " + principalProxy.isRequestSecure());
		System.out.println("Request Cookies:" + requestCookies);
		// add a cookie to response
		response.addCookie(new Cookie("user", "Pankaj"));
		if (requestCookies == null)
			requestCookies = new HashMap<String, String>();
		requestCookies.put("test", "test");

		System.out.println("Session Attributes: " + sessionAttributes);
		// add session attribute
		HttpSession mySession = request.getSession();
		mySession.setAttribute("user", "Pankaj");
		//OR
		sessionAttributes.put("test", "Test");

		System.out.println("Context Attributes: "
				+ contextAttributes.get("user"));
		// add context attribute
		contextAttributes.put("user", "Pankaj");

		System.out.println("Request Attributes: " + requestAttributes);
		return SUCCESS;
	}

	// variables for *Aware interfaces
	private PrincipalProxy principalProxy = null;
	private HttpServletRequest request = null;
	private HttpServletResponse response = null;
	private Map<String, Object> requestAttributes = null;
	private Map<String, Object> sessionAttributes = null;
	private Map<String, Object> contextAttributes = null;
	private Map<String, String> requestCookies = null;

	@Override
	public void setPrincipalProxy(PrincipalProxy principalProxy) {
		this.principalProxy = principalProxy;
	}

	@Override
	public void setServletResponse(HttpServletResponse httpServletResponse) {
		this.response = httpServletResponse;
	}

	@Override
	public void setServletRequest(HttpServletRequest httpServletRequest) {
		this.request = httpServletRequest;
	}

	@Override
	public void setRequest(Map<String, Object> requestAttr) {
		this.requestAttributes = requestAttr;
	}

	@Override
	public void setCookiesMap(Map<String, String> cookies) {
		this.requestCookies = cookies;
	}

	@Override
	public void setApplication(Map<String, Object> applicationAttributes) {
		this.contextAttributes = applicationAttributes;
	}

	@Override
	public void setSession(Map<String, Object> sessionAttr) {
		this.sessionAttributes = sessionAttr;
	}

	// java bean properties to hold request attributes
	private String user;
	private String password;

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}

A single action class implementing all the *Aware interfaces and using them to log some data in server log files.

一个实现所有* Aware接口并使用它们将某些数据记录在服务器日志文件中的动作类。

Once we execute the login action and then hit home action multiple times, we get following logs.

一旦执行了登录操作,然后多次击中主页操作,我们就会获得以下日志。

Request Method: POST
Using HTTPS?: false
Request Cookies:{}
Session Attributes: {}
Context Attributes: null
Request Attributes: {struts.valueStack=com.opensymphony.xwork2.ognl.OgnlValueStack@662fe032, __cleanup_recursion_counter=1, struts.actionMapping=ActionMapping{name='home', namespace='/', method='null', extension='action', params=null, result=null}}
Request Method: POST
Using HTTPS?: false
Request Cookies:{}
Session Attributes: {test=Test, user=Pankaj}
Context Attributes: Pankaj
Request Attributes: {__cleanup_recursion_counter=1, struts.valueStack=com.opensymphony.xwork2.ognl.OgnlValueStack@749cd006, struts.actionMapping=ActionMapping{name='home', namespace='/', method='null', extension='action', params=null, result=null}}

Notice that request cookies are NULL, however I checked request and response in browser and it’s sending cookies in request.

请注意,请求cookie为NULL,但是我在浏览器中检查了请求和响应,并在请求中发送了cookie。

That’s all for accessing Servlet API core components in Struts 2 Action classes. It’s simple and elegant to use.

这就是访问Struts 2 Action类中的Servlet API核心组件的全部。 使用起来简单而优雅。

翻译自: https://www.journaldev.com/2203/get-servlet-session-request-response-context-attributes-struts-2-action

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
目录 1.简介 2.如何使用示例代码 3.我为什么要学习Wicket? 3.1。我们都喜欢意大利面:-) ... 3.2。面向组件的框架 - 概述 3.3。面向组件的Web开发框架的优点 3.4。Wicket与其他面向组件的框架相比 威克特说“你好世界!” 4.1。Wicket分发和模块 4.2。Wicket应用程序的配置 4.3。HomePage类 4.4。Wicket链接 4.5。摘要 5. Wicket作为页面布局管理器 5.1。页眉,页脚,左侧菜单,内容等... 5.2。这是继承! 5.3。划分et impera! 5.4。使用wicket标记继承:扩展标记 5.5。摘要 6.保持对HTML的控制 6.1。隐藏或禁用组件 6.2。修改标签属性 6.3。生成标记属性“id” 6.4。使用WebMarkupContainer创建内嵌面板 6.5。使用标记片段 6.6。将标题内容添加到最终页面 6.7。在我们的页面/面板使用存根标记 6.8。如何仅渲染组件主体 6.9。用wicket隐藏装饰元素:enclosure标签 6.10。使用Border包围现有标记 6.11。摘要 7.组件生命周期 7.1。组件的生命周期阶段 7.2。组件生命周期的钩子方法 7.3。初始化阶段 7.4。渲染阶段 7.5。删除阶段 7.6。独立舞台 7.7。摘要 8.页面版本控制和缓存 8.1。有状态页面与无状态页面 8.2。有状态页面 8.3。无状态页面 8.4。摘要 9.在请求处理的引擎盖下 9.1。类应用和请求处理 9.2。请求响应类 9.3。请求处理的“主管” - RequestCycle 9.4。会话类 9.5。异常处理 9.6。摘要 10. Wicket链接和URL生成 10.1。PageParameters 10.2。可收藏的链接 10.3。使用标记wicket自动创建可收藏的链接:链接 10.4。外部链接 10.5。无状态链接 10.6。生成结构清晰的URL 10.7。摘要 11. Wicket模型和表格 11.1。什么是模特? 11.2。IModel和Lambda 11.3。模型和JavaBeans 11.4。Wicket形式 11.5。组件DropDownChoice 11.6。模型链 11.7。可拆卸型号 11.8。在组件使用多个模型 11.9。使用型号! 11.10。摘要 12. Wicket详细说明 12.1。默认表单处理 12.2。表单验证和反馈消息 12.3。输入值转换 12.4。使用JSR 303验证 12.5。使用IFormSubmittingComponent提交表单 12.6。嵌套表格 12.7。多行文字输入 12.8。上传文件 12.9。使用FormComponentPanel创建复杂的表单组件 12.10。无国籍形式 12.11。使用单选按钮和复选框 12.12。使用ListMultipleChoices和Palette选择多个值 12.13。摘要 13.使用继器显示多个项目 13.1。RepeatingView组件 13.2。ListView组件 13.3。RefreshingView组件 13.4。可分页的继器 13.5。摘要 14.组件排队 14.1。标记层次结构和代码 14.2。改进了汽车组件 14.3。组件什么时候出列? 14.4。排队的限制 14.5。摘要 15.与Wicket的国际化 15.1。本土化 15.2。Wicket的本地化 15.3。捆绑查找算法 15.4。组件选择的本地化 15.5。国际化和模型 15.6。摘要 16. Wicket的资源管理 16.1。静态与动态资源 16.2。资源参考 16.3。包资源 16.4。向页眉部分添加资源 16.5。上下文相关资源 16.6。资源依赖性 16.7。使用资源包聚合多个资源 16.8。将JavaScript放在页面正文 16.9。标题贡献者定位 16.10。自定义资源 16.11。安装资源 16.12。Lambda支持 16.13。共享资源 16.14。自定义资源加载 16.15。CssHeaderItem和JavaScriptHeaderItem压缩 16.16。NIO资源 16.17。资源通过模型得出 16.18。摘要 17.与JavaScript集成的示例 17.1。我们想做什么...... 17.2。......以及我们将如何做到这一点 17.3。摘要 18. Wicket高级主题 18.1。通过行为丰富组件 19.使用AJAX 19.1。如何使用AJAX组件和行为 19.2。内置AJAX组件 19.3。内置的AJAX行为 19.4。使用活动指示器 19.5。AJAX请求属性和调用侦听器 19.6。创建自定义AJAX调用侦

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值