Spring MVC passo-a-passo - Parte 1
Autor: Evaldo Wolkers | Publicado: 2012-02-29T07:57:00-08:00



Capítulo 1.&nbsp;Aplicação Básica&nbsp;e &nbsp;Preparação do Ambiente







1.1.&nbsp;Criando a estrutura de&nbsp;diretório do projeto







Abra o Eclipse (pode utilizar a workspace padrão ou criar uma nova workspace), vá ao Menu File e escolha ‘New / Java Project’. Informe o nome do projeto ‘springapp’ e clique em ‘Finish’.



Clique no seu projeto ‘springapp’ e no menu File escolha ‘New / Folder’, em ‘Folder name‘ informe ‘war’ e clique em ‘Finish’.







A Estrutura de diretórios do projeto





1.2.&nbsp;Criando o arquivo ‘index.jsp‘



Como estamos criando uma aplicação web, vamos criar uma página JSP simples chamada ‘index.jsp‘ no diretório ‘war’. O ‘index.jsp‘ é o ponto de entrada para a nossa aplicação. Vá ao menu ‘File’ e escolha ‘New / File’. Clique no diretório ‘war’ e informe o nome ‘index.jsp’. Clique em ‘Finish’ e digite o código abaixo.



‘springapp/war/índex.jsp‘

&lt;html&gt;

&nbsp; &nbsp; &lt;head&gt;&lt;title&gt;Exemplo: Spring Application&lt;/title&gt;&lt;/head&gt;

&nbsp; &nbsp; &lt;body&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;h1&gt;Exemplo Spring Application&lt;/h1&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;p&gt;Meu teste Spring.&lt;/p&gt;

&nbsp; &nbsp; &lt;/body&gt;

&lt;/html&gt;



Para termos uma aplicação web completa vamos criar um diretório chamado ‘WEB-INF’ dentro do diretório ‘war’ e colocar um arquivo ‘web.xml’ neste novo diretório. Não descreverei os passos porque já criamos um diretório e um arquivo anteriormente.



‘springapp/war/WEB-INF/web.xml‘



&lt;?xml version="1.0" encoding="UTF-8"?&gt;

&lt;web-app version="2.4"

&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; xmlns="http://java.sun.com/xml/ns/j2ee"

&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee&nbsp;

&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" &gt;



&nbsp; &lt;servlet&gt;

 &lt;servlet-name&gt;springapp&lt;/servlet-name&gt;

 &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;

 &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;

&nbsp; &lt;/servlet&gt;



&nbsp; &lt;servlet-mapping&gt;

 &lt;servlet-name&gt;springapp&lt;/servlet-name&gt;

 &lt;url-pattern&gt;*.htm&lt;/url-pattern&gt;

&nbsp; &lt;/servlet-mapping&gt;



&nbsp; &lt;welcome-file-list&gt;

&nbsp; &nbsp; &lt;welcome-file&gt;

&nbsp; &nbsp; &nbsp; index.jsp

&nbsp; &nbsp; &lt;/welcome-file&gt;

&nbsp; &lt;/welcome-file-list&gt;

&lt;/web-app&gt;






1.2.&nbsp;Fazendo o deploy da aplicação no Tomcat



Vamos agora escrever o script de construção Ant que vamos utilizar ao longo deste tutorial. Este script Ant conterá targets para compilação, construção e deploy da aplicação. Um script de construção separado será utilizado para targets específicos de um servidor de aplicação, como targets para controlar a aplicação no Tomcat.



‘springapp/build.xml’:



&lt;?xml version="1.0"?&gt;



&lt;project name="springapp" basedir="." default="usage"&gt;

&nbsp; &nbsp; &lt;property file="build.properties"/&gt;



&nbsp; &nbsp; &lt;property name="src.dir" value="src"/&gt;

&nbsp; &nbsp; &lt;property name="web.dir" value="war"/&gt;

&nbsp; &nbsp; &lt;property name="build.dir" value="${web.dir}/WEB-INF/classes"/&gt;

&nbsp; &nbsp; &lt;property name="name" value="springapp"/&gt;

 &lt;property name="test.dir" value="test"/&gt;



&nbsp; &nbsp; &lt;path id="master-classpath"&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;fileset dir="${web.dir}/WEB-INF/lib"&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;include name="*.jar"/&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;/fileset&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;!-- We need the servlet API classes: --&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;!--&nbsp; * for Tomcat 5/6 use servlet-api.jar --&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;!--&nbsp; * for other app servers - check the docs --&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;fileset dir="${appserver.lib}"&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;include name="servlet*.jar"/&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;/fileset&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;pathelement path="${build.dir}"/&gt;

&nbsp; &nbsp; &lt;/path&gt;



&nbsp; &nbsp; &lt;target name="usage"&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;echo message=""/&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;echo message="${name} build file"/&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;echo message="-----------------------------------"/&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;echo message=""/&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;echo message="Available targets are:"/&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;echo message=""/&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;echo message="build &nbsp; &nbsp; --&gt; Build the application"/&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;echo message="deploy&nbsp; &nbsp; --&gt; Deploy application as directory"/&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;echo message="deploywar --&gt; Deploy application as a WAR file"/&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;echo message="install &nbsp; --&gt; Install application in Tomcat"/&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;echo message="reload&nbsp; &nbsp; --&gt; Reload application in Tomcat"/&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;echo message="start &nbsp; &nbsp; --&gt; Start Tomcat application"/&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;echo message="stop&nbsp; &nbsp; &nbsp; --&gt; Stop Tomcat application"/&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;echo message="list&nbsp; &nbsp; &nbsp; --&gt; List Tomcat applications"/&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;echo message=""/&gt;

