JAVA + Spring + Netbeans 7.2 - Mysql + Hibernate 3 + CRUD + Struts 2 Lesson 09
Autor: Mario Cezzare Angelicola Chiodi | Publicado: 2012-10-03T14:17:00-07:00




 

 

 

 

 

 

 

 

 

 

 

 

 

 

 
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/current/scripts/clipboard.swf';
SyntaxHighlighter.all();
 
Dando&nbsp;seqüência&nbsp;nos posts de JAVA + Spring, agora vou apresentar o Framework Apache Struts&nbsp;em sua versão 2.

(ainda não pus a legenda das imagens&nbsp;)
Requisitos :
-&nbsp;Netbeans 7.2
-&nbsp;spring-3.2.0.M2&nbsp;-- link direto
- estar com o banco mysql springlessons, e a tabela contato criada.
- Struts 2

- Lib XStream , para manipular arquivos XML .

- Ter lido :


Posts Anteriores :&nbsp;

JSNBTut - Base&nbsp;&nbsp;que é uma preparação do ambiente para o desenvolvimento

Opcionais :&nbsp;

JSNBTut - Lesson 01&nbsp;- introdução ao Spring
JSNBTut - Lesson 02&nbsp;-&nbsp;introdução ao gerenciamento de dependências no &nbsp;Spring
JSNBTut - Lesson 03&nbsp;- acessando banco de dados Mysql com beans e injeção de dependências
JSNBTut - Lesson 04&nbsp;-&nbsp;outro jeito rápido de utilizar o Spring e Mysql sem utilizar Arquivos XML.
JSNBTut - Lesson 05&nbsp;-&nbsp;comparação entre as implementações e introdução ao Swing. Jtable + DefaultTableModel e implementação de uma TableModel, ...
JSNBTut - Lesson 06&nbsp;- implementando um CRUD ao exemplo , que é o projeto que continua da lição 5.
JSNBTut - Lesson 07- Finalizando o &nbsp;CRUD completo em Java &nbsp; utilizando&nbsp;Swing e&nbsp;&nbsp;Spring-&nbsp;Implementamos um validador com&nbsp;org.springframework.validation.Validator-&nbsp;Implementamos um Tema- Vimos como importar /exportar arquivos XML usando XStream- Aprendemos a usar Anotações- Implementamos um SplashScreen- Aprendemos a distribuir nossa aplicação e customizar o&nbsp;build&nbsp;do projeto no build.xml

JSNBTut - Lesson 08
- Organização de projetos WEB
- Implementar o Struts 1.3.10
- Criamos uma interface contatoDAO
- implementamos a interface com a classe ContatoDaoImpl
- criamos uma interface de Serviço ContatoService
- implementamos a interface &nbsp;com a classe ContatoServiceImpl
- Criamos as classes p/ atender os actions que são mapeados no arquivo struts-config.xml, que extendem a classe org.apache.struts.action.Action
- Definimos as actions e mappings no arquivo struts-config.xml
- criamos uma view através de um arquivo index.jsp
- Criamos uma vier p/ mostrar os erros
- Integramos o Spring 3 com o Struts 2
- Definimos nossos beans no arquivo &nbsp;action-servlet.xml
- Vimos nos logs a ordem em que as classes são instanciadas e como localizar erros
- Compartilhamos a conexão através de uma classe ConexaoMysql

Este é o 9º da série , o objetivo deste post é implementar o programa 
que terminamos na lição 07 na web utilizando &nbsp;o framework 
Struts 2 , e depois integraremos com o Spring 3 e o Hibernate 3, passando o controle da app p/ o Spring.
Os arquivos dos 2 projetos finalizados nesse Post estão ao final das explicações ou no final deste Post:

Nesta lição , eu procurei capturar quase todos os passos em telas, pois nada como a referência de cada framework ou componente p/ explicar sua utilização, o que mostro aqui é um jeito de implementar.


Adiantando, &nbsp;algumas coisas que faremos ?

- Aprenderemos a conectar no Mysql pelo NB e armazenar um driver
- Aprenderemos a utilizar e configurar o Hibernate pelo NB
- Aprenderemos a fazer a engenharia reversa das tabelas do banco para as configurações do Hibernate gerando os arquivos de para os mappings: Hibernate Mapping
na versão V1:


- Introduziremos o &nbsp;Full Hibernate Plugin's Session Factory

- Introduziremos&nbsp;o conceito de BO (Business Objects)


- Utilizar os recursos de Injeção de dependências do Spring:
- Deixaremos a app apenas (pode ser que sobre alguma) com as libs necessárias no final do Projeto.




Nesta lição adicionei o campo email:
Lembrando a estrutura da nossa tabela do mysql


Figura 01 - Tabela Contato





CREATE  TABLE IF NOT EXISTS `springlessons`.`contato` (
  `id` INT(11) NOT NULL AUTO_INCREMENT ,
  `nome` VARCHAR(45) NULL DEFAULT NULL ,
  `telefone` VARCHAR(45) NULL DEFAULT NULL ,
  `email` VARCHAR(45) NULL DEFAULT NULL ,
  PRIMARY KEY (`id`) )
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci





Let's Go.

&nbsp;1) Obtendo as Libs

Não consegui utilizar as libs adicionadas ao projeto pelo NB. Portanto vamos adicionar algumas manualmente , e depois organizar.


LIBS:
Struts 2:
-antlr-2.7.6.jar
-commons-collections-3.1.jar
-commons-fileupload-1.2.1.jar
-commons-io-1.3.2.jar
-commons-lang-2.3.jar
-commons-logging-1.1.jar
-freemarker-2.3.13.jar
-javassist-3.9.0.GA.jar
-ognl-2.6.11.jar
-struts2-convention-plugin-2.1.6.jar
-struts2-core-2.1.6.jar
-struts2-fullhibernatecore-plugin-1.4-GA.jar
-xwork-2.1.2.jar
Hibernate 3
-ejb3-persistence.jar

-hibernate-annotations.jar
-hibernate-commons-annotations.jar
-hibernate-validator.jar
-hibernate3.jar
-jta-1.1.jar


Dom4j
-dom4j-1.6.1.jar

apache-log4j-1.2.17
-log4j-1.2.15.jar

slf4j-1.7.1

-slf4j-api-1.5.8.jar
-slf4j-log4j12-1.5.8.jar





jUnit

-junit-3.8.1.jar


2) Iniciando o Projeto



Figura 02 - Nova WebApp





Figura 03 - Nova WebApp / Setup



Não adicione nenhum Framework, vamos adicionar depois :



Figura 04- Sem Frameworks




Figura 05 - Lista das libs utilizadas




2)-Adicionando a conexão do mysql ao NB



Figura 06 - Conectando o NB ao Mysql&nbsp;




Figura 07 - Conectando o NB ao Mysql&nbsp;




Figura 08 - Conectando o NB ao Mysql&nbsp;- novo driver




Figura 09 - Conectando o NB ao Mysql&nbsp;- Teste de conexão




Figura 10 - Driver disponíveis




3)-Criando o arquivo de configuração do Hibernate pelo NB
Isso criará o arquivo hibernate.cfg.xml


Figura 11 - Gerando o arquivo hibernate.cfg.xml




Figura 12 - Gerando o arquivo hibernate.cfg.xml pelo Wizard




Figura 13-confirme o nome &nbsp;do arquivo hibernate.cfg.xml




Figura 14-Escolha a conexão




Figura 15- Arquivo gerado&nbsp;hibernate.cfg.xml




Figura 16 - configurando a engenharia reversa das tabelas





Figura 17-confirme o nome &nbsp;do arquivo hibernate.revenge.xml







Figura 18-escolha as tabelas p/ gerar os mappings






Figura 19-Arquivo gerado hibernate.revenge.xml




4)-Fazendo a Engenharia reversa das tabelas do schema e Adicionando o mapeamento aos campos
Isso criará o arquivo hibernate.reveng.xml e os nossos&nbsp;Modelos Contato.java&nbsp;e&nbsp;Usuario.java



Figura 20 - fazendo a engenharia reversa das tabelas






Figura 21 - fazendo a engenharia reversa das tabelas, escolha os arquivos XML criados




Figura 22 -Arquivos gerados







Figura 23 -Arquivo final do hibernate



hibernate.cfg.xml :
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"&gt;
&lt;hibernate-configuration&gt;
  &lt;session-factory&gt;
    &lt;property name="hibernate.dialect"&gt;org.hibernate.dialect.MySQLDialect&lt;/property&gt;
    &lt;property name="hibernate.connection.driver_class"&gt;com.mysql.jdbc.Driver&lt;/property&gt;
    &lt;property name="hibernate.connection.url"&gt;jdbc:mysql://ns1:3306/springlessons?zeroDateTimeBehavior=convertToNull&lt;/property&gt;
    &lt;property name="hibernate.connection.username"&gt;springlessons&lt;/property&gt;
    &lt;property name="hibernate.connection.password"&gt;DHADdSXcDF29WGXy&lt;/property&gt;
    &lt;mapping resource="com/springlesson09/model/Usuario.hbm.xml"/&gt;
    &lt;mapping resource="com/springlesson09/model/Contato.hbm.xml"/&gt;
  &lt;/session-factory&gt;
&lt;/hibernate-configuration&gt;



hibernate.revenge.xml&nbsp;:
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd"&gt;
&lt;hibernate-reverse-engineering&gt;
  &lt;schema-selection match-catalog="springlessons"/&gt;
  &lt;table-filter match-name="contato"/&gt;
  &lt;table-filter match-name="usuario"/&gt;
&lt;/hibernate-reverse-engineering&gt;

Contato.hbm.xml :
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"&gt;
&lt;!-- Generated Oct 1, 2012 11:10:50 PM by Hibernate Tools 3.2.1.GA --&gt;
&lt;hibernate-mapping&gt;
  &lt;class catalog="springlessons" name="com.springlesson09.model.Contato" table="contato"&gt;
    &lt;id name="id" type="java.lang.Integer"&gt;
      &lt;column name="id"/&gt;
      &lt;generator class="identity"/&gt;
    &lt;/id&gt;
    &lt;property name="nome" type="string"&gt;
      &lt;column length="45" name="nome"/&gt;
    &lt;/property&gt;
    &lt;property name="telefone" type="string"&gt;
      &lt;column length="45" name="telefone"/&gt;
    &lt;/property&gt;
    &lt;property name="email" type="string"&gt;
      &lt;column length="45" name="email"/&gt;
    &lt;/property&gt;
  &lt;/class&gt;
