Struts2和Spring整合

之前用的三大框架,一直没有对struts2进行整合,项目结构一直不太规范,参考网上的例子,感觉并没什么不一样,下面说一下怎么配置吧。还有就是怎么读取配置文件获取bean.

1。除了导入Struts2和Spring的核心库之外,还要导入commons-logging和struts2-spring-plugin包,否则启动会出异常

2。web.xml里
	<!-- 配置spring资源  如果你的spring在src下就不用配置了-->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:config-resource/applicationContext.xml</param-value>
	</context-param>
	<!-- 配置spring -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

4。applicationContext.xml 注入Action的bean. 注:scope="prototype" 会在该类型的对象被请求时创建一个新的action对象。如果没有配置scope=prototype则添加的时候不会新建一个action,他任然会保留上次访问的过记录的信息。 为了使struts2线程安全,配上去,不配也可以运行。
	<bean id="gCAction" class="com.hb.action.GCAction"  scope="prototype">
		<property name="gCService" ref="gCService"></property>
	</bean>

5.struts.xml里  就是把原来的 class="包名.类名"换成了spring配置文件里的 bean id了
<struts>
	<!-- 将Action的创建交给spring来管理  这个有没有运行效果一样-->
	<constant name="struts.objectFactory" value="spring" />
	
	<package name="gongcheng" extends="json-default">
		<action name="gc_*" class="gCAction" method="{1}">
			<result name="to_index">/index.jsp</result>
			<result name="to_update">/editGC.jsp</result>
			<result name="to_list" type="redirect">/gc_GCList.action</result>
			<result type="json"></result>
		</action>
	</package>
</struts>    

总结
	整合就直接把class换成bean id就可以了 
	<constant name="struts.objectFactory" value="spring" /> 和 scope="prototype"
	这两个好像都不需要,只要把web.xml配置sping启动监听就可以了,为了使struts2每次请求都生成一个action,线程安全,要配上去(配置到 action 那个bean里)
	还有一个:struts2-spring-plugin包+web.xml加上spring的监听才可以注入bean属性,才能使用注入的属性(提供set方法),
	如何通过读取配置文件去获取bean, beanName就是spring bean 的id,如果spring配置文件没放到包里的话,就  /applicationContext.xml
	public Object getBean(String beanName){
		ApplicationContext app =  new ClassPathXmlApplicationContext("config-resource/applicationContext.xml");
		return app.getBean(beanName);
	}

Hibernate获取session的方法:
public class HibernateUtil {
	private static SessionFactory sessionFactory = null;
	private static SessionFactory getSessionFactory(){
		if(sessionFactory==null){
			sessionFactory = (SessionFactory)new ClassPathXmlApplicationContext("confige-resource/applicationContext.xml").getBean("sessionFactory");
		}
		return sessionFactory;
	}
	public static Session getSession(){
		return getSessionFactory().openSession();
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值