mardi 18 janvier 2011

Spring Webservice 2.0 with JaxB (Maven, Hibernate, Tomcat)




Pré-requis
Pour ce tutorial, nous travaillons avec Maven 3.0, Spring 3.0, Spring WS 2.0, JaxB 2.1, Hibernate 3.4, Tomcat 6.0.29, JDK 1.6.0.17.
L'ensemble de cette architecture est disponible dans le zip hoteia-howto-spring-ws-jaxb-full.
Un second fichier, hoteia-howto-spring-ws-jaxb-project, ne contient que le workspace.
Mise en place du core, Service & DAO

Création de l'entité Person, de son DAO et de son service tel que :

Person.java

package com.hoteia.howto.spring.domain;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Version;

@Entity
@Table(name = "hoteia_person")
@NamedQueries({
 @NamedQuery(name="person.personByLastname", query="FROM Person person WHERE person.lastname = :lastname")
})
public class Person implements Serializable {

 /**
  * Generated UID
  */
 private static final long serialVersionUID = 5907376955767500978L;

 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 private Long id;
 
 @Version
 private int version;
 
 private String title;
 private String lastname;
 private String firstname;

 public Long getId() {
  return id;
 }

 public void setId(Long id) {
  this.id = id;
 }
 
 public int getVersion() {
  return version;
 }

 public void setVersion(int version) {
  this.version = version;
 }

 public String getTitle() {
  return title;
 }

 public void setTitle(String title) {
  this.title = title;
 }

 public String getLastname() {
  return lastname;
 }
 
 public void setLastname(String lastname) {
  this.lastname = lastname;
 }
 
 public String getFirstname() {
  return firstname;
 }
 
 public void setFirstname(String firstname) {
  this.firstname = firstname;
 }

 @Override
 public String toString() {
  return "Person [id=" + id + ", version=" + version + ", title=" + title
    + ", lastname=" + lastname + ", firstname=" + firstname + "]";
 }

 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result
    + ((firstname == null) ? 0 : firstname.hashCode());
  result = prime * result + ((id == null) ? 0 : id.hashCode());
  result = prime * result
    + ((lastname == null) ? 0 : lastname.hashCode());
  result = prime * result + ((title == null) ? 0 : title.hashCode());
  result = prime * result + version;
  return result;
 }

 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  Person other = (Person) obj;
  if (firstname == null) {
   if (other.firstname != null)
    return false;
  } else if (!firstname.equals(other.firstname))
   return false;
  if (id == null) {
   if (other.id != null)
    return false;
  } else if (!id.equals(other.id))
   return false;
  if (lastname == null) {
   if (other.lastname != null)
    return false;
  } else if (!lastname.equals(other.lastname))
   return false;
  if (title == null) {
   if (other.title != null)
    return false;
  } else if (!title.equals(other.title))
   return false;
  if (version != other.version)
   return false;
  return true;
 }
 
}
       

PersonDaoImpl.java

package com.hoteia.howto.spring.dao.impl;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.hoteia.howto.spring.dao.PersonDao;
import com.hoteia.howto.spring.domain.Person;

@Repository("personDao")
@Transactional
@Scope("prototype")
public class PersonDaoImpl extends BaseDaoImpl implements PersonDao {

 protected final Log logger = LogFactory.getLog(getClass());
 
 public Person getPersonById(String personId) {
  return hibernateTemplate.get(Person.class, new Long(personId));
 }

 @SuppressWarnings("unchecked")
 public Person getPersonByLastname(String lastname) {
  String[] parameterNames = new String[] { "lastname" };
  String[] parameterValues = new String[] { lastname };
  List<Person> persons = hibernateTemplate.findByNamedQueryAndNamedParam("person.personByLastname", parameterNames, parameterValues);
  if(persons != null
    && persons.size() > 1){
   return persons.get(0);
  } else {
   return null;
  }
 }
 
 @SuppressWarnings("unchecked")
 public List<Person> findAllPerson(Person person) {
  return (List<Person>) hibernateTemplate.find("from " + Person.class.getName());
 }

 @Transactional(readOnly = false)
 public void savePerson(Person person) {
  hibernateTemplate.saveOrUpdate(person);
 }

 @Transactional(readOnly = false)
 public void deletePerson(Person person) {
  hibernateTemplate.delete(person);

 }

}
       