&lt;/hibernate-mapping&gt;

Usuario.hbm.xml :
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"&gt;
&lt;!-- Generated Oct 1, 2012 11:10:50 PM by Hibernate Tools 3.2.1.GA --&gt;
&lt;hibernate-mapping&gt;
  &lt;class catalog="springlessons" name="com.springlesson09.model.Usuario" table="usuario"&gt;
    &lt;id name="id" type="java.lang.Integer"&gt;
      &lt;column name="id"/&gt;
      &lt;generator class="identity"/&gt;
    &lt;/id&gt;
    &lt;property name="nome" type="string"&gt;
      &lt;column length="45" name="nome" not-null="true"/&gt;
    &lt;/property&gt;
    &lt;property name="email" type="string"&gt;
      &lt;column length="45" name="email" not-null="true"&gt;
        &lt;comment&gt;licao 09 - WEB&lt;/comment&gt;
      &lt;/column&gt;
    &lt;/property&gt;
    &lt;property name="senha" type="string"&gt;
      &lt;column length="45" name="senha" not-null="true"/&gt;
    &lt;/property&gt;
  &lt;/class&gt;
&lt;/hibernate-mapping&gt;


Usuario.java :
package com.springlesson09.model;
// Generated Oct 1, 2012 11:10:44 PM by Hibernate Tools 3.2.1.GA
/**
 * Usuario generated by hbm2java
 */
public class Usuario  implements java.io.Serializable {


     private Integer id;
     private String nome;
     private String email;
     private String senha;

    public Usuario() {
    }

    public Usuario(String nome, String email, String senha) {
       this.nome = nome;
       this.email = email;
       this.senha = senha;
    }
   
    public Integer getId() {
        return this.id;
    }
    
    public void setId(Integer id) {
        this.id = id;
    }
    public String getNome() {
        return this.nome;
    }
    
    public void setNome(String nome) {
        this.nome = nome;
    }
    public String getEmail() {
        return this.email;
    }
    
    public void setEmail(String email) {
        this.email = email;
    }
    public String getSenha() {
        return this.senha;
    }
    
    public void setSenha(String senha) {
        this.senha = senha;
    }

}




Contato.java :
package com.springlesson09.model;
// Generated Oct 1, 2012 11:10:44 PM by Hibernate Tools 3.2.1.GA
/**
 * Contato generated by hbm2java
 */
public class Contato  implements java.io.Serializable {


     private Integer id;
     private String nome;
     private String telefone;
     private String email;

    public Contato() {
    }

    public Contato(String nome, String telefone, String email) {
       this.nome = nome;
       this.telefone = telefone;
       this.email = email;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }
   
   
    public String getNome() {
        return this.nome;
    }
    
    public void setNome(String nome) {
        this.nome = nome;
    }
    public String getTelefone() {
        return this.telefone;
    }
    
    public void setTelefone(String telefone) {
        this.telefone = telefone;
    }
    public String getEmail() {
        return this.email;
    }
    
    public void setEmail(String email) {
        this.email = email;
    }
}







5)-Criando uma interface DAO



Figura 24 - Criando uma interface





Figura 25 - Criando uma interface ContatoDAO




ContatoDAO.java
package com.springlesson09.dao;

import com.springlesson09.model.Contato;
import java.util.List;


public interface ContatoDAO {

public void saveOrUpdateContato(Contato contato);
 public List&lt;Contato&gt; listContato();
 public Contato listContatoById(Integer contatoId);
 public void deleteContato(Integer contatoId);
    
}


6) Criando a implementação do DAO




Figura 26 - Implementando uma interface






Figura 27- Implementando uma interface, aproveite o NB


ContatoDAOImpl.java
package com.springlesson09.dao;

import com.googlecode.s2hibernate.struts2.plugin.annotations.SessionTarget;
import com.googlecode.s2hibernate.struts2.plugin.annotations.TransactionTarget;
import com.springlesson09.model.Contato;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;


public class ContatoDAOImpl implements ContatoDAO {

    @SessionTarget
    Session session;
    @TransactionTarget
    Transaction transaction;

    /**
     *
     * @param contato
     */
    @Override
    public void saveOrUpdateContato(Contato contato) {
//        throw new UnsupportedOperationException("Not supported yet.");
        try {
            session.saveOrUpdate(contato);
        } catch (Exception e) {
            transaction.rollback();
            e.printStackTrace();
        }
    }
    /**
     *
     * @return
     */
    @SuppressWarnings("unchecked")
    @Override
    public List&lt;Contato&gt; listContato() {
        List&lt;Contato&gt; courses = null;
        try {
            courses = session.createQuery("from Contato").list();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return courses;
    }

    @Override
    public Contato listContatoById(Integer contatoId) {
        Contato contato = null;
        try {
            contato = (Contato) session.get(Contato.class, contatoId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return contato;
    }

    @Override
    public void deleteContato(Integer contatoId) {
        try {
            Contato contato = (Contato) session.get(Contato.class, contatoId);
            session.delete(contato);
        } catch (Exception e) {
            transaction.rollback();
            e.printStackTrace();
        }
    }
}



7) Preparando o action (service)



Figura 28- Implementando a action



Figura 29- Implementando a action


ContatoAction.java :
package com.springlesson09.service;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.springlesson09.dao.ContatoDAO;
import com.springlesson09.dao.ContatoDAOImpl;
import com.springlesson09.model.Contato;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;

public class ContatoAction extends ActionSupport implements ModelDriven&lt;Contato&gt; {

    private static final long serialVersionUID = -6659925652584240539L;
    private Contato contato = new Contato();
    private List&lt;Contato&gt; contatoList = new ArrayList&lt;Contato&gt;();
    private ContatoDAO contatoDAO = new ContatoDAOImpl();

    @Override
    public Contato getModel() {
        return contato;
    }

    public String saveOrUpdate() {
        contatoDAO.saveOrUpdateContato(contato);
        return SUCCESS;
    }

    /**
     * To list all contatos.
     *
     * @return String
     */
    public String list() {
        contatoList = contatoDAO.listContato();
        return SUCCESS;
    }

    /**
     * To delete a contato.
     *
     * @return String
     */
    public String delete() {
        HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
        contatoDAO.deleteContato(Integer.parseInt(request.getParameter("id")));
        return SUCCESS;
    }

    /**
     * To list a single contato by Id.
     *
     * @return String
     */
    public String edit() {
        HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
        contato = contatoDAO.listContatoById(Integer.parseInt(request.getParameter("id")));
        return SUCCESS;
    }

    public Contato getContato() {
        return contato;
    }

    public void setContato(Contato contato) {
        this.contato = contato;
    }

    public List&lt;Contato&gt; getContatoList() {
        return contatoList;
    }

    public void setContatoList(List&lt;Contato&gt; contatoList) {
        this.contatoList = contatoList;
    }
}


8) Criando os arquivos XML struts.xml e web.xml



Figura 30- Implementando os arquivos XML



src/struts.xml :

&lt;!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd"&gt;

&lt;struts&gt;
    &lt;package name="default" extends="hibernate-default"&gt;
        &lt;action name="saveOrUpdateContato" method="saveOrUpdate" class="com.springlesson09.service.ContatoAction"&gt;
            &lt;result name="success" type="redirect"&gt;listContato&lt;/result&gt;
        &lt;/action&gt;
        &lt;action name="listContato" method="list" class="com.springlesson09.service.ContatoAction"&gt;
            &lt;result name="success"&gt;/register.jsp&lt;/result&gt;
        &lt;/action&gt;
        &lt;action name="editContato" method="edit" class="com.springlesson09.service.ContatoAction"&gt;
            &lt;result name="success"&gt;/register.jsp&lt;/result&gt;
        &lt;/action&gt;
        &lt;action name="deleteContato" method="delete" class="com.springlesson09.service.ContatoAction"&gt;
            &lt;result name="success" type="redirect"&gt;listContato&lt;/result&gt;
        &lt;/action&gt;
    &lt;/package&gt;
&lt;/struts&gt;


WEB-INF/web.xml :

&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"&gt;
    &lt;display-name&gt;Struts2Example19&lt;/display-name&gt;
    &lt;filter&gt;
        &lt;filter-name&gt;struts2&lt;/filter-name&gt;
        &lt;filter-class&gt;
            org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
        &lt;/filter-class&gt;
    &lt;/filter&gt;
    &lt;filter-mapping&gt;
        &lt;filter-name&gt;struts2&lt;/filter-name&gt;
        &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
    &lt;/filter-mapping&gt;

    &lt;welcome-file-list&gt;
        &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt;
    &lt;/welcome-file-list&gt;
&lt;/web-app&gt;


O NB já deve ter criado os arquivo XML context.xml e o beans.xml:

META-INF/context.xml&nbsp;

&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;Context antiJARLocking="true" path="/SpringLesson09"/&gt;


WEB-INF/beans.xml:

&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;beans xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd"&gt;
&lt;/beans&gt;



Remova a lib do Hibernate &nbsp;que o NB adicionou


Figura 31- Limpe o que o NB adicionou


e deixe apenas as utilizadas.


Figura 32- Limpeza das biblotecas


9) Criando os arquivos jsp e css

I) acertemos o index.jsp que o NB criou :
index.jsp :
&lt;%@page contentType="text/html" pageEncoding="UTF-8"%&gt;
&lt;%@taglib uri="/struts-tags" prefix="s"%&gt;
&lt;!DOCTYPE html&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;title&gt;&lt;/title&gt;
        &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;script type="text/javascript"&gt;
            location.href='/SpringLesson09/listContato';
        &lt;/script&gt;
    &lt;/body&gt;
&lt;/html&gt;



II)register.jsp

&lt;%@ page language="java" contentType="text/html; charset=ISO-8859-1"
         pageEncoding="ISO-8859-1"%&gt;
&lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt;
&lt;%@taglib uri="/struts-tags" prefix="s"%&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"&gt;
        &lt;title&gt;Novo Contato&lt;/title&gt;
        &lt;s:head /&gt;
        &lt;style type="text/css"&gt;
            @import url(style.css);
        &lt;/style&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;s:form action="saveOrUpdateContato"&gt;
            &lt;s:push value="contato"&gt;
                &lt;s:hidden name="id" /&gt;
                &lt;s:textfield name="nome" label="Nome" /&gt;
                &lt;s:textfield name="telefone" label="Fone" /&gt;
                &lt;s:textfield name="email" label="Email" /&gt;

                &lt;s:submit /&gt;
            &lt;/s:push&gt;
        &lt;/s:form&gt;

        &lt;s:if test="contatoList.size() &gt; 0"&gt;
            &lt;div class="content"&gt;
                &lt;table class="contatoTable" cellpadding="5px"&gt;
                    &lt;tr class="even"&gt;
                        &lt;th&gt;Nome&lt;/th&gt;
                        &lt;th&gt;Fone&lt;/th&gt;
                        &lt;th&gt;Email&lt;/th&gt;
                        &lt;th&gt;&amp;nbsp;&lt;/th&gt;
                        &lt;th&gt;&amp;nbsp;&lt;/th&gt;

                    &lt;/tr&gt;
                    &lt;s:iterator value="contatoList" status="contatoStatus"&gt;
                        &lt;tr
                            class="&lt;s:if test="#contatoStatus.odd == true "&gt;odd&lt;/s:if&gt;&lt;s:else&gt;even&lt;/s:else&gt;"&gt;
                            &lt;td&gt;&lt;s:property value="nome" /&gt;&lt;/td&gt;
                            &lt;td&gt;&lt;s:property value="telefone" /&gt;&lt;/td&gt;
                            &lt;td&gt;&lt;s:property value="email" /&gt;&lt;/td&gt;

                            &lt;td&gt;&lt;s:url id="editURL" action="editContato"&gt;
                                    &lt;s:param name="id" value="%{id}"&gt;&lt;/s:param&gt;
                                &lt;/s:url&gt; &lt;s:a href="%{editURL}"&gt;Edit&lt;/s:a&gt;&lt;/td&gt;
                            &lt;td&gt;&lt;s:url id="deleteURL" action="deleteContato"&gt;
                                    &lt;s:param name="id" value="%{id}"&gt;&lt;/s:param&gt;
                                &lt;/s:url&gt; &lt;s:a href="%{deleteURL}"&gt;Delete&lt;/s:a&gt;&lt;/td&gt;
                            &lt;/tr&gt;
                    &lt;/s:iterator&gt;
                &lt;/table&gt;
            &lt;/div&gt;
        &lt;/s:if&gt;
    &lt;/body&gt;
&lt;/html&gt;





III) o style.css

@CHARSET "ISO-8859-1";

.content {
font-family: sans-serif;
font-size: small;
}


.userTable {
 border-width: 1px 1px 1px 1px;
 border-spacing: 2px;
 border-style: outset outset outset outset;
 border-color: black black black black;
 border-collapse: collapse;
}

.userTable td {
 border-width: 1px 1px 1px 1px;
 border-spacing: 2px;
 border-style: outset outset outset outset;
 border-color: black black black black;
 border-collapse: collapse;
}

.userTable th {
 border-width: 1px 1px 1px 1px;
 border-spacing: 2px;
 border-style: outset outset outset outset;
 border-color: black black black black;
 border-collapse: collapse;
 background-color: rgb(255, 255, 255);
}

.odd {
background-color: #FFFFF0;
}

.even {
background-color: #FAF0E6;
}




10) Conferindo a estrutura do projeto :


Figura 33- Visão do projeto






11) Testando&nbsp;




Figura 34-1º Teste sem utilizar as DI Spring

















Observe o Log :
INFO: No Spring WebApplicationInitializer types detected on classpath
Oct 2, 2012 8:46:08 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
Oct 2, 2012 8:50:54 PM org.apache.catalina.core.ApplicationContext log
INFO: SessionListener: contextDestroyed()
Oct 2, 2012 8:50:54 PM org.apache.catalina.core.ApplicationContext log
INFO: ContextListener: contextDestroyed()
Oct 2, 2012 8:52:25 PM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
Oct 2, 2012 8:52:25 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
Oct 2, 2012 8:52:36 PM org.apache.catalina.core.ApplicationContext log
INFO: ContextListener: contextInitialized()
Oct 2, 2012 8:52:36 PM org.apache.catalina.core.ApplicationContext log
INFO: SessionListener: contextInitialized()
Oct 2, 2012 8:52:36 PM org.apache.catalina.core.ApplicationContext log
INFO: ContextListener: attributeAdded('org.apache.jasper.compiler.TldLocationsCache', 'org.apache.jasper.compiler.TldLocationsCache@6a74f160')
Oct 2, 2012 8:52:53 PM org.apache.catalina.core.ApplicationContext log
INFO: Closing Spring root WebApplicationContext
Oct 2, 2012 8:53:10 PM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
Oct 2, 2012 8:53:10 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
Oct 2, 2012 8:54:20 PM org.apache.catalina.core.ApplicationContext log
INFO: Closing Spring root WebApplicationContext
Oct 2, 2012 8:54:25 PM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
Oct 2, 2012 8:54:25 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
Oct 2, 2012 8:56:40 PM org.apache.catalina.core.ApplicationContext log
INFO: Closing Spring root WebApplicationContext
Oct 2, 2012 8:56:44 PM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
Oct 2, 2012 8:56:44 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
Oct 2, 2012 9:02:24 PM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
Oct 2, 2012 9:02:24 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
Oct 2, 2012 9:02:37 PM org.apache.catalina.core.ApplicationContext log
INFO: ContextListener: contextInitialized()
Oct 2, 2012 9:02:37 PM org.apache.catalina.core.ApplicationContext log
INFO: SessionListener: contextInitialized()
Oct 2, 2012 9:02:37 PM org.apache.catalina.core.ApplicationContext log
INFO: ContextListener: attributeAdded('org.apache.jasper.compiler.TldLocationsCache', 'org.apache.jasper.compiler.TldLocationsCache@fae7b85')


Experimente adicionar, atualizar e excluir registros:



Download do projeto NB:

SpringLesson09-v1.zip




Certo. Já que as lições são sobre o Spring. Vamos fazer o Spring gerenciar tudo isso



vou começar outra numeração:
Para que o Spring possa gerenciar os beans, precisaremos fazer algumas modificações no projeto.
Como implementar um BO(Business Objects) em vez de um serviço, essa adaptação fiz do mkYoung
e por isso no App vc verá uma estrutura para uma tabela customer, que tem a mesma implementação com menos métodos.


0) Apr

Se tiver problemas de memória com o TomCat, mesmo definindo no arquivo catalina.sh &nbsp;JAVA_OPTS="-Xms128M -Xmx256" ou mais, e instalando o Apr ou use o GlassFish ;)


I) baixe os fontes da libapr :&nbsp;




Figura 35-Instalação do APR



II) compie e instale
307 &nbsp;cd /Users/surfer/Downloads/JavaDocs/apr-1.4.6&nbsp;
308 &nbsp;./configure&nbsp;
309 &nbsp;make
310 &nbsp;sudo make install



Apos compilar e instalar , crie os links p/ dentro de uma pasta que já está no CLASSPATH do tomcat

no caso do MAC OSX &nbsp;

&nbsp;311 &nbsp;cd /Library/Java/Extensions

&nbsp;322 &nbsp;ln -s /usr/local/apr/lib/* .


Figura 36-linkando as novas libs





Apos compilar e instalar , instale o native que vem com &nbsp;tomcat que tem como parámetro o local estão os binários do libapr



&nbsp; 348 &nbsp;cd /Users/surfer/_java/Servers/apache-tomcat-7.0.30/bin/tomcat-native-1.1.24-src/jni/native&nbsp;
&nbsp; 349 &nbsp;./configure --help
&nbsp; 350 &nbsp;./configure --with-apr=/usr/local/apr/ --with-java-home=/System/Library/Frameworks/JavaVM.framework/Versions/Current/&nbsp;
&nbsp; 351 &nbsp;make
&nbsp; 352 &nbsp;sudo make install









Figura 37-Instalação do APR no tomcat Native




Figura 38-Instalação do APR no tomcat Native


na proxima vez que vc iniciar o tomcat no log deve aparecer algo como :

Log :
Oct 2, 2012 10:45:09 PM org.apache.catalina.core.AprLifecycleListener init
INFO: Loaded APR based Apache Tomcat Native library 1.1.24 using APR version 1.4.6.
Oct 2, 2012 10:45:10 PM org.apache.catalina.core.AprLifecycleListener init
INFO: APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
Oct 2, 2012 10:45:10 PM org.apache.catalina.core.AprLifecycleListener initializeSSL
INFO: OpenSSL successfully initialized (OpenSSL 0.9.8l 5 Nov 2009)
Oct 2, 2012 10:45:12 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-apr-8080"]
Oct 2, 2012 10:45:12 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-apr-8009"]
Oct 2, 2012 10:45:12 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 4661 ms
Oct 2, 2012 10:45:12 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Oct 2, 2012 10:45:12 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.30


2) pegue a versão mais atual do full-hibernate-plugin-for-struts2&nbsp;e verifique as libs

O projeto novo deve ficar com a seguinte estrutura :


Figura 39- Visão do projeto p/implementar o Spring





Figura 40- Visão do projeto p/implementar o Spring- Libs




usei o recurso de mapeamento p/ gerar a classe Customer

3) Crie a interface ContatoBo




Figura 41 - Adicionando um BO para o Contato



Java :
package com.springlesson09.model;

import java.util.List;

public interface ContatoBo {

    public void saveOrUpdateContato(Contato contato);

    public List&lt;Contato&gt; listContato();

    public Contato listContatoById(Integer contatoId);

    public void deleteContato(Integer contatoId);
}




4) Implemente a interface ContatoBo


Figura 42 - Implementando a Interface do BO



Figura 43 - Implementando a Interface do BO, pelo NB






Java :
package com.springlesson09.model;

import com.springlesson09.dao.CustomerDAO;
import java.util.List;


public class CustomerBoImpl implements CustomerBo {
     CustomerDAO customerDAO;
        //DI via Spring
    public void setCustomerDAO(CustomerDAO customerDAO) {
        this.customerDAO = customerDAO;
    }
        
        
    @Override
    public void addCustomer(Customer customer) {
        customerDAO.addCustomer(customer);

    }

    @Override
    public List&lt;Customer&gt; listCustomer() {
        return customerDAO.listCustomer();
    }
    
}



5) Verifique a classe de implementação do ContatoDAO

Usaremos os métodos do hibernate e não da nossa implementação ; observe :


ContatoDAOImpl.java
package com.springlesson09.dao;

import com.googlecode.s2hibernate.struts2.plugin.annotations.SessionTarget;
import com.googlecode.s2hibernate.struts2.plugin.annotations.TransactionTarget;
import com.springlesson09.model.Contato;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class ContatoDAOImpl extends HibernateDaoSupport implements ContatoDAO {

    @SessionTarget
    Session session;
    @TransactionTarget
    Transaction transaction;

    /**
     *
     * @param contato
     */
