Struts初学者教程

Welcome to Struts Tutorial for Beginners. Struts is one of the oldest frameworks to build Java Web Application.

欢迎使用Struts初学者教程。 Struts是构建Java Web应用程序的最古老的框架之一。

Struts教程 (Struts Tutorial)

struts tutorial, struts 2, struts 2 tutorial, struts2

Struts was the initial implementation of MVC design pattern and it has evolved a lot along with latest enhancements in Java, Java EE technologies. Struts tutorial article is aimed to provide basic details of Struts 2 and how we can create our first “Hello World” Struts 2 application.


Struts是MVC设计模式的最初实现,它随着Java,Java EE技术的最新增强而发展了很多。 Struts教程文章旨在提供Struts 2的基本细节,以及如何创建第一个“ Hello World” Struts 2应用程序。

Struts2 (Struts 2)

Apache Struts 2 is an open source, industry standard, flexible and extendable framework to build Java EE web application. Struts 2 is based on OpenSymphony WebWork framework. Struts 2 is very flexible in terms of development and configurations and we will see how easy it is to develop a web application using Struts 2 framework.

Apache Struts 2是用于构建Java EE Web应用程序的开源,行业标准,灵活和可扩展的框架。 Struts 2基于OpenSymphony WebWork框架 。 Struts 2在开发和配置方面非常灵活,我们将看到使用Struts 2框架开发Web应用程序是多么容易。

Struts 2架构图 (Struts 2 Architecture Diagram)

Below diagram shows different component of Struts 2 in a web application.

下图显示了Web应用程序中Struts 2的不同组件。

Struts 2拦截器 (Struts 2 Interceptors)

Struts Interceptors are like Servlet Filters that executes before and after the request is being processed. They are used to perform common operations for different actions. For example logging, session validation, adding common headers to response etc.

Struts拦截器就像Servlet过滤器一样 ,在处理请求之前和之后执行。 它们用于执行不同操作的通用操作。 例如日志记录,会话验证,向响应添加通用标头等。

Struts 2 ValueStack和OGNL (Struts 2 ValueStack and OGNL)

ValueStack is the storage area where the application data is stored by Struts 2 for processing a client request. The data is stored in ActionContext objects that use ThreadLocal to have values specific to the particular request thread.

ValueStack是Struts 2在其中存储应用程序数据以处理客户端请求的存储区域。 数据存储在使用ThreadLocal的 ActionContext对象中,该对象具有特定于特定请求线程的值。

Object-Graph Navigation Language (OGNL) is a powerful Expression Language that is used to manipulate data stored on the ValueStack. As you can see in architecture diagram, both interceptors and result pages can access data stored on ValueStack using OGNL.

对象图导航语言 (OGNL)是一种功能强大的表达语言,用于处理存储在ValueStack上的数据。 从体系结构图中可以看到,拦截器和结果页面都可以使用OGNL访问存储在ValueStack上的数据。

Struts 2动作 (Struts 2 Action)

Struts 2 Action components handle the client requests. Struts 2 provides different ways to create Action classes.

Struts 2 Action组件处理客户端请求。 Struts 2提供了创建Action类的不同方法。

  1. By implementing com.opensymphony.xwork2.Action interface.

    通过实现com.opensymphony.xwork2.Action接口。
  2. By extending com.opensymphony.xwork2.ActionSupport class. Usually it’s used to create empty action classes to forward request to another resource.

    通过扩展com.opensymphony.xwork2.ActionSupport类。 通常,它用于创建空的操作类以将请求转发到另一个资源。
  3. Annotating a class with @Action or @Actions annotation.

    用@Action或@Actions注释对类进行注释。
  4. Following naming convention for classes, name should end with Action and should have execute() method.

    遵循类的命名约定,名称应以Action结尾,并应具有execute()方法。

Struts 2结果 (Struts 2 Result)

Result components are usually JSP or HTML pages to create view for client response. Struts 2 provides their own tags that we can use in JSP pages to create response. Struts tags are great example of JSP Custom Tags.

结果组件通常是JSP或HTML页面,用于创建客户端响应的视图。 Struts 2提供了自己的标签,我们可以在JSP页面中使用它们来创建响应。 Struts标记是JSP定制标记的一个很好的例子。

Struts 2声明式架构和布线 (Struts 2 Declarative Architecture and Wiring)

Struts 2 provides two ways to configure our application for action classes and result pages.

