有一年多沒寫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