Exemple d'intégration Struts + Spring
Voici un didacticiel pour montrer comment accéder aux beans déclarés dans le conteneur Spring Ioc dans une application Web développée avec Apache Struts 1.x.
Téléchargez cet exemple de Struts 1.x + Spring -Struts-Spring-Hibernate-Example.zip
Spring est livré avec une solution «Struts-specific» pour les beans d'accès déclarés dans le conteneur Spring Ioc.
-
Enregistrez un plug-in Struts prêt à l'emploi Spring dans le fichier de configuration Struts.
-
Modifiez votre classe d'action Struts pour étendre la classeActionSupport de Spring, une sous-classe de la classe Action Struts.
-
LesActionSupport fournissent une méthodegetWebApplicationContext() pratique pour vous permettre d'accéder aux beans déclarés dans le conteneur Spring Ioc.
1. Dépendances Struts + Spring
Pour s'intégrer à Struts 1.x, Spring a besoin des bibliothèques «spring-web.jar» et «spring-struts.jar». Vous pouvez le télécharger sur le site Web de Spring ou sur Maven.
pom.xml
org.springframework spring 2.5.6 org.springframework spring-web 2.5.6 org.springframework spring-struts 2.0.8
2. Enregistrer le plug-in Struts
Dans votre fichier de configuration Struts (struts-config.xml), enregistrez le plug-in Struts prêt à l'emploi de Spring - «ContextLoaderPlugIn».
struts-config.xml
Le «ContextLoaderPlugIn» gérera tout le travail d'intégration entre Struts et Spring. Vous pouvez charger le fichier xml de votre bean Spring dans la propriété «contextConfigLocation».
SpringBeans.xml
3. Spring's ActionSupport
Dans la classe Struts Action, étend la classe Spring «ActionSupport» et récupère le bean Spring via la méthode «getWebApplicationContext()».
CustomerBean.xml
Struts Action
package com.example.customer.action; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.springframework.web.struts.ActionSupport; import com.example.customer.bo.CustomerBo; import com.example.customer.model.Customer; public class ListCustomerAction extends ActionSupport{ public ActionForward execute(ActionMapping mapping,ActionForm form, HttpServletRequest request,HttpServletResponse response) throws Exception { CustomerBo customerBo = (CustomerBo) getWebApplicationContext().getBean("customerBo"); ... return mapping.findForward("success"); } }
Terminé.