//    @Override
    public void saveOrUpdateContato(Contato contato) {
        try {
//            session.saveOrUpdate(contato);
            session.save(contato);
        } catch (Exception ex) {
            transaction.rollback();
            java.util.logging.Logger.getLogger(ContatoDAOImpl.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
    }

    /**
     *
     * @return
     */
//    @SuppressWarnings("unchecked")
//    @Override
    public List&lt;Contato&gt; listContato() {
        List&lt;Contato&gt; contatos = null;
        try {
            contatos = session.createQuery("from Contato").list();
        } catch (Exception ex) {
            java.util.logging.Logger.getLogger(ContatoDAOImpl.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        return contatos;
    }

//    @Override
    public Contato listContatoById(Integer contatoId) {
        Contato contato = null;
        try {
            contato = (Contato) session.get(Contato.class, contatoId);
        } catch (Exception ex) {
            java.util.logging.Logger.getLogger(ContatoDAOImpl.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        return contato;
    }

//    @Override
    public void deleteContato(Integer contatoId) {
        try {
            Contato contato = (Contato) session.get(Contato.class, contatoId);
            session.delete(contato);
        } catch (Exception ex) {
            transaction.rollback();
            java.util.logging.Logger.getLogger(ContatoDAOImpl.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
    }
}



6) Agora vamos criar a action p/ Contato

vou chmar de outro nome&nbsp;ContatoSpringAction.java p/ enfatizar o uso do Spring


Java :
package com.springlesson09.service;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ModelDriven;
import com.springlesson09.dao.ContatoDAO;
import com.springlesson09.dao.ContatoDAOImpl;
import com.springlesson09.model.Contato;
import com.springlesson09.model.ContatoBo;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;


public class ContatoSpringAction implements ModelDriven {

    Contato contato = new Contato();
    List&lt;Contato&gt; contatoList = new ArrayList&lt;Contato&gt;();
    ContatoDAO contatoDAO = new ContatoDAOImpl();
    ContatoBo contatoBo;

    @Override
    public Object getModel() {
        return contato;
    }

    public Contato getContato() {
        return contato;
    }

    public void setContato(Contato contato) {
        this.contato = contato;
    }

    public List&lt;Contato&gt; getContatoList() {
        return contatoList;
    }

    public void setContatoList(List&lt;Contato&gt; contatoList) {
        this.contatoList = contatoList;
    }

    public ContatoDAO getContatoDAO() {
        return contatoDAO;
    }

    public void setContatoDAO(ContatoDAO contatoDAO) {
        this.contatoDAO = contatoDAO;
    }

    public void setContatoBo(ContatoBo contatoBo) {
        this.contatoBo = contatoBo;
    }

    public String execute() throws Exception {
        return sync();
    }

    public String sync() throws Exception {
        return "success";
    }

    public String listcontato() throws Exception {
        contatoList = contatoDAO.listContato();
        return sync();
    }

    public String saveOrUpdateContato() throws Exception {

        contatoDAO.saveOrUpdateContato(contato);
        //reload
        contatoList = null;
        contatoList = contatoDAO.listContato();
        return sync();

    }

    public String listContatoById() throws Exception {

        contato = contatoDAO.listContatoById(contato.getId());
        return sync();

    }

    public String deleteContato() throws Exception {
        HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
        contatoDAO.deleteContato(Integer.parseInt(request.getParameter("id")));
//        contatoDAO.deleteContato(contato.getId());
        contatoList = null;
        contatoList = contatoDAO.listContato();
        return sync();

    }
    
     public String edit() throws Exception {
        HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
        contato = contatoDAO.listContatoById(Integer.parseInt(request.getParameter("id")));
        return sync();
    }
}



7) Implementemos um arquivo de nome jdbc.properties p/ ser lido pelo bean dataSource


Figura 44 - Arquivo properties





jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://ns1:3306/springlessons
jdbc.username=springlessons
jdbc.password=DHADdSXcDF29WGXy


8) Implementemos os Beans no arquivo&nbsp;applicationContext.xml

WEB-INF/applicationContext.xml: obs: neste caso coloquei todos os beans dentro desse arquivo

&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;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:aop="http://www.springframework.org/schema/aop"
       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/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"&gt;


        &lt;!-- Meus Beans --&gt;
        &lt;!-- customer --&gt;

    &lt;bean id="customerAction" class="com.springlesson09.service.CustomerAction"&gt;
        &lt;property name="customerBo" ref="customerBo" /&gt; 
    &lt;/bean&gt;
 
    &lt;bean id="customerBo" class="com.springlesson09.model.CustomerBoImpl" &gt;
        &lt;property name="customerDAO" ref="customerDAO" /&gt;
    &lt;/bean&gt;
 
    &lt;bean id="customerDAO" class="com.springlesson09.dao.CustomerDAOImpl" &gt;
        &lt;property name="sessionFactory" ref="sessionFactory" /&gt;
    &lt;/bean&gt;
    
    &lt;!-- contato --&gt;
    &lt;bean id="contatoAction" class="com.springlesson09.service.ContatoSpringAction"&gt;
        &lt;property name="contatoBo" ref="contatoBo" /&gt; 
    &lt;/bean&gt;

    &lt;bean id="contatoBo" class="com.springlesson09.model.ContatoBoImpl" &gt;
        &lt;property name="contatoDAO" ref="contatoDAO" /&gt;
    &lt;/bean&gt;

    &lt;bean id="contatoDAO" class="com.springlesson09.dao.ContatoDAOImpl" &gt;
        &lt;property name="sessionFactory" ref="sessionFactory" /&gt;
    &lt;/bean&gt;
    
    
    &lt;!-- ADD PERSISTENCE SUPPORT HERE (jpa, hibernate, etc) --&gt;
    &lt;bean 
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&gt;
        &lt;property name="location"&gt;
            &lt;value&gt;WEB-INF/jdbc.properties&lt;/value&gt;
        &lt;/property&gt;
    &lt;/bean&gt;
 
    &lt;bean id="dataSource" 
          class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt;
        &lt;property name="driverClassName" value="${jdbc.driverClassName}" /&gt;
        &lt;property name="url" value="${jdbc.url}" /&gt;
        &lt;property name="username" value="${jdbc.username}" /&gt;
        &lt;property name="password" value="${jdbc.password}" /&gt;
    &lt;/bean&gt;
 
    &lt;bean id="sessionFactory" 
              class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"&gt;
 
        &lt;property name="dataSource"&gt;
            &lt;ref bean="dataSource"/&gt;
        &lt;/property&gt;
 
        &lt;property name="hibernateProperties"&gt;
            &lt;props&gt;
                &lt;prop key="hibernate.dialect"&gt;org.hibernate.dialect.MySQLDialect&lt;/prop&gt;
                &lt;prop key="hibernate.show_sql"&gt;true&lt;/prop&gt;
            &lt;/props&gt;
        &lt;/property&gt;
 
        &lt;property name="mappingResources"&gt;
            &lt;list&gt;
                &lt;value&gt;com/springlesson09/model/Customer.hbm.xml&lt;/value&gt;
                &lt;value&gt;com/springlesson09/model/Contato.hbm.xml&lt;/value&gt;
            &lt;/list&gt;
        &lt;/property&gt; 
 
    &lt;/bean&gt;
    
&lt;/beans&gt;   





9) Implementemos os Actions no arquivo struts.xml

src/java/struts.xml. Obs: mantive comentado como era antes do spring p/ facilitar a comparação

&lt;!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd"&gt;

&lt;struts&gt;
    &lt;constant name="struts.devMode" value="true" /&gt;
 
    &lt;!--&lt;package name="default" namespace="/" extends="struts-default"&gt;--&gt;
    &lt;package name="default" namespace="/" extends="hibernate-default"&gt;
      &lt;!-- customer --&gt;
        &lt;action name="addCustomerAction" 
                  class="com.springlesson09.service.CustomerAction" 
                  method="addCustomer" &gt;
            &lt;result name="success"&gt;/customer.jsp&lt;/result&gt;
        &lt;/action&gt;
 
        &lt;action name="listCustomerAction"
                        class="com.springlesson09.service.CustomerAction" 
                        method="listCustomer" &gt;
            &lt;result name="success"&gt;/customer.jsp&lt;/result&gt;
        &lt;/action&gt; 
        &lt;!-- contato --&gt; 
        &lt;action name="addContatoAction" 
                 class="com.springlesson09.service.ContatoSpringAction" 
                 method="saveOrUpdateContato" &gt;
           &lt;result name="success"&gt;/contato.jsp&lt;/result&gt;
       &lt;/action&gt;

       &lt;action name="listContatoAction"
                       class="com.springlesson09.service.ContatoSpringAction" 
                       method="listcontato" &gt;
           &lt;result name="success"&gt;/contato.jsp&lt;/result&gt;
       &lt;/action&gt; 
       
       &lt;action name="deleteContatoAction"
                       class="com.springlesson09.service.ContatoSpringAction" 
                       method="deleteContato" &gt;
           &lt;result name="success"&gt;/contato.jsp&lt;/result&gt;
       &lt;/action&gt;
       &lt;action name="editContatoAction"
                       class="com.springlesson09.service.ContatoSpringAction" 
                       method="edit" &gt;
           &lt;result name="success"&gt;/contato.jsp&lt;/result&gt;
       &lt;/action&gt;  
        &lt;!--  
            Antes do Spring  
            
        &lt;package name="default" extends="hibernate-default"&gt;
        &lt;action name="saveOrUpdateContato" method="saveOrUpdate" class="com.springlesson09.service.ContatoAction"&gt;
            &lt;result name="success" type="redirect"&gt;listContato&lt;/result&gt;
        &lt;/action&gt;
        &lt;action name="listContato" method="list" class="com.springlesson09.service.ContatoAction"&gt;
            &lt;result name="success"&gt;/register.jsp&lt;/result&gt;
        &lt;/action&gt;
        &lt;action name="editContato" method="edit" class="com.springlesson09.service.ContatoAction"&gt;
            &lt;result name="success"&gt;/register.jsp&lt;/result&gt;
        &lt;/action&gt;
        &lt;action name="deleteContato" method="delete" class="com.springlesson09.service.ContatoAction"&gt;
            &lt;result name="success" type="redirect"&gt;listContato&lt;/result&gt;
        &lt;/action&gt;--&gt;
    &lt;/package&gt;
&lt;/struts&gt;





10) Acertos no arquivo web.xml

XML :

&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"&gt;
    &lt;display-name&gt;Struts2Example19&lt;/display-name&gt;
    &lt;context-param&gt;
        &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
        &lt;param-value&gt;/WEB-INF/applicationContext.xml&lt;/param-value&gt;
    &lt;/context-param&gt;
    
    &lt;filter&gt;
        &lt;filter-name&gt;struts2&lt;/filter-name&gt;
        &lt;filter-class&gt;
            org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
        &lt;/filter-class&gt;
    &lt;/filter&gt;
    &lt;filter-mapping&gt;
        &lt;filter-name&gt;struts2&lt;/filter-name&gt;
        &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
    &lt;/filter-mapping&gt;

    &lt;welcome-file-list&gt;
        &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt;
    &lt;/welcome-file-list&gt;
 
    &lt;listener&gt;
        &lt;listener-class&gt;
            org.springframework.web.context.ContextLoaderListener
        &lt;/listener-class&gt;
    &lt;/listener&gt;

&lt;/web-app&gt;



11) Arquivos jsp

I) index.jsp