Struts 2提供了两种为操作类和结果页面配置应用程序的方法。

  1. Struts XML File: We have struts.xml file in WEB-INF/classes directory where we can configure our application action classes and result pages.

    Struts XML文件 :WEB-INF / classes目录中有struts.xml文件,可以在其中配置应用程序操作类和结果页面。
  2. Annotation: We can use Java Annotations to provide metadata information about a class. Struts 2 convention plugin can be used to annotate java classes with @Action and @Result annotations to create configure action classes and associated result pages.

    注释 :我们可以使用Java注释来提供有关类的元数据信息。 Struts 2约定插件可用于使用@Action和@Result注释对Java类进行注释,以创建配置操作类和关联的结果页面。

Whichever way we use to configure our application, the end result will always be the same.

无论采用哪种方式配置应用程序,最终结果将始终相同。

Struts教程– Hello World基于XML的应用程序 (Struts Tutorial – Hello World XML Based Application)

Let’s see how we can create our first Struts 2 Hello World application. First of all we need is Struts 2 jar files, the easiest way is to download it from Struts 2 Official Downloads page. But when you will check out the libs in the downloaded archive, you will see a lot of jar files that we don’t need for our simple application.

让我们看看如何创建第一个Struts 2 Hello World应用程序。 首先,我们需要的是Struts 2 jar文件,最简单的方法是从Struts 2官方下载页面下载它。 但是,当您检出下载的档案中的库时,您会看到很多jar文件,对于我们的简单应用程序来说,我们不需要这些jar文件。

So I will create a maven project and add struts-core dependency only, all the other transitive dependency jars will be automatically downloaded and added to the application. Our final project structure will be like below image.

因此,我将创建一个maven项目并仅添加struts-core依赖关系,所有其他传递依赖关系jar将自动下载并添加到应用程序中。 我们的最终项目结构将如下图所示。

Create a new Dynamic Web Project Struts2XMLHelloWorld in Eclipse and then convert it to maven project like below image.

在Eclipse中创建一个新的Dynamic Web Project Struts2XMLHelloWorld,然后将其转换为maven项目,如下图所示。

You will notice pom.xml file is added in the root directory of the project. Our project setup in Eclipse is ready, let’s look at the different components in order.

您会注意到pom.xml文件已添加到项目的根目录中。 我们在Eclipse中的项目设置已经准备就绪,让我们按顺序查看不同的组件。

pom.xml (pom.xml)

Open pom.xml file and add struts core dependency, the final pom.xml will look like below.

打开pom.xml文件并添加struts核心依赖项,最终的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>Struts2XMLHelloWorld</groupId>
	<artifactId>Struts2XMLHelloWorld</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>
		<sourceDirectory>src</sourceDirectory>
		<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>

Notice that I have overridden finalName element to avoid version number getting added in the WAR file when we do maven build. Other parts are added by Eclipse itself, the only dependency we need is struts2-core whose current version is 2.3.15.1 (as of 10-Sep-2013).

请注意,我重写了finalName元素,以避免在进行Maven构建时将版本号添加到WAR文件中。 Eclipse本身添加了其他部分,我们唯一需要的依赖项是struts2-core,其当前版本为2.3.15.1(截至2013年9月10日)。

Just do maven build of the application and you will see a lot of jars added to the application lib directory and shown in Maven Dependencies section of the project like below image.

只需对应用程序进行maven构建,您将看到很多jar添加到应用程序li​​b目录中,并显示在项目的Maven Dependencies部分中,如下图所示。

Struts 2 web.xml配置 (Struts 2 web.xml configuration)

We need to add org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter filter to the web application and provide the URL pattern where we want Struts to take care of the client request. Our web.xml looks like below;

我们需要将org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter过滤器添加到Web应用程序中,并提供URL模式,以便我们让Struts处理客户请求。 我们的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"
	version="3.0">
	<display-name>Struts2XMLHelloWorld</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>

For Struts 2 version below 2.1.3, the filter-class was org.apache.struts2.dispatcher.FilterDispatcher.

对于2.1.3以下的Struts 2版本,过滤器类为org.apache.struts2.dispatcher.FilterDispatcher

Struts教程–结果页 (Struts Tutorial – Result Pages)

We have three JSP pages that will be used by the application, we are using Struts 2 tags to create our JSP pages.

我们有三个供应用程序使用的JSP页面,我们使用Struts 2标记来创建我们的JSP页面。

login.jsp