&nbsp; &nbsp; &lt;/target&gt;



&nbsp; &nbsp; &lt;target name="build" description="Compile main source tree java files"&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;mkdir dir="${build.dir}"/&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;javac destdir="${build.dir}" source="1.5" target="1.5" debug="true"

&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; deprecation="false" optimize="false" failonerror="true" includeantruntime="false"&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;src path="${src.dir}"/&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;classpath refid="master-classpath"/&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;/javac&gt;

&nbsp; &nbsp; &lt;/target&gt;



&nbsp; &nbsp; &lt;target name="deploy" depends="build" description="Deploy application"&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;copy todir="${deploy.path}/${name}" preservelastmodified="true"&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;fileset dir="${web.dir}"&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;include name="**/*.*"/&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;/fileset&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;/copy&gt;

&nbsp; &nbsp; &lt;/target&gt;



&nbsp; &nbsp; &lt;target name="deploywar" depends="build" description="Deploy application as a WAR file"&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;war destfile="${name}.war"

&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; webxml="${web.dir}/WEB-INF/web.xml"&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;fileset dir="${web.dir}"&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;include name="**/*.*"/&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;/fileset&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;/war&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;copy todir="${deploy.path}" preservelastmodified="true"&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;fileset dir="."&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;include name="*.war"/&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;/fileset&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;/copy&gt;

&nbsp; &nbsp; &lt;/target&gt;

&nbsp;&nbsp; &nbsp;

 &lt;target name="buildtests" description="Compile test tree java files"&gt;

 &nbsp; &nbsp; &nbsp; &nbsp; &lt;mkdir dir="${build.dir}"/&gt;

 &nbsp; &nbsp; &nbsp; &nbsp; &lt;javac destdir="${build.dir}" source="1.5" target="1.5" debug="true"

 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; deprecation="false" optimize="false" failonerror="true"&gt;

 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;src path="${test.dir}"/&gt;

 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;classpath refid="master-classpath"/&gt;

 &nbsp; &nbsp; &nbsp; &nbsp; &lt;/javac&gt;

 &lt;/target&gt;

 

 &lt;target name="tests" depends="build, buildtests" description="Run tests"&gt;

 &nbsp; &nbsp; &nbsp; &nbsp; &lt;junit printsummary="on"

 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fork="false"

 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; haltonfailure="false"

 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; failureproperty="tests.failed"

 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; showoutput="true"&gt;

 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;classpath refid="master-classpath"/&gt;

 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;formatter type="brief" usefile="false"/&gt;

  &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;

 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;batchtest&gt;

 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;fileset dir="${build.dir}"&gt;

 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;include name="**/*Tests.*"/&gt;

 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;/fileset&gt;

 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;/batchtest&gt;

  &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;

 &nbsp; &nbsp; &nbsp; &nbsp; &lt;/junit&gt;

  &nbsp; &nbsp; &nbsp; &nbsp;

 &nbsp; &nbsp; &nbsp; &nbsp; &lt;fail if="tests.failed"&gt;

 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tests.failed=${tests.failed}

 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ***********************************************************

 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ***********************************************************

 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ****&nbsp; One or more tests failed!&nbsp; Check the output ...&nbsp; ****

 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ***********************************************************

 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ***********************************************************

 &nbsp; &nbsp; &nbsp; &nbsp; &lt;/fail&gt;

 &nbsp; &nbsp; &lt;/target&gt;

 

&lt;!-- ============================================================== --&gt;

&lt;!-- Tomcat tasks - remove these if you don't have Tomcat installed --&gt;

&lt;!-- ============================================================== --&gt;



&nbsp; &nbsp; &lt;path id="catalina-ant-classpath"&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;!-- We need the Catalina jars for Tomcat --&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;!--&nbsp; * for other app servers - check the docs --&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;fileset dir="${appserver.lib}"&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;include name="catalina-ant.jar"/&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;/fileset&gt;

&nbsp; &nbsp; &lt;/path&gt;



&nbsp; &nbsp; &lt;taskdef name="install" classname="org.apache.catalina.ant.InstallTask"&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;classpath refid="catalina-ant-classpath"/&gt;

&nbsp; &nbsp; &lt;/taskdef&gt;

&nbsp; &nbsp; &lt;taskdef name="reload" classname="org.apache.catalina.ant.ReloadTask"&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;classpath refid="catalina-ant-classpath"/&gt;

&nbsp; &nbsp; &lt;/taskdef&gt;

&nbsp; &nbsp; &lt;taskdef name="list" classname="org.apache.catalina.ant.ListTask"&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;classpath refid="catalina-ant-classpath"/&gt;

&nbsp; &nbsp; &lt;/taskdef&gt;