index.jsp :
&lt;%@page contentType="text/html" pageEncoding="UTF-8"%&gt;
&lt;%@taglib uri="/struts-tags" prefix="s"%&gt;
&lt;!DOCTYPE html&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;title&gt;&lt;/title&gt;
        &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt;
    &lt;/head&gt;
    &lt;body&gt;
        
        &lt;h2&gt;JNSBTut Lesson 09 
        Spring 3 +  Full Hibernate Plugin's  + Struts 2&lt;/h2&gt;
        
        &lt;img src="images/splash_mcezzare_JSNBTut09.png" /&gt;&lt;br&gt;
        &lt;ul&gt;
            &lt;li&gt;&lt;s:a href="/SpringLesson09-v2/listCustomerAction.action"&gt;Customer&lt;/s:a&gt;&lt;/li&gt;
            &lt;li&gt;&lt;s:a href="/SpringLesson09-v2/listContatoAction.action"&gt;Contato&lt;/s:a&gt;&lt;/li&gt;
        
        &lt;/ul&gt;
    &lt;/body&gt;
&lt;/html&gt;



II)contato.jsp (por enquanto p/ cadastrar e atualizar, no update não carrega a lista)

&lt;%@ page language="java" contentType="text/html; charset=ISO-8859-1"
         pageEncoding="ISO-8859-1"%&gt;
&lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt;
&lt;%@taglib uri="/struts-tags" prefix="s"%&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"&gt;
        &lt;title&gt;Novo Contato&lt;/title&gt;
        &lt;s:head /&gt;
        &lt;style type="text/css"&gt;
            @import url(style.css);
        &lt;/style&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;s:form action="addContatoAction"&gt;
            &lt;s:push value="contato"&gt;
                &lt;s:hidden name="id" /&gt;
                &lt;s:textfield name="nome" label="Nome" /&gt;
                &lt;s:textfield name="telefone" label="Fone" /&gt;
                &lt;s:textfield name="email" label="Email" /&gt;

                &lt;s:submit /&gt;
            &lt;/s:push&gt;
        &lt;/s:form&gt;

        &lt;s:if test="contatoList.size() &gt; 0"&gt;
            &lt;div class="content"&gt;
                &lt;table class="contatoTable" cellpadding="5px"&gt;
                    &lt;tr class="even"&gt;
                        &lt;th&gt;Nome&lt;/th&gt;
                        &lt;th&gt;Fone&lt;/th&gt;
                        &lt;th&gt;Email&lt;/th&gt;
                        &lt;th&gt;&amp;nbsp;&lt;/th&gt;
                        &lt;th&gt;&amp;nbsp;&lt;/th&gt;

                    &lt;/tr&gt;
                    &lt;s:iterator value="contatoList" status="contatoStatus"&gt;
                        &lt;tr
                            class="&lt;s:if test="#contatoStatus.odd == true "&gt;odd&lt;/s:if&gt;&lt;s:else&gt;even&lt;/s:else&gt;"&gt;
                            &lt;td&gt;&lt;s:property value="nome" /&gt;&lt;/td&gt;
                            &lt;td&gt;&lt;s:property value="telefone" /&gt;&lt;/td&gt;
                            &lt;td&gt;&lt;s:property value="email" /&gt;&lt;/td&gt;

                            &lt;td&gt;&lt;s:url id="editURL" action="editContato"&gt;
                                    &lt;s:param name="id" value="%{id}"&gt;&lt;/s:param&gt;
                                &lt;/s:url&gt; &lt;s:a href="%{editURL}"&gt;Edit&lt;/s:a&gt;&lt;/td&gt;
                            &lt;td&gt;&lt;s:url id="deleteURL" action="deleteContato"&gt;
                                    &lt;s:param name="id" value="%{id}"&gt;&lt;/s:param&gt;
                                &lt;/s:url&gt; &lt;s:a href="%{deleteURL}"&gt;Delete&lt;/s:a&gt;&lt;/td&gt;
                            &lt;/tr&gt;
                    &lt;/s:iterator&gt;
                &lt;/table&gt;
            &lt;/div&gt;
        &lt;/s:if&gt;
    &lt;/body&gt;
&lt;/html&gt;












IV) customer (está no zip do projeto)




12) Teste


teste os dois: o CRUD


Figura 45 - Teste das implementações






o banco agora está assim :&nbsp;


Figura 46 - Tabelas do banco




CREATE  TABLE IF NOT EXISTS `springlessons`.`customer` (
  `CUSTOMER_ID` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT ,
  `NAME` VARCHAR(45) NOT NULL ,
  `ADDRESS` VARCHAR(255) NOT NULL ,
  `CREATED_DATE` DATETIME NOT NULL ,
  PRIMARY KEY (`CUSTOMER_ID`) )
ENGINE = InnoDB
AUTO_INCREMENT = 5
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci 

CREATE  TABLE IF NOT EXISTS `springlessons`.`contato` (
  `id` INT(11) NOT NULL AUTO_INCREMENT ,
  `nome` VARCHAR(45) NULL DEFAULT NULL ,
  `telefone` VARCHAR(45) NULL DEFAULT NULL ,
  `email` VARCHAR(45) NULL DEFAULT NULL ,
  PRIMARY KEY (`id`) )
ENGINE = InnoDB
AUTO_INCREMENT = 96
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci



Coloquei uma imagem no index.jsp , veja como ficaram os arquivos:



Figura 47 - Projeto Organizado após as alterações - Classes e JSPs






e como ficaram as Libs:




Figura 48 - Projeto Organizado após as alterações - Libs


AO compilar o programa, observe tudo o q ele está carregando no Output :&nbsp;

I) ao rodar no TomCat


Log :

IOct 3, 2012 2:51:15 AM org.apache.catalina.core.AprLifecycleListener init
INFO: Loaded APR based Apache Tomcat Native library 1.1.24 using APR version 1.4.6.
Oct 3, 2012 2:51:15 AM org.apache.catalina.core.AprLifecycleListener init
INFO: APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
Oct 3, 2012 2:51:16 AM org.apache.catalina.core.AprLifecycleListener initializeSSL
INFO: OpenSSL successfully initialized (OpenSSL 0.9.8l 5 Nov 2009)
Oct 3, 2012 2:51:17 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-apr-8080"]
Oct 3, 2012 2:51:17 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-apr-8009"]
Oct 3, 2012 2:51:17 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 4328 ms
Oct 3, 2012 2:51:17 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Oct 3, 2012 2:51:17 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.30
Oct 3, 2012 2:51:17 AM org.apache.catalina.startup.HostConfig deployDescriptor
INFO: Deploying configuration descriptor /Users/surfer/_java/Servers/apache-tomcat-7.0.30/conf/Catalina/localhost/SpringLesson09-v3.xml
log4j:WARN No appenders could be found for logger (org.springframework.web.context.ContextLoader).
log4j:WARN Please initialize the log4j system properly.
02:51:45 - INFO: Full Hibernate Plugin Validation using Hibernate Validator 3.x 
Oct 3, 2012 2:51:46 AM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory /Users/surfer/_java/Servers/apache-tomcat-7.0.30/webapps/docs
Oct 3, 2012 2:51:46 AM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory /Users/surfer/_java/Servers/apache-tomcat-7.0.30/webapps/examples
Oct 3, 2012 2:51:48 AM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory /Users/surfer/_java/Servers/apache-tomcat-7.0.30/webapps/host-manager
Oct 3, 2012 2:51:48 AM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory /Users/surfer/_java/Servers/apache-tomcat-7.0.30/webapps/manager
Oct 3, 2012 2:51:49 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-apr-8080"]
Oct 3, 2012 2:51:49 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-apr-8009"]
Oct 3, 2012 2:51:49 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 32021 ms
Oct 3, 2012 2:51:55 AM org.apache.jasper.compiler.TldLocationsCache tldScanJar
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
02:53:26 - DEBUG: Preparing Injection Hibernate Session and Transaction process: /listContatoAction - Method: com.springlesson09.service.ContatoSpringAction.listcontato() 
02:53:26 - DEBUG: Full Hibernate Plugin's Session Factory: destroy factory required... 
02:53:26 - DEBUG: Full Hibernate Plugin's Session Factory: C3P0 not found 
02:53:26 - DEBUG: Full Hibernate Plugin's Session Factory: All SessionFactories Destroyed sucessful 
02:53:26 - DEBUG: Hibernate Session Required (from current Thread) - SessionFactory required: (default) 
02:53:26 - DEBUG: No Hibernate Session in current thread. New Hibernate Session will be created and returned (SessionFactory "(default)") 
02:53:26 - DEBUG: New Hibernate Session required - SessionFactory required: (default) 
02:53:26 - DEBUG: Full Hibernate Plugin's Session Factory build started... 
02:53:26 - DEBUG: Full Hibernate Plugin's Session Factory using Hibernate Annotation Configuration 
02:53:26 - DEBUG: Full Hibernate Plugin's Session Factory configuration file "/hibernate.cfg.xml" configured 
02:53:27 - DEBUG: SessionFactory "" configured from "/hibernate.cfg.xml" file 
02:53:27 - DEBUG: "" configured as the *default* SessionFactory of the Full Hibernate Plugin's Session Factory  
02:53:27 - DEBUG: Full Hibernate Plugin's Session Factory built successful 
02:53:27 - DEBUG: New Hibernate Session created and returned (SessionFactory "") 
02:53:27 - DEBUG: Hibernate Session from Full Hibernate Plugin's Hibernate Session Factory 
02:53:27 - DEBUG: Hibernate Session injected (by annotation) into Action. Field "session". Class "com.springlesson09.dao.ContatoDAOImpl" 
02:53:27 - DEBUG: Hibernate Transaction injected (by annotation) into Action. Field "transaction". Class "com.springlesson09.dao.ContatoDAOImpl" 
02:53:27 - WARN: Full Hibernate Plugin Validation Allowed only in Actions that 'ISA' ActionSupport 
Hibernate: 
    select
        contato0_.id as id5_,
        contato0_.nome as nome5_,
        contato0_.telefone as telefone5_,
        contato0_.email as email5_ 
    from
        springlessons.contato contato0_