login.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<%-- Using Struts2 Tags in JSP --%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Login Page</title>
</head>
<body>
<h3>Welcome User, please login below</h3>
<s:form action="login">
	<s:textfield name="name" label="User Name"></s:textfield>
	<s:textfield name="pwd" label="Password" type="password"></s:textfield>
	<s:submit value="Login"></s:submit>
</s:form>
</body>
</html>

Notice the form field names are name and pwd, we will see how they are used in Action classes.

注意,表单字段名称是namepwd ,我们将看到它们在Action类中的用法。

welcome.jsp

welcome.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>Welcome Page</title>
</head>
<body>
<h3>Welcome <s:property value="name"></s:property></h3>
</body>
</html>

Notice the struts tag s:property that we can use to get request attributes, the name is same as in login.jsp.

注意,我们可以使用struts标记s:property来获取请求属性,该名称与login.jsp中的名称相同。

error.jsp

error.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>Error Page</title>
</head>
<body>
<h4>User Name or Password is wrong</h4>
<s:include value="login.jsp"></s:include>
</body>
</html>

This is a simple JSP page where we are adding error message and including login page in response.

这是一个简单的JSP页面,我们在其中添加错误消息并在响应中包括登录页面。

Struts教程–动作类 (Struts Tutorial – Action Classes)

Our application has only one Action class where we are implementing Struts 2 Action interface.

我们的应用程序只有一个Action类,用于实现Struts 2 Action接口。

LoginAction.java

LoginAction.java

package com.journaldev.struts2.action;

import com.opensymphony.xwork2.Action;

public class LoginAction implements Action {
	
	@Override
	public String execute() throws Exception {
		if("pankaj".equals(getName()) && "admin".equals(getPwd()))
		return "SUCCESS";
		else return "ERROR";
	}
	
	//Java Bean to hold the form parameters
	private String name;
	private String pwd;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	
}

Notice the action class is also a java bean with same variables as login.jsp and their getter and setter methods. Struts will take care of mapping the request parameters to the action class variables.

注意,动作类也是一个Java bean,其变量与login.jsp及其getter和setter方法相同。 Struts将负责将请求参数映射到动作类变量。

Struts教程–配置文件 (Struts Tutorial – Configuration File)

Since we are using XML based configuration for wiring our application, we need to create Struts configuration file that should be named as struts.xml and inside WEB-INF/classes directory.

由于我们使用基于XML的配置来连接应用程序,因此我们需要在Web INF / classes目录中创建应名为struts.xml的 Struts配置文件。

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>

<package name="user" namespace="/User" extends="struts-default">
	<action name="home">
		<result>/login.jsp</result>
	</action>
	<action name="login" class="com.journaldev.struts2.action.LoginAction">
	<result name="SUCCESS">/welcome.jsp</result>
	<result name="ERROR">/error.jsp</result>
	</action>

</package>

</struts>

For action “home”, there is no Action class and only one result, so request will be forwarded to the login.jsp page.

对于动作“ home”,没有动作类,只有一个结果,因此请求将转发到login.jsp页面。

For action “login”, LoginAction is the action class and if execute() method returns “SUCCESS” the request will be processed by welcome.jsp and for “ERROR” it will be forwarded to error.jsp page.

对于操作“登录”,LoginAction是操作类,如果execute()方法返回“ SUCCESS”,则请求将由welcome.jsp处理,对于“ ERROR”,该请求将转发至error.jsp页面。

namespace=”/User” is important and used in URL to access the action classes, it’s provided to create different modules.

namespace =“ / User”很重要,并且在URL中用于访问操作类,它用于创建不同的模块。

So we can access our application with URL https://localhost:8080/Struts2XMLHelloWorld/User/home.action. Notice that URL is ending with .action that is the default suffix for Struts 2 action like it is .do for Struts 1.

因此,我们可以使用URL https://localhost:8080/Struts2XMLHelloWorld/User/home.action访问我们的应用程序。 请注意,URL以.action结尾,这是Struts 2操作的默认后缀,就像Struts 1是.do一样。

Struts教程– Struts 2 Hello World测试 (Struts Tutorial – Struts 2 Hello World Test)

When we run our application, we get following response pages.

当我们运行我们的应用程序时,我们得到以下响应页面。

Thats all for Struts 2 beginners tutorial, check out next article we are using annotations to create Struts 2 Web Application without using struts.xml configuration file.

多数民众赞成在Struts 2初学者教程中,请查看下一篇文章,我们将使用注释来创建Struts 2 Web应用程序,而无需使用struts.xml配置文件。

翻译自: https://www.journaldev.com/2134/struts-tutorial-for-beginners

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值