温习java:Struts与Spring集成

来源:互联网 发布:mac air可以玩dnf吗 编辑:程序博客网 时间:2024/05/16 08:15

有一年多没写java了!快忘光了!现在手上有个项目,正好温习一下!与把过去的东东晒晒!第一篇当数struts与spring的集成了!开源框架发展的很快,现在struts 2也普遍了。这篇集成讲的是struts 1.29与spring 2.0。这种版本层次在现今的企业应用还是蛮多的。都是被证实为很稳定的。

 

struts集成spring的方式一:

step 1:加载AppliationContext:
方式一:
web.xml
  <!-- Spring ApplicationContext配置文件的路径 -->
  <context-param> 
         <param-name>contextConfigLocation</param-name> 
         <param-value>classpath*:spring/*.xml</param-value> 
  </context-param>
  <!-- Spring ApplicationContext 载入 -->
  <listener> 
         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
  </listener>
 
  方式二:
  struts-config.xml
  <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
        <set-property property="contextConfigLocation" value="/WEB-INF/spring-config/applicationContext.xml" />
  </plug-in>
 
  step 2:让Action继承ActionSupport
  public class LoginAction extends ActionSupport{
  ...
  }
 
  step 3:调用ActionSupport的方法getWebApplicationContext获得WebApplicationContext 通过WebApplicatioContext获得被spring容器管理的Service
 
  public class LoginAction extends ActionSupport{
        public ActionForward execute(ActionMapping mapping,
                                                        ActionForm form,
                                                        HttpServletRequest request,
                                                        HttpServletResponse response) throws Exception{
                      //取得Spring上下文
                      ApplicationContext context = getWebApplicationContext();
                      //取得被Spring管理的bean
                      StudentService ss = (StudentService)context.getBean("studentService");
                      ...
        }
  ...
  }



struts集成spring的方式二:
step 1:加载AppliationContext:
step 2:使用Action代理类(DelegatingActionProxy):DelegatingActionProxy的作用是依据path去spring容器中查找被管理的Action
 public class LoginAction extends Action{
                    private StudentService ss;
                    //通用Ioc注入
                    public void setStudentService(StudentService ss){
                             this.ss=ss;
                    }
                    ...
 }
struts-config.xml
<action path="/listStudents" type="org.springframework.web.struts.DelegatingActionProxy" />
step 3:在spring配置文件中,配置Action
applicationContext.xml
<bean name="ss"  ...>
</bean>
<bean name="/listStudents" class="...">
     <property name="ss">
           <ref bean="ss" />
     </property>
</bean>



struts集成spring的方式三:
step 1:加载AppliationContext:
step 2:配置新的控制器DelegatingRequestProcessor
struts-config.xml
<action path="/listStudents" />

<controller processorClass="org.springframework.web.struts.DelegatingRequestProcessor" />

当收到一个/listStudents请求时,DelegatingRequestProcessor会自动从Spring应用上下文中查找一个名为/listStudents的bean

原创粉丝点击