这是 Struts 2 教程系列中的第二篇文章. 如果您直接来到这里,我建议查看之前的帖子。 (Struts 2 初学者教程)(/社区/教程/struts-tutorial-for-beginners) 在最后的教程中,我们研究了 Struts 2 架构,它是组件,并构建了一个简单的 Struts 2 网页应用程序,具有基于 XML 的配置(struts.xml)。
Struts 2 公约概念
Struts 2 使用两种方法来找出行动类和结果类。我们需要使用 struts2-convention-plugin API 来使用这些方法。如果您有正常的 Web 应用程序,您可以下载其 jar 文件并将其放入 Web 应用程序 lib 目录。对于 maven 项目,您可以简单地添加其依赖性如下。
1<dependency>
2 <groupId>org.apache.struts</groupId>
3 <artifactId>struts2-convention-plugin</artifactId>
4 <version>2.3.15.1</version>
5</dependency>
- 联合国 ** 扫描**:在这个方法中,我们指定需要扫描的软件包用于动作类。 需要用 web.xml 为 Struts 2 过滤器进行配置, 如下面的. (_
)
(Filter-name > struts2org.apache.struts2.dispatscher.ng.filter.filter.StrutsPrepareExecuteFilter <( ) > 行动包件 (- ) 方法后发现2个行动包件。 附加 ) ) - 任意类执行动作接口或扩展动作支持类. () ) - 任何以动作结尾并包含执行()方法的类. 对于这些类,使用命名公约来确定动作和结果.行动
**或行动
**说明的任何类别。 ( - ** 《南明公约》:Struts 2将自动为以Action结尾的类名创建动作。 动作名通过去除动作后缀并转换出第一个字母为小写来决定. 所以如果阶级名称是"家庭行动",那么行动就是"家庭". 如果这些类没有用 QQResult ** 附加说明以提供结果,则结果页会被查看到 WEB-INF/content 目录,名称应为 {action}-{ return_string}.jsp. 因此,如果家庭行动类正在返回"成功",则请求会被转发到WEB-INF/content/home-success. jsp**页. 仅使用命名公约就可能非常混乱,我们不能将同一种JSP页面用于其他动作类. 因此,我们应该尽量避免这种情况,并使用基于注释的配置. (_) (英语)
Now we are ready to create our Hello World struts 2 application using annotations and we won't have struts 2 configuration file. Create a dynamic web project in Eclipse Struts2AnnotationHelloWorld and convert it to maven project. The final project looks like below image.
Maven 配置
我们在 pom.xml 中添加了 struts2-core 和 struts2-convention 插件依赖,最终 pom.xml 代码是:
1<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
3 <modelVersion>4.0.0</modelVersion>
4 <groupId>Struts2AnnotationHelloWorld</groupId>
5 <artifactId>Struts2AnnotationHelloWorld</artifactId>
6 <version>0.0.1-SNAPSHOT</version>
7 <packaging>war</packaging>
8
9 <dependencies>
10 <dependency>
11 <groupId>org.apache.struts</groupId>
12 <artifactId>struts2-core</artifactId>
13 <version>2.3.15.1</version>
14 </dependency>
15 <dependency>
16 <groupId>org.apache.struts</groupId>
17 <artifactId>struts2-convention-plugin</artifactId>
18 <version>2.3.15.1</version>
19 </dependency>
20 </dependencies>
21
22 <build>
23 <plugins>
24 <plugin>
25 <artifactId>maven-compiler-plugin</artifactId>
26 <version>3.1</version>
27 <configuration>
28 <source>1.6</source>
29 <target>1.6</target>
30 </configuration>
31 </plugin>
32 <plugin>
33 <artifactId>maven-war-plugin</artifactId>
34 <version>2.3</version>
35 <configuration>
36 <warSourceDirectory>WebContent</warSourceDirectory>
37 <failOnMissingWebXml>false</failOnMissingWebXml>
38 </configuration>
39 </plugin>
40 </plugins>
41 <finalName>${project.artifactId}</finalName>
42 </build>
43</project>
部署描述器配置
1<?xml version="1.0" encoding="UTF-8"?>
2<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
3 xmlns="https://java.sun.com/xml/ns/javaee"
4 xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
5 id="WebApp_ID" version="3.0">
6 <display-name>Struts2AnnotationHelloWorld</display-name>
7
8 <filter>
9 <filter-name>struts2</filter-name>
10 <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
11 <init-param>
12 <param-name>actionPackages</param-name>
13 <param-value>com.journaldev.struts2.actions</param-value>
14 </init-param>
15 </filter>
16
17 <filter-mapping>
18 <filter-name>struts2</filter-name>
19 <url-pattern>/*</url-pattern>
20 </filter-mapping>
21
22</web-app>
请注意 init-param 元素,我们提供的操作类包将被 struts 2 扫描。
结果页
我们在我们的应用程序中有三个结果页面:login.jsp
1<%@ page language="java" contentType="text/html; charset=US-ASCII"
2 pageEncoding="US-ASCII"%>
3<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
4<%-- Using Struts2 Tags in JSP --%>
5<%@ taglib uri="/struts-tags" prefix="s"%>
6<html>
7<head>
8<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
9<title>Login Page</title>
10</head>
11<body>
12<h3>Welcome User, please login below</h3>
13<s:form action="login">
14 <s:textfield name="name" label="User Name"></s:textfield>
15 <s:textfield name="pwd" label="Password" type="password"></s:textfield>
16 <s:submit value="Login"></s:submit>
17</s:form>
18</body>
19</html>
《错误。jsp》
1<%@ page language="java" contentType="text/html; charset=US-ASCII"
2 pageEncoding="US-ASCII"%>
3<%@ taglib uri="/struts-tags" prefix="s"%>
4
5<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
6<html>
7<head>
8<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
9<title>Error Page</title>
10</head>
11<body>
12<h4>User Name or Password is wrong</h4>
13<s:include value="login.jsp"></s:include>
14</body>
15</html>
「歡迎」JSP
1<%@ page language="java" contentType="text/html; charset=US-ASCII"
2 pageEncoding="US-ASCII"%>
3<%@ taglib uri="/struts-tags" prefix="s"%>
4<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
5<html>
6<head>
7<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
8<title>Welcome Page</title>
9</head>
10<body>
11<h3>Welcome <s:property value="name"></s:property></h3>
12</body>
13</html>
现在让我们创建我们的动作类,我们将注释以配置动作和结果页面。
动作类与注释
1package com.journaldev.struts2.actions;
2
3import org.apache.struts2.convention.annotation.Action;
4import org.apache.struts2.convention.annotation.Actions;
5import org.apache.struts2.convention.annotation.Namespace;
6import org.apache.struts2.convention.annotation.Namespaces;
7import org.apache.struts2.convention.annotation.Result;
8
9import com.opensymphony.xwork2.ActionSupport;
10
11/**
12 * An empty class for default Action implementation for:
13 *
14 * <action name="home">
15 * <result>/login.jsp</result>
16 * </action>
17 * HomeAction class will be automatically mapped for home.action
18 * Default page is login.jsp which will be served to client
19 * @author pankaj
20 *
21 */
22
23@Namespaces(value={@Namespace("/User"),@Namespace("/")})
24@Result(location="/login.jsp")
25@Actions(value={@Action(""),@Action("home")})
26public class HomeAction extends ActionSupport {
27}
请注意,HomeAction 是一个空类,其唯一目的是将请求转发到 login.jsp 页面。
1package com.journaldev.struts2.actions;
2
3import org.apache.struts2.convention.annotation.Action;
4import org.apache.struts2.convention.annotation.Namespace;
5import org.apache.struts2.convention.annotation.Namespaces;
6import org.apache.struts2.convention.annotation.Result;
7
8/**
9 * Notice the @Action annotation where action and result pages are declared
10 * Also notice that we don't need to implement Action interface or extend ActionSupport
11 * class, only we need is an execute() method with same signature
12 * @author pankaj
13 *
14 */
15@Action(value = "login", results = {
16 @Result(name = "SUCCESS", location = "/welcome.jsp"),
17 @Result(name = "ERROR", location = "/error.jsp") })
18@Namespaces(value={@Namespace("/User"),@Namespace("/")})
19public class LoginAction {
20
21 public String execute() throws Exception {
22 if("pankaj".equals(getName()) && "admin".equals(getPwd()))
23 return "SUCCESS";
24 else return "ERROR";
25 }
26
27 //Java Bean to hold the form parameters
28 private String name;
29 private String pwd;
30 public String getName() {
31 return name;
32 }
33 public void setName(String name) {
34 this.name = name;
35 }
36 public String getPwd() {
37 return pwd;
38 }
39 public void setPwd(String pwd) {
40 this.pwd = pwd;
41 }
42}
Notice the use of @Action, @Actions, @Result, @Namespace and @Namespaces annotations, the usage is self explanatory. Now when we run our application, we get following response pages.
If you have read the last post where we have developed the same application with struts.xml configuration, you will notice that it's almost same. The only change is the way we wire our application action classes and result pages.