Struts 2数据标签示例教程

In last article we saw how we can use OGNL in Struts 2 to work with application data and store or retrieve it from ValueStack. Struts 2 provide a lot of custom tags that we can use in JSP pages to get the application data from ValueStack as well as from request, session or application scope attributes.

在上一篇文章中,我们看到了如何在Struts 2中使用OGNL处理应用程序数据以及从ValueStack存储或检索它。 Struts 2提供了许多自定义标签,我们可以在JSP页面中使用它们来从ValueStack以及从请求,会话或应用程序范围属性中获取应用程序数据。

Struts 2 tags can be divided into three categories – Data tags, Control tags and UI tags. Today we will look into Struts2 Data tags and how we can use them in JSP pages. We need to import Struts 2 tag libraries in JSP pages to use them through taglib directive as:

Struts 2标签可分为三类- 数据标签控制标签UI标签 。 今天,我们将研究Struts2数据标签以及如何在JSP页面中使用它们。 我们需要在JSP页面中导入Struts 2标记库,以通过taglib指令使用它们:

<%@ taglib uri="/struts-tags" prefix="s" %>

<%@ taglib uri="/struts-tags" prefix="s" %>

Let’s first have the brief introduction of the Struts 2 Data tags and then we will look at their usage in a struts project.

首先让我们简要介绍一下Struts 2 Data标记,然后再看一下它们在struts项目中的用法。

  1. property tag: This is one of the most widely used tag to get the property from ValueStack as well as application, session or request scopes. Some of the important attributes of property tag are – value for expression, default for default value if OGNL expression returns null and escapeHtml for escaping HTML tags. We can also invoke a bean method through property tag.
    <s:property value="country" default="USA"/>

    property标签 :这是从ValueStack以及应用程序,会话或请求范围中获取属性的最广泛使用的标签之一。 属性标记的一些重要属性是–表达式的值,如果OGNL表达式返回null,则默认为默认值,而转义HTML标记则使用escapeHtml。 我们还可以通过属性标签调用bean方法。
  2. set tag: This is used to set values in application, session, request, page, or action. If we don’t provide any scope, value will be set for action.
    <s:set var="defaultGender" value="gender" scope="application"></s:set>

    set tag :用于设置应用程序,会话,请求,页面或操作中的值。 如果我们不提供任何范围,则会为操作设置值。
  3. push tag: Most of the times in result pages, we work with bean properties from a single bean. We can use push tag to pus the value on top of the stack, so that we can use the properties directly without prefixing it with bean. This helps in writing cleaner code when single bean is used a lot.
    <s:push value="user">
    User Name = <s:property value="name" /><br> <!-- no need to use user.name now -->
    </s:push>

    push tag :大多数情况下,在结果页面中,我们使用单个bean的bean属性。 我们可以使用push标签在栈顶上插入值,这样我们就可以直接使用属性而无需在bean前面加上前缀。 当经常使用单个bean时,这有助于编写更简洁的代码。
  4. bean tag: We can use bean tag to initialize a java bean in JSP page and then use param tag to pass parameters to it’s properties setter methods. Once the bean is initialized, we can access it with property tag.
    <s:bean name="com.journaldev.struts2.model.User" var="myUser">
    	<s:param name="name">Pankaj</s:param>
    </s:bean>

    bean标签 :我们可以使用bean标签在JSP页面中初始化Java bean,然后使用param标签将参数传递给它的属性设置器方法。 初始化bean之后,我们可以使用property标签访问它。
  5. action tag: We can use action tag to invoke another action from result pages and then use the returned value in the page. We can choose to render the response in current page through executeResult attribute.
    <s:action name="footer" namespace="/" executeResult="true"></s:action>

    action标签 :我们可以使用action标签从结果页面调用另一个操作,然后在页面中使用返回的值。 我们可以选择通过executeResult属性在当前页面中呈现响应。
  6. a tag: We can use this tag to create hyperlinks in the JSP page.
    <s:a href="https://www.journaldev.com">Go To Home</s:a>

    标签 :我们可以使用此标签在JSP页面中创建超链接。
  7. date tag: We can use this tag to get java bean date variable and then format it with formatter.
    <s:date name="date" format="MM/dd/yyyy"/>

    date标签 :我们可以使用此标签获取java bean date变量,然后使用formatter对其进行格式化。
  8. include tag: This is similar to JSP include action and we can use it to include another resource in the JSP page.
    <s:include value="/footer.jsp"></s:include>

    include标记 :这类似于JSP include动作 ,我们可以使用它在JSP页面中包括另一个资源。
  9. i18n and text tag: These tags can be used for i18n support in JSP pages. We can use i18n tag to provide the property file name where we should look for the key value, key name is passed with text tag.
    <s:i18n name="global">
        <s:text name="home.name"></s:text>
    </s:i18n>

    i18n和文本标签 :这些标签可用于JSP页面中的i18n支持。 我们可以使用i18n标记来提供属性文件名,我们应该在其中查找键值,键名与text标记一起传递。
  10. debug tag: We can use this tag for debugging JSP pages. This tag creates a Debug link that shows us ValueStack contents and stack context information.
    <s:debug></s:debug>

    debug标签 :我们可以使用此标签来调试JSP页面。 此标记创建一个Debug链接,该链接向我们显示ValueStack的内容和堆栈上下文信息。

We will create a simple web application where we will use above tags in JSP result page. We will create simple action classes to populate the bean values. We will also create global property file to be used for i18n. Our final project will look like below image.

我们将创建一个简单的Web应用程序,将在JSP结果页面中使用以上标记。 我们将创建简单的动作类来填充bean值。 我们还将创建用于i18n的全局属性文件。 我们的最终项目将如下图所示。

