整合 Struts2 和 Spring
jar包依赖
<!-- https://mvnrepository.com/artifact/org.apache.struts/struts2-spring-plugin -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-spring-plugin</artifactId>
<version>2.5.22</version>
</dependency>
添加Spring配置文件
spring-struts2.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd" >
<context:component-scan
base-package="ssh.day02"/>
</beans>
利用 ContextLoaderListener 初始化Spring容器:
在web.xml中配置如下:
<!-- 利用ContextLoaderListener初始化Spring容器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-*.xml</param-value>
</context-param>
创建 控制器:
package ssh.day02;
import org.springframework.stereotype.Controller;
@Controller
public class DemoAction {
public String execute() {
System.out.println("Hello World!");
return "success";
}
}
配置 struts.xml
<!-- 利用Spring管理控制器对象 class=BeanID -->
<action name="demo" class="demoAction">
<result name="success">
/WEB-INF/jsp/ok.jsp
</result>
</action>
测试
http://localhost:8085/struts2demo/test/demo
控制台输出