Struts 2 注解示例

17 Mar 2025 | 阅读 2 分钟

Struts 2 为您提供使用注解创建 struts 应用程序的便捷方式。 因此,不需要 struts.xml 文件。

正如我们之前所说,有两种方法可以使用零配置文件(没有 struts.xml 文件)。

  1. 通过约定
  2. 通过注解

Struts 2 应用程序中使用的注解

对于 struts 2 的简单注解示例,我们可以使用 3 个注解

1) @Action 注解用于标记 action 类。

2) @Results 注解用于为一个 action 定义多个结果。

3) @Result 注解用于显示单个结果。


使用注解的 struts 2 应用程序示例

您需要为 struts 注解应用程序创建 4 个文件

  1. index.jsp
  2. Action 类
  3. src 目录中的 struts.properties
  4. 结果页面
  5. web.xml 文件

让我们先看一下目录结构

directory structure of struts 2 application using annotation

1) 创建 index.jsp 用于输入

此 jsp 页面使用 struts UI 标签创建一个表单,该表单接收用户的姓名。

index.jsp

2) 创建 action 类

此 action 类使用 action 和 result 的注解。

RegisterAction.java

3) 在 src 目录中创建 struts.properties 文件

struts.properties

4) 创建 result.jsp 以显示消息

此 jsp 页面显示用户名。

result.jsp


输出

struts annotation example 1 struts 2 annotation example 2