配置文件 (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>Struts2DataTagsExample</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>Struts2DataTagsExample</groupId>
	<artifactId>Struts2DataTagsExample</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>

pom.xml and web.xml files have configuration for using Struts 2 in web application.

pom.xml和web.xml文件具有在Web应用程序中使用Struts 2的配置。

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.devMode" value="false"></constant>
<constant name="struts.convention.result.path" value="/"></constant>
<constant name="struts.custom.i18n.resources" value="global" />

<package name="user" namespace="/" extends="struts-default">
	<action name="home" class="com.journaldev.struts2.actions.HomeAction">
	<result name="success">/home.jsp</result>
	</action>

	<action name="footer" class="com.journaldev.struts2.actions.FooterAction">
	<result name="success">/footer.jsp</result>
	</action>
</package>

</struts>

The important point to note is the struts.custom.i18n.resources configuration to use global.properties file for i18n.

需要注意的重要一点是struts.custom.i18n.resources配置,以将global.properties文件用于i18n。

global.properties

global.properties

home.name=Home
home.title=Home Page

Simple property file that will be used in result page to show messages.

简单属性文件,将在结果页面中使用它显示消息。

Java Bean类 (Java Bean Class)

package com.journaldev.struts2.model;

import java.util.Date;

public class User {

	private String name;
	private String address;
	private String gender;
	private Date date;
	
	public User(){
		this.date = new Date();
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
	
	public String getDefaultName(){
		return "admin";
	}
	public Date getDate() {
		return date;
	}
	public void setDate(Date date) {
		this.date = date;
	}
}

Simple java bean whose values will be set in the action class and used in JSP page to show values.

简单的Java Bean,其值将在操作类中设置,并在JSP页面中用于显示值。

动作班 (Action Classes)

package com.journaldev.struts2.actions;

import com.journaldev.struts2.model.User;
import com.opensymphony.xwork2.ActionSupport;

public class HomeAction extends ActionSupport {

	private static final long serialVersionUID = 1L;

	@Override
	public String execute(){
		user = new User();
		user.setName("Pankaj Kumar");
		user.setGender("Male");
		
		return SUCCESS;
	}
	
	private User user;

	public User getUser() {
		return user;
	}

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

}

Simple action class that is setting java bean properties.

设置Java bean属性的简单操作类。

package com.journaldev.struts2.actions;

import com.opensymphony.xwork2.ActionSupport;

public class FooterAction extends ActionSupport {

	@Override
	public String execute() {
		return SUCCESS;
	}
}

This action will be invoked from JSP page using action tag.

将使用操作标记从JSP页面调用此操作。

结果页 (Result Pages)

footer.jsp

footer.jsp

<strong>Footer Data</strong>

Simple HTML fragment that will be included in home.jsp using include tag and its the response of footer action.

简单HTML片段,它将使用include标签及其页脚操作的响应包含在home.jsp中。

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>
<h4>Struts 2 property tag example</h4>

User Name = <s:property value="user.name"/><br>
User Address = <s:property value="user.address" default="USA"/><br>

<h4>Struts 2 set tag example</h4>
<s:set var="defaultGender" value="user.gender" scope="application"></s:set>
Default Gender = <s:property value="#application.defaultGender"/><br>
Default Gender = <s:property value="#application['defaultGender']"/><br>

<h4>Struts 2 push tag example</h4>
<s:push value="user">
User Name = <s:property value="name" /><br>
User Address = <s:property value="address" default="USA"/><br>
User Address = <s:property value="gender" default="female"/><br>
</s:push>

<h4>Struts 2 bean tag example</h4>
<s:bean name="com.journaldev.struts2.model.User" var="myUser">
	<s:param name="name">Lisa</s:param>
	<s:param name="gender" value="#application.defaultGender"></s:param>
	<s:param name="address">India</s:param>
</s:bean>

MyUser Name = <s:property value="#myUser.name"/><br>
MyUser Gender = <s:property value="#myUser.gender"/><br>
MyUser Address = <s:property value="#myUser.address"/><br>
Default Name = <s:property value="#myUser.getDefaultName()"/><br>

<h4>Struts 2 action tag example</h4>

Data from footer action = <s:action name="footer" namespace="/" executeResult="true"></s:action>

<h4>Struts 2 Miscellaneous Data tags example</h4>

a tag example: <s:a href="#top">Go To Top</s:a><br>
date tag example: <s:date name="user.date" format="MM/dd/yyyy"/><br>
include tag example: <s:include value="/footer.jsp"></s:include><br>
text tag example: <s:text name="home.title"></s:text><br>
i18n tag example: <s:i18n name="global"><s:text name="home.name"></s:text></s:i18n><br>
debug tag example: <s:debug></s:debug>

</body>
</html>

This is the main result page where all the Struts 2 data tags usage are shown. Please look into this carefully for example usage of struts 2 data tags.

这是主要结果页面,其中显示了所有Struts 2数据标签的使用情况。 请仔细研究此内容,例如struts 2数据标签的用法。

When we execute home action, we get following output.

当执行home动作时,我们得到以下输出。

Download project from above link and look into the data tags usage, play around with different attributes of these tags to learn more about them.

从上面的链接下载项目,并查看数据标签的用法,尝试使用这些标签的不同属性以了解有关它们的更多信息。

Thats all for Struts 2 data tags example tutorial, please read next post for Struts2 Control tags and UI tags in future articles.

多数民众赞成在Struts 2数据标签示例教程中,请在以后的文章中阅读有关Struts2 Control标签和UI标签的下一篇文章。

翻译自: https://www.journaldev.com/2230/struts-2-data-tags-example-tutorial

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值