1、Spring整合web应用
添加依赖 Spring-web spring-context-support
配置监听器 web.xml
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:app*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
|
|
定义核心配置文件 applicationContext.xml
<bean id="now" class="java.util.Date" p:year="1900"/> |
在 servlet中获取ApplicationContext,然后获取受管bean
ApplicationContext ac = WebApplicationContextUtils. getRequiredWebApplicationContext(application); Date now=(Date)ac.getBean("now"); out.println(now); |
|
2、Spring整合Struts2框架
添加spring-web struts2-core
Struts2和Spring框架整合需要一个额外的插件包struts2-spring-plugin
配置Spring整合web应用的监听器
ContextLoaderListener
配置Struts2的前端控制器 web.xml
<filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class> <init-param> <param-name>struts.devMode</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> |
定义Struts2的核心配置文件 struts.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd"> <struts> <package name="default" extends="struts-default" strict-method-invocation="false"></package> </struts> |
定义对象工厂: struts2默认使用xwork充当对象工厂,整合Spring框架后Action对象的创建应该由Spring负责
struts.xml定义常量用于设置对象工厂为spring
常量名称为struts.objectFactory
<constant name="struts.objectFactory" value="spring"/>
这个常量可以不用定义,因为在struts2-spring-plugin.jar中的struts-plugin.xml中已经定义了;当然定义了也不会出现任何错误
定义Action类
public class HelloAction extends ActionSupport { private String username; private String message;
@Override public String execute() throws Exception { if (StringUtils.isBlank(username)) username = "Struts2"; message = "Hello " + username + "!"; return SUCCESS; } |
Action组件在整合Spring后,是由Spring的IoC/DI容器负责管理。需要将Action配置在applicationContext.xml中
<bean id="helloAction" class="com.yan.action.HelloAction"/>
注意:因为action要求多实例单线程的运行方式,所以必须配置 scope=prototype,否则默认Spring的受管bean是单例的
<bean id="helloAction" class="com.yan.action.HelloAction" scope="prototype"/>
在Struts2的核心配置struts.xml中定义对应的路径
<action name="hello" class="helloAction"> <result>/msg_show.jsp</result> </action>
|
注意:class不再是Action类的全名,而是Action类在Spring的IoC/DI容器的名称,对应<bean>的id属性值
页面输出HelloAction中的message属性值
<s:property value="message"/>
访问路径
http://localhost:8080/spring0010/hello.action?username=***** |