hoteia-howto-spring-dao.xml, context des DAOs, qui sera packagé dans le jar pour être importé dans le context de la webapp.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
     xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
     ">

 <context:component-scan base-package="com.hoteia.howto"/>
 
</beans>
       

PersonServiceImpl.java

package com.hoteia.howto.spring.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.hoteia.howto.spring.dao.PersonDao;
import com.hoteia.howto.spring.domain.Person;
import com.hoteia.howto.spring.service.PersonService;

@Repository("personService")
public class PersonServiceImpl implements PersonService {
 
 @Autowired
 private PersonDao personDao;

 public Person getPersonById(String personId) {
  return personDao.getPersonById(personId);
 }
 
 public Person getPersonByLastname(String lastname) {
  return personDao.getPersonByLastname(lastname);
 }

 public List<Person> findAllPerson(Person person) {
  return personDao.findAllPerson(person);
 }
 
 public void savePerson(Person person) {
  personDao.savePerson(person);
 }

 public void deletePerson(Person person) {
  personDao.deletePerson(person);
 }

}
       

hoteia-howto-spring-service.xml, context des Services, qui sera packagé dans le jar pour être importé dans le context de la webapp.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
     xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
     ">

 <context:component-scan base-package="com.hoteia.howto"/>

</beans>
       
Mise en place du client/server ws

person.xsd

<?xml version="1.0" encoding="UTF-8"?>
                    
<xsd:schema xmlns="http://localhost:8280/ws-in/ws/services/person/schemas"
            targetNamespace="http://localhost:8280/ws-in/ws/services/person/schemas"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema">

    <xsd:element name="save-persons-request">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="person" type="person" minOccurs="0" maxOccurs="unbounded" />
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element> 
    
    <xsd:element name="save-persons-response">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="response" type="response" minOccurs="0" maxOccurs="1" />
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>

    <xsd:complexType name="person">
        <xsd:sequence>
            <xsd:element name="id" type="xsd:string" />
            <xsd:element name="lastname" type="xsd:string" />
            <xsd:element name="firstname" type="xsd:string" />
        </xsd:sequence>
    </xsd:complexType>

    <xsd:complexType name="response">
        <xsd:sequence>
            <xsd:element name="message" type="xsd:string" />
            <xsd:element name="code" type="xsd:string" />
            <xsd:element name="status" type="xsd:string" />
        </xsd:sequence>
    </xsd:complexType>
 
</xsd:schema>

       

PersonEndpoint.java

package com.hoteia.howto.spring.ws;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;

import com.hoteia.howto.spring.Constants;
import com.hoteia.howto.spring.ws.jaxb.pojo.ObjectFactory;
import com.hoteia.howto.spring.ws.jaxb.pojo.SavePersonsRequest;
import com.hoteia.howto.spring.ws.jaxb.pojo.SavePersonsResponse;
import com.hoteia.howto.spring.ws.service.PersonEndPointService;

/**
 * Person Web service endpoint. Uses a PersonService to create a response string.
 *
 */
@Endpoint
public class PersonEndpoint {

 protected final Log logger = LogFactory.getLog(getClass());
 
    /**
     * The local name of the expected request.
     */
    public static final String PERSON_REQUEST_LOCAL_NAME = "save-persons-request";

    /**
     * The local name of the created response.
     */
    public static final String PERSON_RESPONSE_LOCAL_NAME = "save-persons-response";

    @Autowired
 private PersonEndPointService personEndPointService;

    /**
     * Reads the given requestElement, and sends a the response back.
     *
     * @param requestElement the contents of the SOAP message as DOM elements
     * @return the response element
     */
    @PayloadRoot(localPart = PERSON_REQUEST_LOCAL_NAME, namespace = Constants.NAMESPACE_URI)
    public SavePersonsResponse handleSavePersonsResponseRequest(SavePersonsRequest savePersonsRequest) {
     
  ObjectFactory objFactory = new ObjectFactory();
  SavePersonsResponse savePersonsResponse = objFactory.createSavePersonsResponse();
  personEndPointService.savePersons(savePersonsRequest, savePersonsResponse);
   
        return savePersonsResponse;
    }
    
}
       

PersonEndPointServiceImpl.java