02:53:36 - DEBUG: Hibernate Transation  org.hibernate.transaction.JDBCTransaction@3cd16610 rolledback by Full Hibernate Plugin 
02:53:36 - DEBUG: Hibernate Session closed 
02:53:36 - DEBUG: Hibernate Session closed by Full Hibernate Plugin's Hibernate Session Factory 
02:53:36 - DEBUG: Hibernate Transaction Committed 
02:53:36 - DEBUG: Injection Hibernate Session and Transaction process for /listContatoAction - Method: com.springlesson09.service.ContatoSpringAction.listcontato() finished 
02:54:12 - DEBUG: Preparing Injection Hibernate Session and Transaction process: /editContatoAction - Method: com.springlesson09.service.ContatoSpringAction.edit() 
02:54:12 - DEBUG: Hibernate Session Required (from current Thread) - SessionFactory required: (default) 
02:54:12 - DEBUG: No Hibernate Session in current thread. New Hibernate Session will be created and returned (SessionFactory "(default)") 
02:54:12 - DEBUG: New Hibernate Session required - SessionFactory required: (default) 
02:54:12 - DEBUG: New Hibernate Session created and returned (SessionFactory "") 
02:54:12 - DEBUG: Hibernate Session from Full Hibernate Plugin's Hibernate Session Factory 
02:54:12 - DEBUG: Hibernate Session injected (by annotation) into Action. Field "session". Class "com.springlesson09.dao.ContatoDAOImpl" 
02:54:12 - DEBUG: Hibernate Transaction injected (by annotation) into Action. Field "transaction". Class "com.springlesson09.dao.ContatoDAOImpl" 
02:54:12 - WARN: Full Hibernate Plugin Validation Allowed only in Actions that 'ISA' ActionSupport 
Hibernate: 
    select
        contato0_.id as id5_0_,
        contato0_.nome as nome5_0_,
        contato0_.telefone as telefone5_0_,
        contato0_.email as email5_0_ 
    from
        springlessons.contato contato0_ 
    where
        contato0_.id=?
02:54:13 - DEBUG: Hibernate Transation  org.hibernate.transaction.JDBCTransaction@11ace672 rolledback by Full Hibernate Plugin 
02:54:13 - DEBUG: Hibernate Session closed 
02:54:13 - DEBUG: Hibernate Session closed by Full Hibernate Plugin's Hibernate Session Factory 
02:54:13 - DEBUG: Hibernate Transaction Committed 
02:54:13 - DEBUG: Injection Hibernate Session and Transaction process for /editContatoAction - Method: com.springlesson09.service.ContatoSpringAction.edit() finished 
02:54:15 - DEBUG: Preparing Injection Hibernate Session and Transaction process: /addContatoAction - Method: com.springlesson09.service.ContatoSpringAction.saveOrUpdateContato() 
02:54:15 - DEBUG: Hibernate Session Required (from current Thread) - SessionFactory required: (default) 
02:54:15 - DEBUG: No Hibernate Session in current thread. New Hibernate Session will be created and returned (SessionFactory "(default)") 
02:54:15 - DEBUG: New Hibernate Session required - SessionFactory required: (default) 
02:54:15 - DEBUG: New Hibernate Session created and returned (SessionFactory "") 
02:54:15 - DEBUG: Hibernate Session from Full Hibernate Plugin's Hibernate Session Factory 
02:54:15 - DEBUG: Hibernate Session injected (by annotation) into Action. Field "session". Class "com.springlesson09.dao.ContatoDAOImpl" 
02:54:15 - DEBUG: Hibernate Transaction injected (by annotation) into Action. Field "transaction". Class "com.springlesson09.dao.ContatoDAOImpl" 
02:54:15 - WARN: Full Hibernate Plugin Validation Allowed only in Actions that 'ISA' ActionSupport 
Hibernate: 
    insert 
    into
        springlessons.contato
        (nome, telefone, email) 
    values
        (?, ?, ?)
Hibernate: 
    select
        contato0_.id as id5_,
        contato0_.nome as nome5_,
        contato0_.telefone as telefone5_,
        contato0_.email as email5_ 
    from
        springlessons.contato contato0_
02:54:17 - DEBUG: Hibernate Transation  org.hibernate.transaction.JDBCTransaction@17f74864 rolledback by Full Hibernate Plugin 
02:54:17 - DEBUG: Hibernate Session closed 
02:54:17 - DEBUG: Hibernate Session closed by Full Hibernate Plugin's Hibernate Session Factory 
02:54:17 - DEBUG: Hibernate Transaction Committed 
02:54:18 - DEBUG: Injection Hibernate Session and Transaction process for /addContatoAction - Method: com.springlesson09.service.ContatoSpringAction.saveOrUpdateContato() finished 
02:54:21 - DEBUG: Preparing Injection Hibernate Session and Transaction process: /deleteContatoAction - Method: com.springlesson09.service.ContatoSpringAction.deleteContato() 
02:54:21 - DEBUG: Hibernate Session Required (from current Thread) - SessionFactory required: (default) 
02:54:21 - DEBUG: No Hibernate Session in current thread. New Hibernate Session will be created and returned (SessionFactory "(default)") 
02:54:21 - DEBUG: New Hibernate Session required - SessionFactory required: (default) 
02:54:21 - DEBUG: New Hibernate Session created and returned (SessionFactory "") 
02:54:21 - DEBUG: Hibernate Session from Full Hibernate Plugin's Hibernate Session Factory 
02:54:21 - DEBUG: Hibernate Session injected (by annotation) into Action. Field "session". Class "com.springlesson09.dao.ContatoDAOImpl" 
02:54:21 - DEBUG: Hibernate Transaction injected (by annotation) into Action. Field "transaction". Class "com.springlesson09.dao.ContatoDAOImpl" 
02:54:21 - WARN: Full Hibernate Plugin Validation Allowed only in Actions that 'ISA' ActionSupport 
Hibernate: 
    select
        contato0_.id as id5_0_,
        contato0_.nome as nome5_0_,
        contato0_.telefone as telefone5_0_,
        contato0_.email as email5_0_ 
    from
        springlessons.contato contato0_ 
    where
        contato0_.id=?
Hibernate: 
    delete 
    from
        springlessons.contato 
    where
        id=?
Hibernate: 
    select
        contato0_.id as id5_,
        contato0_.nome as nome5_,
        contato0_.telefone as telefone5_,
        contato0_.email as email5_ 
    from
        springlessons.contato contato0_
02:54:21 - DEBUG: Hibernate Transation  org.hibernate.transaction.JDBCTransaction@42886462 rolledback by Full Hibernate Plugin 
02:54:21 - DEBUG: Hibernate Session closed 
02:54:21 - DEBUG: Hibernate Session closed by Full Hibernate Plugin's Hibernate Session Factory 
02:54:21 - DEBUG: Hibernate Transaction Committed 
02:54:21 - DEBUG: Injection Hibernate Session and Transaction process for /deleteContatoAction - Method: com.springlesson09.service.ContatoSpringAction.deleteContato() finished 
02:54:21 - DEBUG: Preparing Injection Hibernate Session and Transaction process: /listContatoAction - Method: com.springlesson09.service.ContatoSpringAction.listcontato() 
02:54:21 - DEBUG: Hibernate Session Required (from current Thread) - SessionFactory required: (default) 
02:54:21 - DEBUG: No Hibernate Session in current thread. New Hibernate Session will be created and returned (SessionFactory "(default)") 
02:54:21 - DEBUG: New Hibernate Session required - SessionFactory required: (default) 
02:54:21 - DEBUG: New Hibernate Session created and returned (SessionFactory "") 
02:54:21 - DEBUG: Hibernate Session from Full Hibernate Plugin's Hibernate Session Factory 
02:54:21 - DEBUG: Hibernate Session injected (by annotation) into Action. Field "session". Class "com.springlesson09.dao.ContatoDAOImpl" 
02:54:22 - DEBUG: Hibernate Transaction injected (by annotation) into Action. Field "transaction". Class "com.springlesson09.dao.ContatoDAOImpl" 
02:54:22 - WARN: Full Hibernate Plugin Validation Allowed only in Actions that 'ISA' ActionSupport 
Hibernate: 
    select
        contato0_.id as id5_,
        contato0_.nome as nome5_,
        contato0_.telefone as telefone5_,
        contato0_.email as email5_ 
    from
        springlessons.contato contato0_
