1. Introduction
1.介绍
Apache Struts 2 is an MVC-based framework for developing enterprise Java web applications. It is a complete rewrite of original Struts framework. It has an open source API implementation and a rich feature set.
Apache Struts 2是一个基于MVC的框架,用于开发企业级Java Web应用程序。它是对原Struts框架的完全重写。它有一个开源的API实现和丰富的功能集。
In this tutorial, we will have a beginner’s introduction to different core components of the Struts2 framework. Moreover, we will show how to use them.
在本教程中,我们将对Struts2框架的不同核心组件进行初级介绍。此外,我们将展示如何使用它们。
2. Overview of Struts 2 Framework
2.Struts 2框架的概述
Some of Struts 2 features are:
Struts 2的一些特点是。
- POJO (plain old Java Objects)-based actions
- plugin support for REST, AJAX, Hibernate, Spring, etc
- convention over configuration
- support of various view-layer technologies
- ease of profiling and debugging
2.1. Different Components of Struts2
2.1.Struts2的不同组件
Struts2 is an MVC-based framework so the following three components will be present in all Struts2 applications:
Struts2是一个基于MVC的框架,所以以下三个组件将出现在所有Struts2应用程序中。
- Action class – which is a POJO class (POJO means it is not part of any type hierarchy and can be used as a standalone class); we will implement our business logic here
- Controller – in Struts2, HTTP filters are used as controllers; they basically perform tasks like intercepting and validating requests/responses
- View – is used for presenting processed data; it is usually a JSP file
3. Designing Our Application
3.设计我们的应用程序
Let’s proceed with the development of our web app. It is an application where a user selects a particular Car brand and gets greeted by a customized message.
让我们继续开发我们的网络应用。这是一个应用程序,用户选择一个特定的汽车品牌,并得到一个定制的信息迎接。
3.1. Maven Dependencies
3.1.Maven的依赖性
Let’s add following entries to the pom.xml:
让我们在pom.xml中添加以下条目。
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.5.10</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-junit-plugin</artifactId>
<version>2.5.10</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-convention-plugin</artifactId>
<version>2.5.10</version>
</dependency>
The latest version of the dependencies can be found here.
最新版本的依赖项可以在这里找到。
3.2. Business Logic
3.2.业务逻辑
Let’s create an action class CarAction which returns a message for a particular input value. The CarAction has two fields – carName (used for storing the input from the user) and carMessage (used for storing the custom message to be displayed):
让我们创建一个动作类CarAction,为特定的输入值返回一个消息。CarAction有两个字段 – carName(用于存储用户的输入)和carMessage(用于存储要显示的自定义消息)。
public class CarAction {
private String carName;
private String carMessage;
private CarMessageService carMessageService = new CarMessageService();
public String execute() {
this.setCarMessage(this.carMessageService.getMessage(carName));
return "success";
}
// getters and setters
}
The CarAction class uses CarMessageService which provides the customized message for a Car brand:
CarAction类使用 CarMessageService,它为Car品牌提供定制的信息。
public class CarMessageService {
public String getMessage(String carName) {
if (carName.equalsIgnoreCase("ferrari")){
return "Ferrari Fan!";
}
else if (carName.equalsIgnoreCase("bmw")){
return "BMW Fan!";
}
else {
return "please choose ferrari Or bmw";
}
}
}
3.3. Accepting User Input
3.3.接受用户输入
Let’s add a JSP which is an entry point in our application. This is a content of the input.jsp file:
让我们添加一个JSP,它是我们应用程序中的一个入口点。这是input.jsp文件的内容。
<body>
<form method="get" action="/struts2/tutorial/car.action">
<p>Welcome to Baeldung Struts 2 app</p>
<p>Which car do you like !!</p>
<p>Please choose ferrari or bmw</p>
<select name="carName">
<option value="Ferrari" label="ferrari" />
<option value="BMW" label="bmw" />
</select>
<input type="submit" value="Enter!" />
</form>
</body>
The <form> tag specifies the action (in our case it is a HTTP URI to which GET request has to be sent).
<form>标签指定了行动(在我们的例子中,它是一个HTTP URI,必须向其发送GET请求)。
3.4. The Controller Part
3.4.控制器部分
StrutsPrepareAndExecuteFilter is the controller, which will intercept all incoming requests. We need to register the following filter in the web.xml:
StrutsPrepareAndExecuteFilter是一个控制器,它将拦截所有进入的请求。我们需要在web.xml中注册以下过滤器:。
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
StrutsPrepareAndExecuteFilter will filter every incoming request as we are specifying URL matching wildcard <url-pattern>/*</url-pattern>
StrutsPrepareAndExecuteFilter 将过滤每个传入的请求,因为我们指定了与通配符相匹配的URL <url-pattern>/*</url-pattern>
3.5. Configuring the Application
3.5.配置应用程序
Let’s add following annotations to our action class Car:
让我们为我们的动作类Car添加以下注解。
@Namespace("/tutorial")
@Action("/car")
@Result(name = "success", location = "/result.jsp")
Let’s understand the logic of this annotations. The @Namespace is used for logical separation of request URI for different action classes; we need to include this value in our request.
让我们来理解这个注解的逻辑。 @Namespace用于对不同行动类别的请求URI进行逻辑分离;我们需要在我们的请求中包含这个值。
Furthermore, the @Action tells the actual end point of the request URI which will hit our Action class. The action class consults CarMessageService and initializes the value of another member variable carMessage. After execute() method returns a value, “success” in our case, it matches that value to invoke result.jsp
此外,@Action告诉了请求URI的实际终点,它将击中我们的Action类。行动类咨询了CarMessageService,并初始化了另一个成员变量carMessage的值。在execute()方法返回一个值后,“success”在我们的例子中,它匹配这个值来调用result.jsp。
Finally, the @Result has two parameters. First one, name, specifies the value which our Action class will return; this value is returned from the execute() method of Action class. This is the default method name which will be executed.
最后,@Result有两个参数。第一个,name,指定我们的Action类将返回的值;这个值从Action类的execute()方法返回。这是将被执行的默认方法名称。
The second part, location, tells which is the file to be referred to after the execute() method has returned a value. Here, we are specifying that when execute() returns a String with value “success“, we have to forward the request to result.jsp.
第二部分,location,告诉我们在execute()方法返回一个值后,将引用哪个文件。这里,我们指定当execute()返回一个值为”success“的字符串时,我们必须将请求转发给result.jsp。
The same configuration can be achieved by providing XML configuration file:
同样的配置可以通过提供XML配置文件来实现。
<struts>
<package name="tutorial" extends="struts-default" namespace="/tutorial">
<action name="car" class="com.baeldung.struts.CarAction" method="execute">
<result name="success">/result.jsp</result>
</action>
</package>
</struts>
3.6. The View
3.6.观点
This is the content of result.jsp which will be used for presenting the message to the user:
这是result.jsp的内容,它将被用来向用户展示信息。
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<body>
<p> Hello Baeldung User </p>
<p>You are a <s:property value="carMessage"/></p>
</body>
There are two important things to notice here:
这里有两件重要的事情需要注意。
- in <@taglib prefix=”s” uri=”/struts-tags %> we are importing struts-tags library
- in <s:property value=”carMessage”/> we are using struts-tags library to print the value of a property carMessage
4. Running the Application
4.运行应用程序
This web app can be run in any web container, for example in Apache Tomcat. These are the required steps for accomplishing it:
这个网络应用可以在任何网络容器中运行,例如在Apache Tomcat中。这些是完成它的必要步骤。
- After deploying the web app, open the browser and access the following URL: http://www.localhost.com:8080/MyStrutsApp/input.jsp
- Select one of the two options and submit the request
- You will be forwarded to the result.jsp page with customized message based on the selected input option
5. Conclusion
5.结论
In this tutorial, we walked through a step by step guide, how to create our first Struts2 web application. We covered different MVC related aspects in the Struts2 domain and showed how to put them together for development.
在本教程中,我们通过一步步的指导,了解了如何创建我们的第一个Struts2 Web应用程序。我们涵盖了Struts2领域中与MVC相关的不同方面,并展示了如何将它们放在一起进行开发。
As always, this tutorial can be found over on Github as a Maven project.
一如既往,本教程可在Github上找到,作为一个Maven项目。