spring整合struts2(hibernate的配置和spring配置文件综合在一起)

来源:互联网 发布:国民党抗战电影 知乎 编辑:程序博客网 时间:2024/05/16 00:38
第一步就是引入struts2和spring最基本已经struts中的spring-plugin的jar包,然后在web.xml配置filter引入struts2和配置listener引入spring如:
<filter>
  <filter-name>struts2</filter-name>
  <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>

<filter-mapping>
  <filter-name>struts2</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

然后在struts.xml中配置action时要注意的是class对于的不再是具体的action类,struts已经把注入的任务交给了spring了。至于引入spring-plugin这个jar包是因为它把objectfactory改为了spring中的objectfactory。可以在struts—core中看到defaultproperties的文件中看到# struts.objectFactory = spring,默认是不引用spring的factory的,但是引入struts2-spring-plugin的jar包后就会覆盖这个默认的设置,因为容器加载完struts—default.xml后会加载struts2-spring-plugin的jar包中的struts-plugin.xml,因此会覆盖,所以会成功整合spring。

配置一个action类的一个例子。:
首先在applicationContext.xml中配置相应的bean;
<bean id="loginService" class="com.ccy.service.impl.LoginServiceImpl" scope="singleton"></bean>

<bean id="loginAction" class="com.ccy.action.LoginAction" scope="prototype">
  <property name="loginService" ref="loginService"></property>
</bean>


然后在struts中配置相应的action:

<action name="login" class="loginAction">
    <result name="success">/loginsuccess.jsp</result>
    <result name="error">/login.jsp</result>
  </action>

注意这里的class不是指具体的类,而是指bean中红色的那个bean。这样就把装配任务交给了spring,注意scope的五个配置的值:singleton是指单例,就是说从头到尾都只有一个这样的bean,适合配置那些无状态的bean,而prototype是指每次调用都会new 一个这样的bean,适合有状态的类,而request是指在web引用中,发出请求就new一个bean,这种情况下和prototype一样,但是它仅仅可以用在web应用中,有请求才发生作用,prototype可以用在普通的项目,也可以用在web项目中,因此可以使用prototype代替request,session是指在web应用中的整个会话都起作用。只会在会话中生成一次。最后一个是globalsession,这个一般不会用到。最后要什么一点就是用spring框架最好就用接口编程的方法,否则还不如不用spring这个框架。我个人对spring的一个很浅显的认识就是spring倡导的思想就是为每个client通过beanfactory提供一个方法的接口让你调用,至于后台它调用哪个实例,哪个方法,如何实现上层不需要了解。所以如果不用接口编程,还不如不用spring。同时用接口编程的一个好处就是到时候改实现的具体方法和类都需要改一下配置文件和实现的类,不用理会调用的类。
0 0