package com.hoteia.howto.spring.ws.service.impl;

import java.util.Iterator;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.hoteia.howto.spring.domain.Person;
import com.hoteia.howto.spring.service.PersonService;
import com.hoteia.howto.spring.ws.jaxb.pojo.ObjectFactory;
import com.hoteia.howto.spring.ws.jaxb.pojo.Response;
import com.hoteia.howto.spring.ws.jaxb.pojo.SavePersonsRequest;
import com.hoteia.howto.spring.ws.jaxb.pojo.SavePersonsResponse;
import com.hoteia.howto.spring.ws.service.PersonEndPointService;

/**
* Default implementation of PersonEndPointService.
*
*/
public class PersonEndPointServiceImpl implements PersonEndPointService {

protected final Log logger = LogFactory.getLog(getClass());

private PersonService personService;

public void setPersonService(PersonService personService) {
this.personService = personService;
}

public void savePersons(SavePersonsRequest savePersonsRequest, SavePersonsResponse savePersonsResponse) {
try {

for (Iterator<com.hoteia.howto.spring.ws.jaxb.pojo.Person> iterator = savePersonsRequest.getPerson().iterator(); iterator.hasNext();) {
com.hoteia.howto.spring.ws.jaxb.pojo.Person personPojo = (com.hoteia.howto.spring.ws.jaxb.pojo.Person) iterator.next();

Person person = new Person();
if(StringUtils.isNotEmpty(personPojo.getId())){
person = personService.getPersonById(personPojo.getId());
}
person.setLastname(personPojo.getLastname());
person.setFirstname(personPojo.getFirstname());

personService.savePerson(person);

}

ObjectFactory objFactory = new ObjectFactory();
Response response = objFactory.createResponse();
response.setCode("SUCCESS");
response.setMessage("SUCCESS");
response.setStatus("SUCCESS");

savePersonsResponse.setResponse(response);

} catch (Exception e) {
logger.error("Error during the save of the persons", e);

ObjectFactory objFactory = new ObjectFactory();
Response response = objFactory.createResponse();
response.setCode("ERROR");
response.setMessage("ERROR");
response.setStatus("ERROR");

savePersonsResponse.setResponse(response);
}

}
}

PersonClient.java

package com.hoteia.howto.spring.ws.client;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.ws.client.core.support.WebServiceGatewaySupport;

import com.hoteia.howto.spring.ws.jaxb.pojo.SavePersonsRequest;
import com.hoteia.howto.spring.ws.jaxb.pojo.SavePersonsResponse;

public class PersonClient extends WebServiceGatewaySupport {

 protected final Log logger = LogFactory.getLog(PersonClient.class.getName());

    public void savePersons(SavePersonsRequest savePersonsRequest) throws Exception {
        SavePersonsResponse savePersonsResponse = (SavePersonsResponse) getWebServiceTemplate().marshalSendAndReceive(savePersonsRequest);
  
        if(savePersonsResponse.getResponse().getCode().equals("ERROR")){
   logger.error("something is wrong with the person ws response");
  }

    }
}
       

Nous découpons les contexts Spring en 3 fichiers common, server, client, afin de pouvoir les importer depuis le même jar sans contrainte.

spring-ws-common.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

    <bean id="xsdSchema" class="org.springframework.xml.xsd.SimpleXsdSchema">
        <description>
            This bean definition contains the XSD schema.
        </description>
        <property name="xsd" ref="xsd"/>
    </bean>
 
 <bean id="marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
        <description>
            The JAXB 2 Marshaller is used by the endpoints.
        </description>
  <property name="contextPath" value="com.hoteia.howto.spring.ws.jaxb.pojo"/>
        <property name="schema" ref="xsd"/>
    </bean>
 
    <bean class="org.springframework.ws.server.endpoint.adapter.GenericMarshallingMethodEndpointAdapter">
        <description>
            This adapter allows for methods that need and returns marshalled objects. The MarshallingEndpoint
            uses JAXB 2 objects.
        </description>
        <constructor-arg ref="marshaller"/>
    </bean>

 <bean id="xsd" class="java.lang.String">
     <constructor-arg type="String" value="classpath:/person.xsd"/>
    </bean>
</beans>
       