02:54:23 - DEBUG: Hibernate Transation  org.hibernate.transaction.JDBCTransaction@1f4e8ac9 rolledback by Full Hibernate Plugin 
02:54:23 - DEBUG: Hibernate Session closed 
02:54:23 - DEBUG: Hibernate Session closed by Full Hibernate Plugin's Hibernate Session Factory 
02:54:23 - DEBUG: Hibernate Transaction Committed 
02:54:23 - DEBUG: Injection Hibernate Session and Transaction process for /listContatoAction - Method: com.springlesson09.service.ContatoSpringAction.listcontato() finished













II) ao rodar no GlassFish (não funcionou)


Log :
INFO: JMX005: JMXStartupService had Started JMXConnector on JMXService URL service:jmx:rmi://mmac.lpanic.intra:8686/jndi/rmi://mmac.lpanic.intra:8686/jmxrmi
INFO: WEB0169: Created HTTP listener [http-listener-1] on host/port [0.0.0.0:8080]
INFO: WEB0169: Created HTTP listener [http-listener-2] on host/port [0.0.0.0:8181]
INFO: WEB0169: Created HTTP listener [admin-listener] on host/port [0.0.0.0:4848]
INFO: WEB0171: Created virtual server [server]
INFO: WEB0171: Created virtual server [__asadmin]
INFO: WEB0172: Virtual server [server] loaded default web module []
INFO: defaultVirtualServer = server
INFO: SEC1002: Security Manager is OFF.
INFO: No default web.xml
INFO: standardContext = StandardEngine[glassfish-web].StandardHost[server].StandardContext[/osgi]
INFO: No default web.xml
INFO: standardContext = StandardEngine[glassfish-web].StandardHost[__asadmin].StandardContext[/osgi]
INFO: SEC1010: Entering Security Startup Service
INFO: SEC1143: Loading policy provider com.sun.enterprise.security.provider.PolicyWrapper.
INFO: SEC1115: Realm [admin-realm] of classtype [com.sun.enterprise.security.auth.realm.file.FileRealm] successfully created.
INFO: SEC1115: Realm [file] of classtype [com.sun.enterprise.security.auth.realm.file.FileRealm] successfully created.
INFO: SEC1115: Realm [certificate] of classtype [com.sun.enterprise.security.auth.realm.certificate.CertificateRealm] successfully created.
INFO: SEC1011: Security Service(s) Started Successfully
INFO: WELD-000900 1.1.8 (Final)
INFO: PWC1412: WebModule[null] ServletContext.log():No Spring WebApplicationInitializer types detected on classpath
INFO: PWC1412: WebModule[null] ServletContext.log():Initializing Spring root WebApplicationContext
SEVERE: log4j:WARN No appenders could be found for logger (org.springframework.web.context.ContextLoader).
SEVERE: log4j:WARN Please initialize the log4j system properly.
INFO: Hibernate 3.5.0-Final
INFO: hibernate.properties not found
INFO: Bytecode provider name : javassist
INFO: using JDK 1.4 java.sql.Timestamp handling
INFO: Mapping class: com.springlesson09.model.Customer -&gt; customer
INFO: Mapping class: com.springlesson09.model.Contato -&gt; contato
INFO: Initializing connection provider: org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider
INFO: RDBMS: MySQL, version: 5.1.63-0ubuntu0.11.10.1
INFO: JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.1.22 ( Revision: ${bzr.revision-id} )
INFO: Using dialect: org.hibernate.dialect.MySQLDialect
INFO: Transaction strategy: org.springframework.orm.hibernate3.SpringTransactionFactory
INFO: No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
INFO: Automatic flush during beforeCompletion(): disabled
INFO: Automatic session close at end of transaction: disabled
INFO: JDBC batch size: 15
INFO: JDBC batch updates for versioned data: disabled
INFO: Scrollable result sets: enabled
INFO: JDBC3 getGeneratedKeys(): enabled
INFO: Connection release mode: auto
INFO: Maximum outer join fetch depth: 2
INFO: Default batch fetch size: 1
INFO: Generate SQL with comments: disabled
INFO: Order SQL updates by primary key: disabled
INFO: Order SQL inserts for batching: disabled
INFO: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
INFO: Using ASTQueryTranslatorFactory
INFO: Query language substitutions: {}
INFO: JPA-QL strict compliance: disabled
INFO: Second-level cache: enabled
INFO: Query cache: disabled
INFO: Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory
INFO: Optimize cache for minimal puts: disabled
INFO: Structured second-level cache entries: disabled
INFO: Echoing all SQL to stdout
INFO: Statistics: disabled
INFO: Deleted entity synthetic identifier rollback: disabled
INFO: Default entity-mode: pojo
INFO: Named query checking : enabled
INFO: Check Nullability in Core (should be disabled when Bean Validation is on): enabled
INFO: building session factory
INFO: Not binding factory to JNDI, no JNDI name configured
INFO: 01:18:33 - INFO: Full Hibernate Plugin Validation using Hibernate Validator 3.x 

INFO: WEB0671: Loading application [SpringLesson09-v2] at [/SpringLesson09-v2]
INFO: SpringLesson09-v2 was successfully deployed in 30,920 milliseconds.
WARNING: PWC4011: Unable to set request character encoding to UTF-8 from context /SpringLesson09-v2, because request parameters have already been read, or ServletRequest.getReader() has already been called
WARNING: PWC4011: Unable to set request character encoding to UTF-8 from context /SpringLesson09-v2, because request parameters have already been read, or ServletRequest.getReader() has already been called
WARNING: PWC4011: Unable to set request character encoding to UTF-8 from context /SpringLesson09-v2, because request parameters have already been read, or ServletRequest.getReader() has already been called
INFO: 01:19:46 - DEBUG: Preparing Injection Hibernate Session and Transaction process: /listContatoAction - Method: com.springlesson09.service.ContatoSpringAction.listcontato() 

INFO: 01:19:46 - DEBUG: Full Hibernate Plugin's Session Factory: destroy factory required... 

INFO: 01:19:46 - DEBUG: Full Hibernate Plugin's Session Factory: C3P0 not found 

INFO: 01:19:46 - DEBUG: Full Hibernate Plugin's Session Factory: All SessionFactories Destroyed sucessful 

INFO: 01:19:46 - DEBUG: Hibernate Session Required (from current Thread) - SessionFactory required: (default) 

INFO: 01:19:46 - DEBUG: No Hibernate Session in current thread. New Hibernate Session will be created and returned (SessionFactory "(default)") 

INFO: 01:19:46 - DEBUG: New Hibernate Session required - SessionFactory required: (default) 

INFO: 01:19:46 - DEBUG: Full Hibernate Plugin's Session Factory build started... 

INFO: Hibernate Annotations 3.5.0-Final
INFO: Hibernate Commons Annotations 3.2.0.Final
INFO: 01:19:47 - DEBUG: Full Hibernate Plugin's Session Factory using Hibernate Annotation Configuration 

INFO: configuring from resource: /hibernate.cfg.xml
INFO: Configuration resource: /hibernate.cfg.xml
INFO: Reading mappings from resource : com/springlesson09/model/Usuario.hbm.xml
INFO: Reading mappings from resource : com/springlesson09/model/Contato.hbm.xml
INFO: Reading mappings from resource : com/springlesson09/model/Customer.hbm.xml
INFO: Configured SessionFactory: null
INFO: 01:19:47 - DEBUG: Full Hibernate Plugin's Session Factory configuration file "/hibernate.cfg.xml" configured 

INFO: Unable to find org.hibernate.search.event.FullTextIndexEventListener on the classpath. Hibernate Search is not enabled.
INFO: Mapping class: com.springlesson09.model.Usuario -&gt; usuario
INFO: Mapping class: com.springlesson09.model.Contato -&gt; contato
INFO: Mapping class: com.springlesson09.model.Customer -&gt; customer
INFO: Hibernate Validator 3.1.0.GA
INFO: Using Hibernate built-in connection pool (not for production use!)
INFO: Hibernate connection pool size: 20
INFO: autocommit mode: false
INFO: using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://ns1:3306/springlessons?zeroDateTimeBehavior=convertToNull
INFO: connection properties: {user=springlessons, password=****}
WARNING: Could not obtain connection to query metadata
java.sql.SQLException: No suitable driver found for jdbc:mysql://ns1:3306/springlessons?zeroDateTimeBehavior=convertToNull
 at java.sql.DriverManager.getConnection(DriverManager.java:602)
 at java.sql.DriverManager.getConnection(DriverManager.java:154)
 at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:133)
 at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:114)
 at org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2163)
 at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2159)
 at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1383)
 at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:954)
 at com.googlecode.s2hibernate.struts2.plugin.util.HibernateSessionFactory.createAndTestSessionFactory(HibernateSessionFactory.java:282)
 at com.googlecode.s2hibernate.struts2.plugin.util.HibernateSessionFactory.rebuildSessionFactory(HibernateSessionFactory.java:227)
 at com.googlecode.s2hibernate.struts2.plugin.util.HibernateSessionFactory.getNewSession(HibernateSessionFactory.java:155)
 at com.googlecode.s2hibernate.struts2.plugin.util.HibernateSessionFactory.getSession(HibernateSessionFactory.java:100)
 at com.googlecode.s2hibernate.struts2.plugin.interceptors.SessionTransactionInjectorInterceptor.getHibernateSessionFromFactory(SessionTransactionInjectorInterceptor.java:379)
 at com.googlecode.s2hibernate.struts2.plugin.interceptors.SessionTransactionInjectorInterceptor.injectHibernateCoreSessionByAnnotation(SessionTransactionInjectorInterceptor.java:454)
 at com.googlecode.s2hibernate.struts2.plugin.interceptors.SessionTransactionInjectorInterceptor.injectHibernateCoreSessionByAnnotation(SessionTransactionInjectorInterceptor.java:470)
 at com.googlecode.s2hibernate.struts2.plugin.interceptors.SessionTransactionInjectorInterceptor.intercept(SessionTransactionInjectorInterceptor.java:165)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:163)
 at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
 at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:148)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:93)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:128)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at org.apache.struts2.interceptor.ProfilingActivationInterceptor.intercept(ProfilingActivationInterceptor.java:104)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:148)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138)
 at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:128)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
 at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:468)
 at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
 at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:76)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
 at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
 at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
 at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
 at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
 at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
 at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
 at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
 at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
 at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
 at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
 at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
 at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
 at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
 at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
 at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
 at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
 at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
 at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
 at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
 at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
 at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
 at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
 at java.lang.Thread.run(Thread.java:680)

