struts2 + spring 整合

来源:互联网 发布:星图数据全网销售直播 编辑:程序博客网 时间:2024/06/06 23:17

一、spring 在web.xml中

①listener方式加载时:
 

指定Spring的配置文件

     <!-- 指定Spring的配置文件 -->

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring*.xml</param-value>
    </context-param>

其中classpath: 表示只会到你的class路径中查找找文件;  相对于classpath*: 不仅包含class路径,还包括jar文件中(class路径)进行查找.
    
    <!-- 指定以Listener方式启动Spring容器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

后台获取bean:

ServletContext context = getServletContext();

   
   WebApplicationContext applicationContext  = WebApplicationContextUtils
     .getWebApplicationContext(context);

②servlet方式加载时:

<servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/applicationContext</param-value>
        </init-param>
    </servlet>

后台获取bean
 

ServletContext context = getServletContext();
  
  XmlWebApplicationContext applicationContext = (XmlWebApplicationContext) context.getAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcherServlet");


二、struts使用spring实例化

需要在struts.xml中配置
    <!-- 设置Struts2默认的ObjectFactory为spring -->
    <constant name="struts.objectFactory" value="spring" />
 

三、struts中的占位符使用

<package name="main" extends="cxstock" namespace="/">
        <action name="*_*" class="{1}Action" method="{2}">
            <result name="input">/login.jsp</result>
            <result name="success" type="redirect">/jsp/main/index.jsp</result>
            <interceptor-ref name="loginedCheck"/>
            <interceptor-ref name="defaultStack"/>
        </action>
    </package>

*_* 中 {1}表示第一个占位符*的值
 



原创粉丝点击