spring-ws-server.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

    <description>
        This web application context contains Spring-WS beans. The beans defined in this context are automatically
        detected by Spring-WS, similar to the way Controllers are picked up in Spring Web MVC.
    </description>

    <import resource="spring-ws-common.xml" />
 
    <bean id="personEndPointService" class="com.hoteia.howto.spring.ws.service.impl.PersonEndPointServiceImpl">
        <description>
            This bean is the person service.
        </description>
        <property name="personService" ref="personService"/>
    </bean>
 
    <bean id="payloadMapping" class="org.springframework.ws.server.endpoint.mapping.PayloadRootAnnotationMethodEndpointMapping">
        <description>
            This endpoint mapping uses the qualified name of the payload (body contents) to determine the endpoint for
            an incoming message. Every message is passed to the default endpoint. Additionally, messages are logged
            using the logging interceptor.
        </description>
        <property name="interceptors">
            <list>
                <ref local="validatingInterceptor"/>
                <ref local="loggingInterceptor"/>
            </list>
        </property>
    </bean>

    <bean id="validatingInterceptor"
          class="org.springframework.ws.soap.server.endpoint.interceptor.PayloadValidatingInterceptor">
        <description>
            This interceptor validates both incoming and outgoing message contents according to the 'person.xsd' XML
            Schema file.
        </description>
        <property name="xsdSchema" ref="xsdSchema"/>
        <property name="validateRequest" value="true"/>
        <property name="validateResponse" value="true"/>
    </bean>

    <bean class="org.springframework.ws.server.endpoint.adapter.DefaultMethodEndpointAdapter"/>

    <bean id="loggingInterceptor" class="org.springframework.ws.server.endpoint.interceptor.PayloadLoggingInterceptor">
        <description>
            This interceptor logs the message payload.
        </description>
    </bean>

    <bean id="person" class="org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition">
        <description>
            This bean definition represents a WSDL definition that is generated at runtime. It can be retrieved by
            going to http://localhost:8280/ws-in/ws/services/person/person.wsdl (i.e. the bean name corresponds to the filename).
        </description>
        <property name="schema" ref="xsdSchema"/>
        <property name="portTypeName" value="Person"/>
        <property name="locationUri" value="http://localhost:8280/ws-in/ws/services/person"/>
        <property name="targetNamespace" value="http://localhost:8280/ws-in/ws/services/person/schemas"/>
    </bean>
 


</beans>
       

spring-ws-client.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

    <import resource="spring-ws-common.xml" />

    <bean id="personClient" class="com.hoteia.howto.spring.ws.client.PersonClient">
        <property name="defaultUri" value="http://localhost:8280/ws-in/ws/services/person"/>
        <property name="marshaller" ref="marshaller"/>
        <property name="unmarshaller" ref="marshaller"/>
    </bean>

</beans>
       
Mise en place d'un front pour la sortie (envoi) Webservice

Nous utiliserons uniquement un controleur pour constuire n "Persons", et les envoyer via le webservice distant.

PersonController.java

package com.hoteia.howto.spring.mvc.controller;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.hoteia.howto.spring.ws.client.PersonClient;
import com.hoteia.howto.spring.ws.jaxb.pojo.ObjectFactory;
import com.hoteia.howto.spring.ws.jaxb.pojo.Person;
import com.hoteia.howto.spring.ws.jaxb.pojo.SavePersonsRequest;

@Controller
@RequestMapping("/sendPersons")
public class PersonController {

 protected final Log logger = LogFactory.getLog(getClass());

 @Autowired
 private PersonClient personClient;
 
 @RequestMapping(method = RequestMethod.GET)
 public ModelAndView parse(){
  if(logger.isDebugEnabled()){
   logger.debug("sendPersons");
  }
  
  try {
   ObjectFactory objFactory = new ObjectFactory();
   
   SavePersonsRequest savePersonsRequest = objFactory.createSavePersonsRequest();
   
   Map<String, Person> persons = buildPersonDetails();

   int poolSize = 50;
   int count = 1;
         for (Iterator<Person> iterator = persons.values().iterator(); iterator.hasNext();) {

          Person person = (Person) iterator.next();
    savePersonsRequest.getPerson().add(person);

    if(count == poolSize
      || count == persons.size()){
     personClient.savePersons(savePersonsRequest);
     savePersonsRequest = objFactory.createSavePersonsRequest();
     count = 1;
    }

    count++;
    
         }
   
  } catch (Exception e) {
   logger.error("Error on the parse controller", e);
  }

  ModelAndView model = new ModelAndView("sendPersons-view");
 
  return model;
 }
 