&nbsp; &nbsp; &lt;taskdef name="start" classname="org.apache.catalina.ant.StartTask"&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;classpath refid="catalina-ant-classpath"/&gt;

&nbsp; &nbsp; &lt;/taskdef&gt;

&nbsp; &nbsp; &lt;taskdef name="stop" classname="org.apache.catalina.ant.StopTask"&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;classpath refid="catalina-ant-classpath"/&gt;

&nbsp; &nbsp; &lt;/taskdef&gt;



&nbsp; &nbsp; &lt;target name="install" description="Install application in Tomcat"&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;install url="${tomcat.manager.url}"

&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; username="${tomcat.manager.username}"

&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; password="${tomcat.manager.password}"

&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; path="/${name}"

&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; war="${name}"/&gt;

&nbsp; &nbsp; &lt;/target&gt;



&nbsp; &nbsp; &lt;target name="reload" description="Reload application in Tomcat"&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;reload url="${tomcat.manager.url}"

&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; username="${tomcat.manager.username}"

&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; password="${tomcat.manager.password}"

&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; path="/${name}"/&gt;

&nbsp; &nbsp; &lt;/target&gt;



&nbsp; &nbsp; &lt;target name="start" description="Start Tomcat application"&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;start url="${tomcat.manager.url}"

&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; username="${tomcat.manager.username}"

&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; password="${tomcat.manager.password}"

&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; path="/${name}"/&gt;

&nbsp; &nbsp; &lt;/target&gt;



&nbsp; &nbsp; &lt;target name="stop" description="Stop Tomcat application"&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;stop url="${tomcat.manager.url}"

&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; username="${tomcat.manager.username}"

&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; password="${tomcat.manager.password}"

&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; path="/${name}"/&gt;

&nbsp; &nbsp; &lt;/target&gt;



&nbsp; &nbsp; &lt;target name="list" description="List Tomcat applications"&gt;

&nbsp; &nbsp; &nbsp; &nbsp; &lt;list url="${tomcat.manager.url}"

&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; username="${tomcat.manager.username}"

&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; password="${tomcat.manager.password}"/&gt;

&nbsp; &nbsp; &lt;/target&gt;



&lt;!-- End Tomcat tasks --&gt;



&lt;/project&gt;








Se você estiver utilizando um servidor de aplicação web diferente, poderá
remover as tarefas específicas do Tomcat no final do script. Você terá que
confiar no recurso de hot deploy do servidor ou parar e iniciar a aplicação
manualmente.







Se você estiver usando uma IDE poderá encontrar erros relatados pela IDE no
‘build.xml’, como os targets do Tomcat. Você pode ignorá-los. A listagem de
arquivos acima está correta.







O script de construção Ant acima contém todas as targets que vamos precisar
para reduzir nossos esforços de desenvolvimento. &nbsp;Não explicaremos o script em detalhe. Você
pode copiar este código e colar em um novo arquivo chamado ‘build.xml‘ na raiz
de sua árvore de diretórios. Precisamos também de um arquivo ‘build.properties‘
que deverá ser personalizado de acordo com a instalação do servidor. Este
arquivo deve estar no mesmo diretório do ‘build.xml’. No exemplo abaixo
coloquei o caminho de instalação do Tomcat no meu computador.









'springapp/build.properties':

# Ant properties for building the
springapp



appserver.home=${user.home}/Desenvolvimento/Servidores/apache-tomcat-6.0.35

# for Tomcat 5 use
$appserver.home}/server/lib

# for Tomcat 6 use
$appserver.home}/lib

appserver.lib=${appserver.home}/lib



deploy.path=${appserver.home}/webapps



tomcat.manager.url=http://localhost:8080/manager

tomcat.manager.username=tomcat

tomcat.manager.password=s3cret



Se estiver em um sistema onde você não é o proprietário&nbsp; (owner) da instalação do Tomcat, então o
proprietário deve conceder-lhe acesso total à pasta ‘webapps’ ou o deve criar
uma nova pasta chamada ‘springapp’ na pasta “webapps“ da instalação do Tomcat e
dar-lhe plenos direitos de acesso. No linux execute o commando ‘chmod a+rwx
springapp‘ para dar plenos direitos à pasta ‘springapp‘.



Para criar um usuário chamado ‘tomcat’ com senha ‘s3cret’,
adicione a entrada abaixo no arquivo 'appserver.home/conf/tomcat-users.xml'.



&lt;tomcat-users&gt; 
&nbsp; &lt;role rolename="manager"&gt; 
&nbsp; &lt;user password="s3cret" roles="manager" username="tomcat"&gt;
&lt;/user&gt;&lt;/role&gt;&lt;/tomcat-users&gt;

Agora execute o ant para certificar-se de que tudo está ok. Abra o
terminal (ou prompt), entre na pasta ‘springapp’ e execute ‘ant’.














A
última coisa que precisamos fazer é criar e implantar o aplicativo. Para isto
basta executar o ‘Ant’ especificando ‘deploy’ ou ‘deploywar’.










1.4.&nbsp;Verificar se a aplicação está
funcionando

Inicie o Tomcat executando&nbsp;'${appserver.home}/bin/startup.bat' (ou ‘sh startup.sh’).
Para ter a certeza de
que a aplicação está funcionando execute o comando ‘ant list’.




























