以前项目的框架是struts1.2+spring,在struts-config里面配置了<plug-in>来在系统初始化的时候加载一个参数初始化的类。
现在改用struts2+spring了,还能够用<plug-in>吗?我在struts.xml里面这样写会报错,不支持呀。
然后我改用spring来加载,让那个类implements InitializingBean。
问题是我现在想获得ServletContext和ApplicationContext对象。
我知道有些人说ServletContext没必要去获得,只是系统以前很多地方都是通过ServletContext对象来调里面的方法,比如servletContext.getRealPath("/")。
现在我这样写
servletContext = ServletActionContext.getServletContext();
得到的servletContext 是一个null。
ActionContext context = ActionContext.getContext();  是可以获取到的
既然servletContext 获取不到,那么
ApplicationContext appContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
也获取不到。
请教各位,我怎么才能获取到ServletContext和ApplicationContext对象呀?或者有办法能在struts2里继续用<plug-in>来初始化也可以。

解决方案 »

  1.   

    此回复为自动发出,仅用于显示而已,并无任何其他特殊作用
    楼主【soniccyj】截止到2008-06-27 16:53:26的历史汇总数据(不包括此帖):
    发帖数:1                  发帖分:100                
    结贴数:1                  结贴分:100                
    未结数:0                  未结分:0                  
    结贴率:100.00%            结分率:100.00%            
    敬礼!
      

  2.   

    Struts2 集成Spring  只需要一个Spring-plugin 的jar 文件。 放到你的lib中。 然后在web.xml中配置一下就OK了
     
    参考:http://struts.apache.org/2.0.11.1/docs/spring-plugin.html
      

  3.   

    首先说struts2和spring集成的问题,在你下载的struts的lib目录下有一个
    struts2-spring-plugin-2.0.11.1.jar包,把它加入到你的classpath中,然后
    可以如下配置,我举个例子
    struts.xml中
    <action name="addPerson" class="addPerson">
    <result name="success">/jsp/addPerson.jsp</result>
    </action>
    spring的applicationContext.xml中
    <bean name="addPerson" class="com.lan.adms.web.AddPersonAction" scope="prototype">
    <property name="myPersonService" ref="myPersonService"></property>
    </bean>第二你想得到servletContext ,你的struts的Action已经被Spring容器管理起来了,你就无需再得到
    servletContext 来初始化ApplicationContext 了,只需要直接注入你的service即可,就像上面那样如果你没有把struts2集成到spring,你也可以通过如下方是获取ApplicationContext 
    那么你的struts2的action只需要实现ServletContextAware,就可以轻松获得servletContext ,例子如下
    public class AddPerson extends ActionSupport implements ServletContextAware {
    private ServletContext context;
    public void setServletContext(ServletContext arg0) {
    // TODO Auto-generated method stub
    this.context = arg0;
    }
    }
    然后你就可以像struts1那样得到ApplicationContext了
      

  4.   

    兄弟,有一个更好的方法:ActionContext ctx = ActionContext.getContext();//在struts2中得到ActionContext应该不难吧ServletContext sc = (ServletContext)ctx.get(ServletActionContext.SERVLET_CONTEXT);//由得到的ActionContext取得ServletContext,Struts1.X中也有ServletContext的吧?ApplicationContext appContext = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);//得到了ServletContext就能得到ApplicationContext,现在就用appContext.getBean("BeanName")去试试吧