INFO: Using dialect: org.hibernate.dialect.MySQLDialect
INFO: Disabling contextual LOB creation as connection was null
INFO: Using default transaction strategy (direct JDBC transactions)
INFO: No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
INFO: Automatic flush during beforeCompletion(): disabled
INFO: Automatic session close at end of transaction: disabled
INFO: Scrollable result sets: disabled
INFO: JDBC3 getGeneratedKeys(): disabled
INFO: Connection release mode: auto
INFO: Maximum outer join fetch depth: 2
INFO: Default batch fetch size: 1
INFO: Generate SQL with comments: disabled
INFO: Order SQL updates by primary key: disabled
INFO: Order SQL inserts for batching: disabled
INFO: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
INFO: Using ASTQueryTranslatorFactory
INFO: Query language substitutions: {}
INFO: JPA-QL strict compliance: disabled
INFO: Second-level cache: enabled
INFO: Query cache: disabled
INFO: Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory
INFO: Optimize cache for minimal puts: disabled
INFO: Structured second-level cache entries: disabled
INFO: Echoing all SQL to stdout
INFO: Statistics: disabled
INFO: Deleted entity synthetic identifier rollback: disabled
INFO: Default entity-mode: pojo
INFO: Named query checking : enabled
INFO: Check Nullability in Core (should be disabled when Bean Validation is on): disabled
INFO: building session factory
INFO: Not binding factory to JNDI, no JNDI name configured
WARNING: SQL Error: 0, SQLState: 08001
SEVERE: No suitable driver found for jdbc:mysql://ns1:3306/springlessons?zeroDateTimeBehavior=convertToNull
SEVERE: Could not build Full Hibernate Plugin's Session Factory
SEVERE: org.hibernate.exception.JDBCConnectionException: Cannot open connection
 at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:99)
 at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
 at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:52)
 at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:449)
 at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:167)
 at org.hibernate.jdbc.BorrowedConnectionProxy.invoke(BorrowedConnectionProxy.java:74)
 at $Proxy146.getMetaData(Unknown Source)
 at com.googlecode.s2hibernate.struts2.plugin.util.HibernateSessionFactory.createAndTestSessionFactory(HibernateSessionFactory.java:285)
 at com.googlecode.s2hibernate.struts2.plugin.util.HibernateSessionFactory.rebuildSessionFactory(HibernateSessionFactory.java:227)
 at com.googlecode.s2hibernate.struts2.plugin.util.HibernateSessionFactory.getNewSession(HibernateSessionFactory.java:155)
 at com.googlecode.s2hibernate.struts2.plugin.util.HibernateSessionFactory.getSession(HibernateSessionFactory.java:100)
 at com.googlecode.s2hibernate.struts2.plugin.interceptors.SessionTransactionInjectorInterceptor.getHibernateSessionFromFactory(SessionTransactionInjectorInterceptor.java:379)
 at com.googlecode.s2hibernate.struts2.plugin.interceptors.SessionTransactionInjectorInterceptor.injectHibernateCoreSessionByAnnotation(SessionTransactionInjectorInterceptor.java:454)
 at com.googlecode.s2hibernate.struts2.plugin.interceptors.SessionTransactionInjectorInterceptor.injectHibernateCoreSessionByAnnotation(SessionTransactionInjectorInterceptor.java:470)
 at com.googlecode.s2hibernate.struts2.plugin.interceptors.SessionTransactionInjectorInterceptor.intercept(SessionTransactionInjectorInterceptor.java:165)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:163)
 at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
 at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:148)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:93)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:128)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at org.apache.struts2.interceptor.ProfilingActivationInterceptor.intercept(ProfilingActivationInterceptor.java:104)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:148)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138)
 at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:128)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
 at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:468)
 at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
 at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:76)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
 at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
 at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
 at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
 at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
 at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
 at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
 at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
 at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
 at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
 at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
 at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
 at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
 at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
 at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
 at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
 at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
 at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
 at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
 at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
 at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
 at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
 at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
 at java.lang.Thread.run(Thread.java:680)
Caused by: java.sql.SQLException: No suitable driver found for jdbc:mysql://ns1:3306/springlessons?zeroDateTimeBehavior=convertToNull
 at java.sql.DriverManager.getConnection(DriverManager.java:602)
 at java.sql.DriverManager.getConnection(DriverManager.java:154)
 at org.hibernate.connection.DriverManagerConnectionProvider.getConnec
SEVERE: tion(DriverManagerConnectionProvider.java:133)
 at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:446)
 ... 76 more

SEVERE: Error! Please, check your JDBC/JDNI Configurations and Database Server avaliability. 
 at /listContatoAction - Method: com.springlesson09.service.ContatoSpringAction.listcontato()
 Could not open or inject a Hibernate Session in ValueStack: org.hibernate.exception.JDBCConnectionException: Cannot open connection
SEVERE: com.googlecode.s2hibernate.lang.BuildSessionFactoryException: org.hibernate.exception.JDBCConnectionException: Cannot open connection
 at com.googlecode.s2hibernate.struts2.plugin.util.HibernateSessionFactory.rebuildSessionFactory(HibernateSessionFactory.java:246)
 at com.googlecode.s2hibernate.struts2.plugin.util.HibernateSessionFactory.getNewSession(HibernateSessionFactory.java:155)
 at com.googlecode.s2hibernate.struts2.plugin.util.HibernateSessionFactory.getSession(HibernateSessionFactory.java:100)
 at com.googlecode.s2hibernate.struts2.plugin.interceptors.SessionTransactionInjectorInterceptor.getHibernateSessionFromFactory(SessionTransactionInjectorInterceptor.java:379)
 at com.googlecode.s2hibernate.struts2.plugin.interceptors.SessionTransactionInjectorInterceptor.injectHibernateCoreSessionByAnnotation(SessionTransactionInjectorInterceptor.java:454)
 at com.googlecode.s2hibernate.struts2.plugin.interceptors.SessionTransactionInjectorInterceptor.injectHibernateCoreSessionByAnnotation(SessionTransactionInjectorInterceptor.java:470)
 at com.googlecode.s2hibernate.struts2.plugin.interceptors.SessionTransactionInjectorInterceptor.intercept(SessionTransactionInjectorInterceptor.java:165)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:163)
 at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
 at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:148)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:93)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:128)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at org.apache.struts2.interceptor.ProfilingActivationInterceptor.intercept(ProfilingActivationInterceptor.java:104)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:148)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138)
 at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:128)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176)
 at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
 at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
 at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:468)
 at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
 at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:76)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
 at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
 at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
 at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
 at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
 at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
 at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
 at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
 at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
 at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
 at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
 at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
 at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
 at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
 at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
 at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
 at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
 at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
 at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
 at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
 at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
 at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
 at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
 at java.lang.Thread.run(Thread.java:680)
Caused by: org.hibernate.exception.JDBCConnectionException: Cannot open connection
 at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:99)
 at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
 at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:52)
 at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:449)
 at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:167)
 at org.hibernate.jdbc.BorrowedConnectionProxy.invoke(BorrowedConnectionProxy.java:74)
 at $Proxy146.getMetaData(Unknown Source)
 at com.googlecode.s2hibernate.struts2.plugin.util.HibernateSessionFactory.createAndTestSessionFactory(HibernateSessionFactory.java:285)
 at com.googlecode.s2hibernate.struts2.plugin.util.HibernateSessionFactory.rebuildSessionFactory(HibernateSessionFactory.java:227)
 ... 71 more
Caused by: java.sql.SQLException: No suitable
SEVERE:  driver found for jdbc:mysql://ns1:3306/springlessons?zeroDateTimeBehavior=convertToNull
 at java.sql.DriverManager.getConnection(DriverManager.java:602)
 at java.sql.DriverManager.getConnection(DriverManager.java:154)
 at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:133)
 at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:446)
 ... 76 more

INFO: Domain Pinged: stable.glassfish.org
WARNING: PWC4011: Unable to set request character encoding to UTF-8 from context /SpringLesson09-v2, because request parameters have already been read, or ServletRequest.getReader() has already been called



Download do projeto NB
SpringLesson09-v2.3.zip





Resumo, o que vimos :



- Aprendemos a conectar no Mysql pelo NB e armazenar um driver

- Aprendemos a utilizar e configurar o Hibernate pelo NB

- Aprendemos a fazer a engenharia reversa das tabelas do banco para as configurações do Hibernate gerando os arquivos de para os mappings: Hibernate Mapping

na versão V1:

- Implementar o Struts 2.1.6

- Criamos uma interface contatoDAO

- Implementamos a interface com a classe ContatoDaoImpl

- Criamos uma interface de Serviço ContatoAction que extende com.opensymphony.xwork2.ActionSupport.ActionSupport implementando ModelDriven

- Definimos as actions e mappings no arquivo struts-config.xml e web.xml

- Removemos as libs repetidas adicionadas pelo NB

- Implementamos a interface &nbsp;com a classe ContatoServiceImpl

- Criamos as classes p/ atender os actions que são mapeados no arquivo struts.xml, que extendem a classe org.apache.struts.action.Action

- Definimos as actions e mappings no arquivo struts.xml

- Criamos uma view através de um arquivo index.jsp







na versão V2:

- Habilitamos o módulo APR no TomCat

- introduzimos o &nbsp;Full Hibernate Plugin's Session Factory

- introduzimos o conceito de BO (Business Objects)

- Criamos uma interface de Serviço ContatoSpringAction que extende com.opensymphony.xwork2.ActionSupport.ActionSupport

- Externalizamos as credenciais do banco em um arquivo.properties

- Implementamos os Beans no applicationContext.xml para o Spring poder utilizar seus recursos de Injeção de dependências

- Aprendemos a usar as anotações do HB Transactional e Session

- Criamos uma vier p/ mostrar os erros

- Integramos o Spring 3 com o Struts 2 e delegamos a responsabilidade dos beans p/ serem gerenciados pelo Spring

- Vimos nos logs a ordem em que as classes são instanciadas e como localizar erros

- Testamos os cadastro e vimos funcionando






Vamos implementar as funcionalidades do Sistema que fizemos com Swing na lição 7, mas melhorando nossa interface utilizando outros recursos como facelets,richFaces, etc..



Dúvidas, Contribuições, Sugestões? Poste..
Grato,
Até a próxima.