Agora abra um browser
e navegue até a página inicial de nossa aplicação através da seguinte URL: http://localhost:8080/springapp/index.jsp.







A
página da aplicação










1.5.&nbsp;Download do
Spring Framework


Se você não fez o download do Spring Framework, agora é a hora de fazê-lo. Para
este tutorial utilizamos o ‘Spring Framework 2.5’ que pode ser baixado
gratuitamente em http://s3.amazonaws.com/dist.springframework.org/release/SPR/spring-framework-2.5-with-dependencies.zip.
Descompacte o arquivo. 



Para completar a instalação é necessário configurar o ambiente. Agora
podemos realmente desenvolver o nosso aplicativo Spring Framework MVC.





























1.6.&nbsp;Modificando o
arquivo'web.xml'&nbsp;na
pasta&nbsp;'WEB-INF'






















Entre na pasta&nbsp;'springapp/war/WEB-INF'.
Modifique o arquivo&nbsp;'web.xml'&nbsp;que
criamos anteriormente. Vamos definir DispatcherServlet&nbsp;(também
conhecido como&nbsp;'Front Controller'. &nbsp;Esta definição servlet também tem uma entrada&nbsp;&lt;servlet-mapping/&gt;&nbsp;que faz mapeamento dos padrões de URL que iremos utilizar. Decidimos deixar qualquer URL com a extensão&nbsp;'.htm' ser encaminhada para o servlet&nbsp;'springapp'&nbsp;(o&nbsp;DispatcherServlet).

























'springapp/war/WEB-INF/web.xml':

&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;web-app version="2.4"
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; xmlns="http://java.sun.com/xml/ns/j2ee" 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" &gt;
&nbsp; &lt;servlet&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;servlet-name&gt;springapp&lt;/servlet-name&gt;&nbsp;&nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;&nbsp;&nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;&nbsp;&nbsp; 
&nbsp;&nbsp;&lt;/servlet&gt;&nbsp;&nbsp;&nbsp; 
&nbsp;
&nbsp; &lt;servlet-mapping&gt;&nbsp;&nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;servlet-name&gt;springapp&lt;/servlet-name&gt;&nbsp;&nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;url-pattern&gt;*.htm&lt;/url-pattern&gt;&nbsp;&nbsp; 
&nbsp;&nbsp;&lt;/servlet-mapping&gt; &nbsp;&nbsp;&nbsp;
&nbsp;
&nbsp; &lt;welcome-file-list&gt;&nbsp;&nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;welcome-file&gt;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; index.jsp
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/welcome-file&gt;
&nbsp; &lt;/welcome-file-list&gt;&nbsp; 
&nbsp;
&lt;/web-app&gt;




Criaremos um arquivo chamado &nbsp;'springapp-servlet.xml'&nbsp;na
pasta&nbsp;'springapp/war/WEB-INF'.
Este arquivo contém a definição do bean usado pelo DispatcherServlet. É no&nbsp;WebApplicationContext&nbsp;onde todos os componentes web são
relacionados. O nome deste arquivo é determinado pelo valor do elemento&nbsp;&lt;servlet-name/&gt; do arquivo 'web.xml'. Esta é a
convenção de nomenclatura padrão usado pelo Spring's Web MVC framework. Agora,
adicione uma entrada bean chamada&nbsp;'/hello.htm'&nbsp;e
especifique a classe springapp.web.HelloController. Isso define o controlador que o aplicativo irá utilizar para atender a
uma solicitação com o mapeamento URL igual a '/hello.htm'. O &nbsp;Spring Web MVC framework usa uma implementação
de classe chamada&nbsp;HandlerMapping&nbsp;para
definir o mapeamento entre a URL requisitada e o objeto que vai lidar com esta
requisição. Ao contrário do&nbsp;DispatcherServlet,
o&nbsp;HelloController&nbsp;é responsável pelo tratamento de uma requisição para uma página específica
do site e é conhecido como um 'Page Controller'. O padrão HandlerMapping&nbsp;que
o DispatcherServlet&nbsp;usa
é o&nbsp;BeanNameUrlHandlerMapping; esta classe vai
utilizar o nome do bean para mapear a URL na requisição para que o DispatcherServlet&nbsp;saiba
qual controlador deve ser invocado para lidar com URLs diferentes.


'springapp/war/WEB-INF/springapp-servlet.xml':

&lt;?xml version="1.0" encoding="UTF-8"?&gt;&nbsp; 
&lt;beans xmlns="http://www.springframework.org/schema/beans"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; xsi:schemaLocation="http://www.springframework.org/schema/beans&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"&gt;&nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&lt;!-- the application context definition for the springapp DispatcherServlet --&gt;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&lt;bean name="/hello.htm" class="springapp.web.HelloController"/&gt;&nbsp; 
&lt;/beans&gt;






&nbsp;





1.7.&nbsp;Copiando
bibliotecas para&nbsp;'WEB-INF/lib'

Primeiro crie a pasta 'lib'&nbsp;dentro
de&nbsp;'war/WEB-INF'. Copie o arquivo&nbsp;spring.jar&nbsp;(de spring-framework-2.5/dist) e spring-webmvc.jar&nbsp;(de&nbsp;spring-framework-2.5/dist/modules)
para a pasta criada&nbsp;'war/WEB-INF/lib'.
Copie também commons-logging.jar&nbsp;(de&nbsp;spring-framework-2.5/lib/jakarta-commons)
para 'war/WEB-INF/lib'. Estes arquivos serão implantados no servidor e serão usados no processo
de compilação.







1.8.&nbsp;Criando
o&nbsp;Controller

Criando a classe Controller – o nome da classe será&nbsp;HelloController,
e será definida no pacote&nbsp;'springapp.web'.
Primeiro crie o pacote e depois&nbsp;o
arquivo 'HelloController.java'&nbsp;gravando-o
na pasta 'src/springapp/web'.

'springapp/src/springapp/web/HelloController.java':

package springapp.web;



import org.springframework.web.servlet.mvc.Controller;

import org.springframework.web.servlet.ModelAndView;



import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;



import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;



import java.io.IOException;



public class HelloController implements Controller {



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



&nbsp;&nbsp;&nbsp;
public ModelAndView
handleRequest(HttpServletRequest request, HttpServletResponse
response)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; throws ServletException, IOException {



&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
logger.info("Returning hello view");



&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
return new ModelAndView("hello.jsp");

&nbsp;&nbsp;&nbsp;
}

}

Esta é uma implementação de Controller&nbsp;básica. Estaremos expandindo este mais tarde, bem como aplicar algumas das implementações de base do controller fornecidos pelo Spring. Em Spring Web MVC, o&nbsp;Controller processa o pedido e retorna ao&nbsp;aModelAndView &nbsp;- neste caso, um chamado&nbsp;'hello.jsp'&nbsp;que é também o nome do arquivo JSP. O modelo que esta classe retorna é efetivamente resolvido através de um&nbsp;ViewResolver. Uma vez que não fora explicitamente definido um&nbsp;ViewResolver, vai ser dado um padrão de Spring que simplesmente encaminha a URL correspondente ao nome da visão especificada. We will modify this later on. Temos que especificar um log. Usando Tomcat, as mensagens de log sõão encontradas no arquivo&nbsp;'catalina.out'&nbsp;que está localizado em'${appserver.home}/log'.



Se você estiver usando uma IDE, você vai querer configurar o caminho de construção do seu projeto, adicionando os jars na pasta 'lib'. Você também vai querer adicionar&nbsp;servlet-api.jar&nbsp;do seu servlet container da pasta&nbsp;'lib'&nbsp;('${appserver.lib}'). Adicionando estes no seu caminho de construção deve resolver com êxito todas as declarações de importação do arquivo&nbsp;'HelloController.java'.


























1.9.&nbsp;Escrevendo o teste para seu&nbsp;Controller


O teste é uma parte vital do desenvolvimento de software. É também uma prática fundamental do desenvolvimento ágil. Descobrimos que o melhor momento para escrever testes é durante o desenvolvimento, não depois, por isso mesmo que nosso controller não tenha uma lógica complexa, iremos escrever o teste. Isso nos permitirá fazer alterações nele no futuro com confiança. Vamos criar uma nova pasta em&nbsp;'springapp'&nbsp;chamada&nbsp;'test'.&nbsp;Este é a estrutura onde todos nossos testes vão estar, sendo um espelhamento da árvore &nbsp;'springapp/src'.




Crie a classe de teste chamada&nbsp;'HelloControllerTests'&nbsp;estendendo de JUnit's classe de teste&nbsp;TestCase. É um teste de unidade que verifica se o nome da view retornado por&nbsp;handleRequest()&nbsp;corresponde ao nome da view esperada:&nbsp;'hello.jsp'.


'springapp/test/springapp/web/HelloControllerTests.java':

package springapp.web;



import org.springframework.web.servlet.ModelAndView;



import springapp.web.HelloController;



import junit.framework.TestCase;



public class HelloControllerTests extends TestCase {



&nbsp;&nbsp;&nbsp;
public void testHandleRequestView() throws Exception{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
HelloController controller = new HelloController();

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
ModelAndView modelAndView = controller.handleRequest(null, null);&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
assertEquals("hello.jsp", modelAndView.getViewName());

&nbsp;&nbsp;&nbsp;
}

}




Para executar o teste (e todos os testes que vamos escrever), precisamos adicionar uma tarefa de teste no nosso script Ant&nbsp;'build.xml'.
Primeiro, copie&nbsp;junit-3.8.2.jar&nbsp;de&nbsp;'spring-framework-2.5/lib/junit'&nbsp;para&nbsp;'war/WEB-INF/lib'. Em vez de criar uma única tarefa para compilar os testes e depois executá-los, vamos dividí-las em duas tarefas distintas: 'buildtests' e 'tests' que depende dos 'buildtests'.




Se você estiver usando uma IDE, você pode querer executar os testes de dentro da sua IDE. Configure o caminho de construção do seu projeto, adicionando o&nbsp;junit-3.8.2.jar.


'springapp/build.xml':

&lt;?xml version="1.0"?&gt;



&lt;project name="springapp" basedir="." default="usage"&gt;

&nbsp;&nbsp;&nbsp;
&lt;property file="build.properties"/&gt;



&nbsp;&nbsp;&nbsp;
&lt;property name="src.dir" value="src"/&gt;

&nbsp;&nbsp;&nbsp;
&lt;property name="web.dir" value="war"/&gt;

&nbsp;&nbsp;&nbsp;
&lt;property name="build.dir" value="${web.dir}/WEB-INF/classes"/&gt;

&nbsp;&nbsp;&nbsp;
&lt;property name="name" value="springapp"/&gt;

&nbsp;&nbsp;&nbsp;&nbsp; &lt;property
name="test.dir" value="test"/&gt;



&nbsp;&nbsp;&nbsp;
&lt;path id="master-classpath"&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;fileset dir="${web.dir}/WEB-INF/lib"&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;include name="*.jar"/&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;/fileset&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;!-- We need the servlet API classes: --&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;!--&nbsp; * for
Tomcat 5/6 use servlet-api.jar --&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;!--&nbsp; * for other
app servers - check the docs --&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;fileset dir="${appserver.lib}"&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;include name="servlet*.jar"/&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;/fileset&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;pathelement path="${build.dir}"/&gt;

&nbsp;&nbsp;&nbsp;
&lt;/path&gt;



&nbsp;&nbsp;&nbsp;
&lt;target name="usage"&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;echo message=""/&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;echo message="${name} build file"/&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;echo message="-----------------------------------"/&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;echo message=""/&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;echo message="Available targets are:"/&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;echo message=""/&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;echo message="build&nbsp;&nbsp;&nbsp;&nbsp; --&gt; Build
the application"/&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;echo message="deploy&nbsp;&nbsp;&nbsp; --&gt;
Deploy application as directory"/&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;echo message="deploywar --&gt; Deploy application as a WAR file"/&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;echo message="install&nbsp;&nbsp; --&gt;
Install application in Tomcat"/&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;echo message="reload&nbsp;&nbsp;&nbsp; --&gt;
Reload application in Tomcat"/&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;echo message="start&nbsp;&nbsp;&nbsp;&nbsp; --&gt; Start
Tomcat application"/&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;echo message="stop&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; --&gt; Stop
Tomcat application"/&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;echo message="list&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; --&gt; List
Tomcat applications"/&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;echo message=""/&gt;

&nbsp;&nbsp;&nbsp;
&lt;/target&gt;



&nbsp;&nbsp;&nbsp;
&lt;target name="build" description="Compile main source tree java files"&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;mkdir dir="${build.dir}"/&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;javac destdir="${build.dir}" source="1.5" target="1.5" debug="true"

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; deprecation="false" optimize="false" failonerror="true" includeantruntime="false"&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;src path="${src.dir}"/&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;classpath refid="master-classpath"/&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;/javac&gt;

&nbsp;&nbsp;&nbsp;
&lt;/target&gt;



&nbsp;&nbsp;&nbsp;
&lt;target name="deploy" depends="build" description="Deploy application"&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;copy todir="${deploy.path}/${name}" preservelastmodified="true"&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;fileset dir="${web.dir}"&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;include name="**/*.*"/&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/fileset&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;/copy&gt;

&nbsp;&nbsp;&nbsp;
&lt;/target&gt;



&nbsp;&nbsp;&nbsp;
&lt;target name="deploywar" depends="build" description="Deploy application as a WAR file"&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;war destfile="${name}.war"

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; webxml="${web.dir}/WEB-INF/web.xml"&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;fileset dir="${web.dir}"&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;include name="**/*.*"/&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/fileset&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;/war&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;copy todir="${deploy.path}" preservelastmodified="true"&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;fileset dir="."&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;include name="*.war"/&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/fileset&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;/copy&gt;

&nbsp;&nbsp;&nbsp;
&lt;/target&gt;

&nbsp;&nbsp;&nbsp;


&nbsp;&nbsp;&nbsp;&nbsp; &lt;target name="buildtests" description="Compile test tree java
files"&gt;

&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;mkdir dir="${build.dir}"/&gt;

&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;javac destdir="${build.dir}" source="1.5" target="1.5" debug="true"

&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; deprecation="false" optimize="false" failonerror="true"&gt;

&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;src path="${test.dir}"/&gt;

&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;classpath refid="master-classpath"/&gt;

&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/javac&gt;

&nbsp;&nbsp;&nbsp;&nbsp; &lt;/target&gt;

&nbsp;&nbsp;&nbsp;&nbsp; 

&nbsp;&nbsp;&nbsp;&nbsp; &lt;target name="tests" depends="build, buildtests" description="Run tests"&gt;

&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;junit printsummary="on"

&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; fork="false"

&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; haltonfailure="false"

&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; failureproperty="tests.failed"

&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; showoutput="true"&gt;

&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;classpath refid="master-classpath"/&gt;

&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;formatter type="brief" usefile="false"/&gt;

&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 

&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;batchtest&gt;

&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;fileset dir="${build.dir}"&gt;

&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;include name="**/*Tests.*"/&gt;

&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/fileset&gt;

&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/batchtest&gt;

&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 

&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/junit&gt;

&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 

&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;fail if="tests.failed"&gt;

&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; tests.failed=${tests.failed}

&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
***********************************************************

&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ***********************************************************

&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ****&nbsp; One or more tests failed!&nbsp; Check the output ...&nbsp; ****

&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
***********************************************************

&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
***********************************************************

&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/fail&gt;

&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &lt;/target&gt;

&nbsp;&nbsp;&nbsp;&nbsp; 

&lt;!--
============================================================== --&gt;

&lt;!-- Tomcat tasks - remove these
if you don't have Tomcat installed --&gt;

&lt;!--
============================================================== --&gt;



&nbsp;&nbsp;&nbsp;
&lt;path id="catalina-ant-classpath"&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;!-- We need the Catalina jars for Tomcat --&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;!--&nbsp; * for other
app servers - check the docs --&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;fileset dir="${appserver.lib}"&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;include name="catalina-ant.jar"/&gt;

&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/fileset&gt;

&nbsp;&nbsp;&nbsp;
&lt;/path&gt;



&nbsp;&nbsp;&nbsp;
&lt;taskdef name="install" classname="org.apache.catalina.ant.InstallTask"&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;classpath refid="catalina-ant-classpath"/&gt;

&nbsp;&nbsp;&nbsp;
&lt;/taskdef&gt;

&nbsp;&nbsp;&nbsp;
&lt;taskdef name="reload" classname="org.apache.catalina.ant.ReloadTask"&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;classpath refid="catalina-ant-classpath"/&gt;

&nbsp;&nbsp;&nbsp;
&lt;/taskdef&gt;

&nbsp;&nbsp;&nbsp;
&lt;taskdef name="list" classname="org.apache.catalina.ant.ListTask"&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;classpath refid="catalina-ant-classpath"/&gt;

&nbsp;&nbsp;&nbsp;
&lt;/taskdef&gt;

&nbsp;&nbsp;&nbsp;
&lt;taskdef name="start" classname="org.apache.catalina.ant.StartTask"&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;classpath refid="catalina-ant-classpath"/&gt;

&nbsp;&nbsp;&nbsp;
&lt;/taskdef&gt;

&nbsp;&nbsp;&nbsp;
&lt;taskdef name="stop" classname="org.apache.catalina.ant.StopTask"&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;classpath refid="catalina-ant-classpath"/&gt;

&nbsp;&nbsp;&nbsp;
&lt;/taskdef&gt;



&nbsp;&nbsp;&nbsp;
&lt;target name="install" description="Install application in
Tomcat"&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;install url="${tomcat.manager.url}"

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; username="${tomcat.manager.username}"

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; password="${tomcat.manager.password}"

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; path="/${name}"

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; war="${name}"/&gt;

&nbsp;&nbsp;&nbsp;
&lt;/target&gt;



&nbsp;&nbsp;&nbsp;
&lt;target name="reload" description="Reload application in Tomcat"&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;reload url="${tomcat.manager.url}"

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; username="${tomcat.manager.username}"

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; password="${tomcat.manager.password}"

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;path="/${name}"/&gt;

&nbsp;&nbsp;&nbsp;
&lt;/target&gt;



&nbsp;&nbsp;&nbsp;
&lt;target name="start" description="Start Tomcat application"&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;start url="${tomcat.manager.url}"

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; username="${tomcat.manager.username}"

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; password="${tomcat.manager.password}"

&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;path="/${name}"/&gt;

&nbsp;&nbsp;&nbsp;
&lt;/target&gt;



&nbsp;&nbsp;&nbsp;
&lt;target name="stop" description="Stop Tomcat application"&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;stop url="${tomcat.manager.url}"

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; username="${tomcat.manager.username}"

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; password="${tomcat.manager.password}"

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; path="/${name}"/&gt;

&nbsp;&nbsp;&nbsp;
&lt;/target&gt;



&nbsp;&nbsp;&nbsp;
&lt;target name="list" description="List Tomcat applications"&gt;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&lt;list url="${tomcat.manager.url}"

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; username="${tomcat.manager.username}"

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; password="${tomcat.manager.password}"/&gt;

&nbsp;&nbsp;&nbsp;
&lt;/target&gt;



&lt;!-- End Tomcat tasks --&gt;



&lt;/project&gt;

Agora execute a tarefa&nbsp;'tests'&nbsp;Ant e o teste deve passar.


$ ant tests
Buildfile: build.xml

build:

buildtests:
    [javac] Compiling 1 source file to /Users/Shared/Projects/springapp/war/WEB-INF/classes

tests:
    [junit] Running springapp.web.HelloWorldControllerTests
    [junit] Oct 30, 2007 11:31:43 PM springapp.web.HelloController handleRequest
    [junit] INFO: Returning hello view
    [junit] Tests run: 1, Failures: 0, Errors: 0, Time elapsed: 0.03 sec
    [junit] Testsuite: springapp.web.HelloWorldControllerTests
    [junit] Tests run: 1, Failures: 0, Errors: 0, Time elapsed: 0.03 sec

    [junit] ------------- Standard Error -----------------
    [junit] Oct 30, 2007 11:31:43 PM springapp.web.HelloController handleRequest
    [junit] INFO: Returning hello view
    [junit] ------------- ---------------- ---------------

BUILD SUCCESSFUL
Total time: 2 seconds




Uma das&nbsp;melhores práticas de&nbsp;desenvolvimento ágil&nbsp;é a
Integração Contínua.&nbsp;É&nbsp;uma boa idéia&nbsp;para garantir que
seus&nbsp;testes são executados em&nbsp;cada compilação de modo&nbsp;que você
sabe que&nbsp;a lógica do aplicativo&nbsp;está se comportando como
esperado&nbsp;com a evolução do código.








1.10.&nbsp;Criando
a&nbsp;View

Agora é a hora de criar sua primeira view. 

Now it is time to create our first view. Como foi mencionado anteriormente,
estamos encaminhando para uma página JSP chamada&nbsp;'hello.jsp'. Para começar vamos
colocá-lo na pasta 'war'.

'springapp/war/hello.jsp':

&lt;html&gt;

&lt;head&gt;

&lt;title&gt;Hello :: Spring Application&lt;/title&gt;

&lt;/head&gt;

&lt;body&gt;

&nbsp;&nbsp;&nbsp;&nbsp; &lt;h1&gt;Hello - Spring Application&lt;/h1&gt;

&nbsp;&nbsp;&nbsp;&nbsp; &lt;p&gt;Greetings.&lt;/p&gt;

&lt;/body&gt;




&lt;/html&gt;




&nbsp;




&nbsp;




1.11.&nbsp;Compilando e
distribuindo a aplicação

Execute&nbsp;a target 'deploy' do Ant&nbsp;(que invoca a target ‘build’), e, em seguida,
execute ‘reload’ que estão configurados no arquivo 'build.xml'.
Isto irá forçar uma compilação e recarregar a aplicação no Tomcat. Temos que
verificar a saída do Ant e os logs do Tomcat para possíveis erros na
implantação, tais como erros de digitação nos arquivos criados ou classes
ausentes nos arquivos JAR.

Aqui está um exemplo de saída do build Ant:

$ ant deploy reload 
Buildfile: build.xml&nbsp; 
&nbsp;
build:&nbsp;&nbsp;&nbsp;&nbsp; 
&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [mkdir] Created dir: /Users/trisberg/Projects/springapp/war/WEB-INF/classes&nbsp;&nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [javac] Compiling 1 source file to /Users/trisberg/Projects/springapp/war/WEB-INF/classes&nbsp; 
&nbsp;
deploy:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [copy] Copying 7 files to /Users/trisberg/apache-tomcat-5.5.17/webapps/springapp&nbsp; 
&nbsp;
BUILD SUCCESSFUL 
Total time: 3 seconds 
$ ant reload 
Buildfile: build.xml&nbsp; 
&nbsp;
reload:&nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [reload] OK - Reloaded application at context path /springapp&nbsp; 
&nbsp;
BUILD SUCCESSFUL 
Total time: 2 seconds


E aqui está um trecho do arquivo de log do Tomcat&nbsp;'catalina.out'.

Oct 30, 2007 11:43:09 PM org.springframework.web.servlet.FrameworkServlet initServletBean&nbsp;
INFO: FrameworkServlet 'springapp': initialization started&nbsp;
Oct 30, 2007 11:43:09 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh&nbsp;
INFO: Refreshing org.springframework.web.context.support.XmlWebApplicationContext@6576d5: display name&nbsp; [WebApplicationContext for namespace 'springapp-servlet']; startup date [Tue Oct 30 23:43:09 GMT 2007];&nbsp;&nbsp;
...&nbsp;
...&nbsp;
Oct 30, 2007 11:43:09 PM org.springframework.web.servlet.FrameworkServlet initServletBean&nbsp;
INFO: FrameworkServlet 'springapp': initialization completed in 150 ms









1.12.&nbsp;Execute o aplicativo

Vamos testar a nova versão.

Abra o seguinte link no seu navegador:&nbsp;http://localhost:8080/springapp/hello.htm.














1.13.&nbsp;Summary

Vamos verificar as partes de nosso aplicativo que criamos até agora.

·&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Página de introdução,&nbsp;'index.jsp', A página de boas-vindas da aplicação. Ela foi utilizada para testar se nossa configuração está correta. Vamos mudar isto mais tarde para realmente fornecer um link para nossa aplicação.

·&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; O&nbsp;DispatcherServlet&nbsp;(front controller) com o correspondente arquivo de configuração&nbsp;'springapp-servlet.xml'.

·&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Um controlador de página,&nbsp;HelloController, com funcionalidade limitada – ele somente retorna um&nbsp;ModelAndView. Atualmente temos um modelo vazio, iremos fornecer um modelo completo mais tarde.

·&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; A classe de teste unitário do controlador de página,&nbsp;HelloControllerTests, para verificar se o nome da view é o que esperamos.

·&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Uma view,&nbsp;'hello.jsp', Que é extremamente básica. A boa notícia é que fizemos todas configurações e agora estamos prontos para adionar mais funcionalidades.

Segue abaixo uma captura de tela da estrutura de pastes de como seu projeto deve estar neste ponto.






Publicado em:&nbsp;http://static.springsource.org/docs/Spring-MVC-step-by-step/part1.html

Evaldo Wolkers.