Struts 2 简明教程
Struts 2 - Value Stack/OGNL
The Value Stack
值堆栈是一组包含以下对象的对象,这些对象按照给定的顺序排列 −
The value stack is a set of several objects which keeps the following objects in the provided order −
Sr.No |
Objects & Description |
1 |
Temporary Objects There are various temporary objects which are created during execution of a page. For example the current iteration value for a collection being looped over in a JSP tag. |
2 |
The Model Object If you are using model objects in your struts application, the current model object is placed before the action on the value stack. |
3 |
The Action Object This will be the current action object which is being executed. |
4 |
Named Objects These objects include #application, #session, #request, #attr and #parameters and refer to the corresponding servlet scopes. |
可以通过为 JSP、Velocity 或 Freemarker 提供的标记访问值堆栈。我们将使用各种标记,在单独的章节中学习如何使用这些标记来获取和设置 struts 2.0 值堆栈。您可以按如下方式在操作中获取 ValueStack 对象 −
The value stack can be accessed via the tags provided for JSP, Velocity or Freemarker. There are various tags which we will study in separate chapters, are used to get and set struts 2.0 value stack. You can get valueStack object inside your action as follows −
ActionContext.getContext().getValueStack()
一旦您获得 ValueStack 对象,就可以使用以下方法来操作该对象 −
Once you have a ValueStack object, you can use the following methods to manipulate that object −
Sr.No |
ValueStack Methods & Description |
1 |
Object findValue(String expr) Find a value by evaluating the given expression against the stack in the default search order. |
2 |
CompoundRoot getRoot() Get the CompoundRoot which holds the objects pushed onto the stack. |
3 |
Object peek() Get the object on the top of the stack without changing the stack. |
4 |
Object pop() Get the object on the top of the stack and remove it from the stack. |
5 |
*void push(Object o)*Put this object onto the top of the stack. |
6 |
void set(String key, Object o) Sets an object on the stack with the given key so it is retrievable by findValue(key,…) |
7 |
void setDefaultType(Class defaultType) Sets the default type to convert to if no type is provided when getting a value. |
8 |
void setValue(String expr, Object value) Attempts to set a property on a bean in the stack with the given expression using the default search order. |
9 |
int size() Get the number of objects in the stack. |
The OGNL
Object-Graph Navigation Language (OGNL)是一种功能强大的表达式语言,用于引用和操作 ValueStack 上的数据。OGNL 还帮助进行数据传输和类型转换。
The Object-Graph Navigation Language (OGNL) is a powerful expression language that is used to reference and manipulate data on the ValueStack. OGNL also helps in data transfer and type conversion.
OGNL 非常类似于 JSP 表达式语言。OGNL 以在上下文中拥有 root 或默认对象的想法为基础。可以使用井号符号(即标记符号)来引用默认对象或 root 对象的属性。
The OGNL is very similar to the JSP Expression Language. OGNL is based on the idea of having a root or default object within the context. The properties of the default or root object can be referenced using the markup notation, which is the pound symbol.
如前所述,OGNL 基于上下文,而 Struts 会构建一个 ActionContext 映射以用于 OGNL。ActionContext 映射包含以下内容:
As mentioned earlier, OGNL is based on a context and Struts builds an ActionContext map for use with OGNL. The ActionContext map consists of the following −
-
Application − Application scoped variables
-
Session − Session scoped variables
-
Root / value stack − All your action variables are stored here
-
Request − Request scoped variables
-
Parameters − Request parameters
-
Atributes − The attributes stored in page, request, session and application scope
了解 Action 对象始终在值栈中可用非常重要。所以,如果您的 Action 对象具有属性 “x” 和 “y” ,您可以随时使用它们。
It is important to understand that the Action object is always available in the value stack. So, therefore if your Action object has properties “x” and “y” there are readily available for you to use.
ActionContext 中的对象使用井号符号进行引用,但是,可以直接引用值栈中的对象。
Objects in the ActionContext are referred using the pound symbol, however, the objects in the value stack can be directly referenced.
例如,如果 employee 是一个操作类的属性,那么它可以按如下方式引用:
For example, if employee is a property of an action class, then it can be referenced as follows −
<s:property value = "name"/>
代替
instead of
<s:property value = "#name"/>
如果您在会话中有一个名为“login”的属性,您可以按如下方式检索它:
If you have an attribute in session called "login" you can retrieve it as follows −
<s:property value = "#session.login"/>
OGNL 还支持处理集合,即 Map、List 和 Set。例如,要显示颜色下拉列表,您可以执行以下操作:
OGNL also supports dealing with collections - namely Map, List and Set. For example to display a dropdown list of colors, you could do −
<s:select name = "color" list = "{'red','yellow','green'}" />
OGNL 表达式巧妙地将“red”、“yellow”、“green”解释为颜色,并基于此构建了一个列表。
The OGNL expression is clever to interpret the "red","yellow","green" as colours and build a list based on that.
在后续章节中研究不同标记时,OGNL 表达式将被广泛使用。因此,与其孤立地查看它们,不如让我们在表单标记/控制标记/数据标记和 Ajax 标记部分中使用一些示例来查看它们。
The OGNL expressions will be used extensively in the next chapters when we will study different tags. So rather than looking at them in isolation, let us look at it using some examples in the Form Tags / Control Tags / Data Tags and Ajax Tags section.
ValueStack/OGNL Example
Create Action
让我们考虑以下操作类,在该类中我们将访问 valueStack,然后设置一些键,我们将在我们的视图中使用 OGNL 来访问这些键,即 JSP 页面。
Let us consider the following action class where we are accessing valueStack and then setting few keys which we will access using OGNL in our view, i.e., JSP page.
package com.tutorialspoint.struts2;
import java.util.*;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class HelloWorldAction extends ActionSupport {
private String name;
public String execute() throws Exception {
ValueStack stack = ActionContext.getContext().getValueStack();
Map<String, Object> context = new HashMap<String, Object>();
context.put("key1", new String("This is key1"));
context.put("key2", new String("This is key2"));
stack.push(context);
System.out.println("Size of the valueStack: " + stack.size());
return "success";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
实际上,执行 Struts 2 时会将操作添加到 valueStack 的顶部。所以,将内容放入值栈的通常方式是为值添加到您的操作类添加 getter/setter,然后使用 <s:property> 标记来访问值。但是,我将向您展示 ActionContext 和 ValueStack 在 struts 中如何工作的。
Actually, Struts 2 adds your action to the top of the valueStack when executed. So, the usual way to put stuff on the Value Stack is to add getters/setters for the values to your Action class and then use <s:property> tag to access the values. But I’m showing you how exactly ActionContext and ValueStack work in struts.
Create Views
让我们在 eclipse 项目中的 WebContent 文件夹中创建以下 jsp 文件 HelloWorld.jsp 。如果执行返回成功,则该视图将被显示:
Let us create the below jsp file HelloWorld.jsp in the WebContent folder in your eclipse project. This view will be displayed in case action returns success −
<%@ page contentType = "text/html; charset = UTF-8" %>
<%@ taglib prefix = "s" uri = "/struts-tags" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
Entered value : <s:property value = "name"/><br/>
Value of key 1 : <s:property value = "key1" /><br/>
Value of key 2 : <s:property value = "key2" /> <br/>
</body>
</html>
我们还需要在 WebContent 文件夹中创建 index.jsp ,其内容如下:
We also need to create index.jsp in the WebContent folder whose content is as follows −
<%@ page language = "java" contentType = "text/html; charset = ISO-8859-1"
pageEncoding = "ISO-8859-1"%>
<%@ taglib prefix = "s" uri = "/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h1>Hello World From Struts2</h1>
<form action = "hello">
<label for = "name">Please enter your name</label><br/>
<input type = "text" name = "name"/>
<input type = "submit" value = "Say Hello"/>
</form>
</body>
</html>
Configuration Files
以下为 struts.xml 文件的内容 −
Following is the content of struts.xml file −
<?xml version = "1.0" Encoding = "UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name = "struts.devMode" value = "true" />
<package name = "helloworld" extends = "struts-default">
<action name = "hello"
class = "com.tutorialspoint.struts2.HelloWorldAction"
method = "execute">
<result name = "success">/HelloWorld.jsp</result>
</action>
</package>
</struts>
以下是 web.xml 文件的内容:
Following is the content of web.xml file −
<?xml version = "1.0" Encoding = "UTF-8"?>
<web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns = "http://java.sun.com/xml/ns/javaee"
xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id = "WebApp_ID" version = "3.0">
<display-name>Struts 2</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
右键点击项目名称并点击 Export > WAR File 以创建一个 War 文件。然后将此 WAR 部署到 Tomcat 的 webapps 目录中。
Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat’s webapps directory.
最后,启动 Tomcat 服务器并尝试访问 URL http://localhost:8080/HelloWorldStruts2/index.jsp 。这将生成以下屏幕
Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will produce the following screen
现在在给定的文本框中输入任何单词并点击“Say Hello”按钮以执行定义的操作。现在,如果你将检查引发的日志,你将会在底部找到以下文本 −
Now enter any word in the given text box and click "Say Hello" button to execute the defined action. Now, if you will check the log generated, you will find the following text at the bottom −
Size of the valueStack: 3
这将显示以下屏幕,该屏幕将显示你输入的任何值以及我们在 ValueStack 上放置的 key1 和 key2 的值。
This will display the following screen, which will display whatever value you will enter and value of key1 and key2 which we had put on ValueStack.