Spring 和 Struts 2 集成17 Mar 2025 | 阅读 2 分钟 Spring 框架提供了一种管理依赖项的简单方法。 它可以很容易地与 struts 2 框架集成。 ContextLoaderListener 类用于将 spring 应用程序与 struts 2 通信。 必须在 web.xml 文件中指定它。
您需要遵循以下步骤 - 创建 struts2 应用程序并添加 spring jar 文件。
- 在 web.xml 文件中,定义 ContextLoaderListener 类。
- 在 struts.xml 文件中,定义 action 类的 bean 名称。
- 在 applicationContext.xml 文件中,创建 bean。 其类名应为 action 类名,例如 com.javatpoint.Login,id 应与 struts.xml 文件的 action 类(例如 login)匹配。
- 在 action 类中,定义额外的属性,例如 message。
Spring 和 Struts 2 集成的示例您需要创建以下文件来实现简单的 spring 和 struts 2 应用程序 - index.jsp
- web.xml
- struts.xml
- applicationContext.xml
- Login.java
- welcome.jsp
- error.jsp
1) index.jsp此页面从用户那里获取名称。 2) web.xml它为 struts 2 定义控制器类,并定义 ContextLoaderListener 监听器类以建立 struts2 和 spring 应用程序之间的连接。 3) struts.xml它定义包含 action 和 result 的 package。 在这里,action 类名称是 login,它将在 applicationContext.xml 文件中搜索。 4) applicationContext.xml它定义了一个 id 为 login 的 bean。 此 bean 对应于 mypack.Login 类。 在这里它将被视为 action 类。 它应该位于 WEB-INF 目录中。 5) Login.java它定义了两个属性 userName 和 message,并定义了返回 success 的 execute 方法。 6) welcome.jsp它打印 userName 和 message 属性的值。 7) error.jsp它是错误页面。 但在此示例中不需要它,因为我们没有在 action 类的 execute 方法中定义任何逻辑。 输出

|