 private Map<String, Person> buildPersonDetails(){
  if(logger.isDebugEnabled()){
   logger.debug("start to build person Map");
  }

  Map<String, Person> persons = new HashMap<String, Person>();
  
  Person person = new Person();
  person.setId("");
  person.setLastname("Bar");
  person.setFirstname("Foo");
  persons.put(person.getLastname() + "-" + person.getFirstname(), person);
  
  if(logger.isDebugEnabled()){
   logger.debug("stop to build person Map");
  }
  
  return persons;
 }
}
       

dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

 <!-- Scans the classpath of this application for @Components to deploy as beans -->
 <context:component-scan base-package="com.hoteia.howto.spring.mvc" />

 <!-- Application Message Bundle -->
 <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
  <property name="basename" value="/WEB-INF/classes/ApplicationResources" />
  <property name="cacheSeconds" value="0" />
 </bean>

 <!-- Configures Spring WS Client -->
 <import resource="classpath*:spring-ws-client.xml" />

 <!-- Configures Spring MVC -->
 <import resource="mvc-config.xml" />

</beans>
       

mvc-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

 <!-- Configures the @Controller programming model -->
 <mvc:annotation-driven />

 <!-- Forwards requests to the "/" resource to the "welcome" view -->
 <mvc:view-controller path="/" view-name="welcome"/>

 <!-- Configures Handler Interceptors --> 
 <mvc:interceptors>
  <!-- Changes the locale when a 'locale' request parameter is sent; e.g. /?locale=de -->
  <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
 </mvc:interceptors>

 <!-- Saves a locale change using a cookie -->
 <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />

 <!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="/WEB-INF/views/"/>
  <property name="suffix" value=".jsp"/>
 </bean>

</beans>
       
Mise en place d'un front pour l'entrée (réception) Webservice

dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

 <!-- Scans the classpath of this application for @Components to deploy as beans -->
 <context:component-scan base-package="com.hoteia.howto.spring.mvc" />
 
 <!-- Configures Spring MVC -->
 <import resource="mvc-config.xml" />
 
 <!-- Application Message Bundle -->
 <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
  <property name="basename" value="/WEB-INF/classes/ApplicationResources" />
  <property name="cacheSeconds" value="0" />
 </bean>

</beans>
       

mvc-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

 <!-- Configures the @Controller programming model -->
 <mvc:annotation-driven />

 <!-- Forwards requests to the "/" resource to the "welcome" view -->
 <mvc:view-controller path="/" view-name="welcome"/>

 <!-- Configures Handler Interceptors --> 
 <mvc:interceptors>
  <!-- Changes the locale when a 'locale' request parameter is sent; e.g. /?locale=de -->
  <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
 </mvc:interceptors>

 <!-- Saves a locale change using a cookie -->
 <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />

 <!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="/WEB-INF/views/"/>
  <property name="suffix" value=".jsp"/>
 </bean>

</beans>
       

db-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
     xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
     ">

 <context:component-scan base-package="com.hoteia.howto"/>
  
 <!-- Configures Spring WS Server -->
 <import resource="classpath*:spring-ws-server.xml" />

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
        <property name="packagesToScan" value="com.hoteia.howto.spring.domain" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.hbm2ddl.auto">create</prop>
                <prop key="hibernate.show_sql">false</prop>
            </props>
        </property>
    </bean>

    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory">
            <ref bean="sessionFactory" />
        </property>
    </bean>
 
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:jdbc.properties</value>
            </list>
        </property>
    </bean>
 
 <!-- JNDI DataSource for J2EE environments -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="maxActive" value="100"/>
        <property name="maxWait" value="1000"/>
        <property name="poolPreparedStatements" value="true"/>
        <property name="defaultAutoCommit" value="true"/>
    </bean>
 
</beans>
       

1 commentaire:

  1. Merci beaucoup pour ce tuto, c'est rare de trouver quelque chose d'aussi complet! surtout avec les sources complètes en téléchargement. Thx

    Fred.

    RépondreSupprimer