vendredi 3 juin 2011

Maven Spring MVC 3 with JBOSS 6 example

Objectifs :

Le principal objectifs de cet exemple est de montrer une configuration Maven qui fonctionne pour Spring MVC 3 et JBoss6.
Le code source est disponible sur Google code : http://code.google.com/p/lin-mon-webapp/ (cf wiki tutorial1)

Arborescence du projet :



Maven :

Il faut noter que la version de Spring qui est utilisée est la version 3.0.5.Les versions antérieurs ne fonctionne pas avec JBOSS 6 du fait d'un bug sur le VFS de JBOSS. Dans ce projet exemple, je n'ai mis que les dépendances utiles (à vous de me dire si je ne dit pas de bétises ...)


Voici le pom.xml du projet :

<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    <groupId>fr.dr.monitor</groupId>
    <artifactId>monitor</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>Monitor app</name>
    
    <dependencies>
      <dependency>
            <groupId>org.springframework</groupId>
     <artifactId>spring-beans</artifactId>
     <version>${org.springframework.version}</version>
      </dependency>


      <dependency>
    <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
    <version>${org.springframework.version}</version>
      </dependency>
      <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
     <version>${org.springframework.version}</version>
      </dependency>


      <dependency>
     <groupId>javax.servlet</groupId>
     <artifactId>servlet-api</artifactId>
     <version>2.5</version>
      </dependency>  


      <dependency>
     <groupId>taglibs</groupId>
     <artifactId>standard</artifactId>
     <version>1.1.2</version>
      </dependency>
      <dependency>
     <groupId>javax.servlet</groupId>
     <artifactId>jstl</artifactId>
     <version>1.1.2</version>
      </dependency>


      <dependency>
     <groupId>junit</groupId>
     <artifactId>junit</artifactId>
     <version>4.5</version>
     <scope>runtime</scope>
      </dependency>
      <dependency>
     <groupId>log4j</groupId>
     <artifactId>log4j</artifactId>
     <version>1.2.14</version>
      </dependency>
</dependencies>


<build>
<finalName>monitor</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
<verbose>true</verbose>
</configuration>
</plugin>

<!-- Permet de créer un projet eclipse avec Maven -->
<plugin>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.4</version>
<configuration>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
</plugins>
</build>
  
<properties>
    <org.springframework.version>3.0.5.RELEASE</org.springframework.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
</project>


src/main/resources/spring.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"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/tx/spring-aop-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"
default-autowire="byName">
<!--
Activates various annotations to be detected in bean classes: Spring's
@Required and @Autowired, as well as JSR 250's @PostConstruct,
@PreDestroy and @Resource (if available) and JPA's @PersistenceContext
and @PersistenceUnit (if available).
-->
<context:annotation-config/>
</beans>



/WEB-INF/web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
  <display-name>Maven Spring MVC 3 with JBOSS 6 </display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:/spring.xml
</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>     
  
  <!-- declare la servlet frontale centrale  -->
  <servlet>
<servlet-name>monitor</servlet-name>
<display-name>monitor</display-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/monitor-servlet.xml</param-value>
    </init-param>
<load-on-startup>1</load-on-startup>
  </servlet>
 
  <servlet-mapping>
<servlet-name>monitor</servlet-name>
<url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>


/WEB-INF/monitor-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- Fichier de conf du contexte d'application pour spring (fichier nommé spring-mvc-webapp-servlet.xml selon la convention. -->
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"
default-autowire="byName">
<!-- - Tous les controlleurs sont automatiquement détectés grâce à l'annotation @Controller.
- On définit ici dans quel package le post processor doit chercher ces beans annotés. -->
  <context:component-scan base-package="fr.dr.monitor.controller"/>  
<!-- Activates various annotations to be detected in bean classes: Spring's
@Required and @Autowired, as well as JSR 250's @PostConstruct,@PreDestroy and 
@Resource (if available) and JPA's @PersistenceContext & @PersistenceUnit.
-->
<context:annotation-config/>
<!--
- Les controlleurs de cette application fournissent une annotation @RequestMapping 
- Qui peuvent être déclaré de deux manière différentes:
-  Au niveau de la classe : 
-      par exemple @RequestMapping("/addVisit.html")
-      Pour ce type de controlleurs on peut annoter les méthodes pour une requete Post ou Get,
- Au niveau de chaque méthodes, différents exemples  seront fournis.  
-->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
<!--
Ceci est le view resolver, il permet de définir la technologie de vue utilisée et comment
sélectionner une vue. Ici on prendra la solution la plus simple elle permet de mapper 
le nom de la vue retournée avec la sélection d'une jsp. Ex. si le nom de la vue retournée est "hello" alors on utilisera le fichier
WEB-INF/jsp/hello.jsp pour constuire la vue. 
-->
<bean 
class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp"/>
</beans>


/WEB-INF/jsp/index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page isELIgnored ="false" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Home</title>
</head>
<body>

Bonjour ${name},

</body>
</html>


fr.dr.monitor.controller.MainController

package fr.dr.monitor.controller;


import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;




@Controller
public class MainController  {


final Logger logger=Logger.getLogger(getClass().getName());


/**
   * Handler de la méthode Get pour l'URL /helloSpringMVC.html. 
   * 
   * @param name le nom que l'on doit afficher dans la vue.
   * @param model une map de toutes les données qui seront utilisables dans la vue 
   * @return le nom de la vue qu'il faudra utiliser.
   */
 @RequestMapping(value="/")
 public  String toIndex(
   @RequestParam(value="name",required=false) String name, 
   ModelMap model) 
 {
logger.info(">toIndex");
   model.addAttribute("name",name);
   logger.info(">add attribute name " + name);
   
   // on utilisera donc le fichier /WEB-INF/jsp/index.jsp
   //au regard de la stratégie de résolution des vues 
   //utilisée dans cette application.
   return "index";
 }


}

Réferences :
http://blog.springsource.com/2011/01/04/green-beans-getting-started-with-spring-mvc
http://www.jairrillo.com/blog/2009/04/22/creating-a-project-using-maven-jsf-richfaces-facelets-tomahawk-hibernate-in-5-minutes/

Aucun commentaire:

Enregistrer un commentaire