Problema em mostrar o DatePicker - FJ21

[quote=remofurlanetto][quote=robertoMoraes]vai ter q remontar sua tag
fica assim:

adicione o atributo value para receber da lista

<%@tag description="calendario" pageEncoding="UTF-8"%>

<%-- The list of normal or fragment attributes can be specified here: --%>

<%@attribute name="id" required="true" %>
<%@attribute name="value" required="true" %>


<script type="text/javascript">
    $(function() {
    $("#${id}").datepicker({dateFormat: 'dd/mm/yy'});
    $("#${value}").datepicker({dateFormat: 'dd/mm/yy'});
    });
</script>
    <input type="text" id="${id}" name="${id}" value="${value}"  />

depois para chamar a tag:

                                                                                    
<label>Validade: <rm:calendario_tag id="data_validade" value="${param.data_validade}" /></label>

lembrando confira no seu head se os caminhos estao certos para a jquery[/quote]

Roberto,

O passo que você informou funciona. mas quando minha data recuperada do banco de dados é mostrada no input do JSP é mostrada desformatada (Exemplo: Fri Mar 09 00:00:00 BRT 2012). Saberia resolver esse problema?

Em minha tag está setado para usar o o formato dd/mm/yy, mas a impressão que tenho é como se essa formatação não tivesse fazendo diferença.

Estou usando mysql.

Obrigado![/quote]

Bom dia,

Posta o seu código, amigo!

[]'s

Ok, segue abaixo:

Estou me baseando pela apostila FJ21 da Caelum.

Acesso a lista através da action listarClientes que executa a query no banco de dados e retorna a lista no JSP listar-clientes.jsp.

Através deste JSP eu clico no botão para alterar/mostrar o cliente (Action: mostrarCliente) e então o JSP mostrar-cliente.jsp é populado com os dados (cada value dos inputs são populados).

O JSP que está vindo com a data desformatada é a Data de Nascimento:

listar-clientes.jsp

<%--
    Document   : listar-contatos
    Created on : Jul 9, 2010, 12:25:12 PM
    Author     : remofurlanetto
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.util.*, br.com.locadora.jdbc.*, br.com.locadora.dao.*, br.com.locadora.modelo.*, java.text.*"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@taglib tagdir="/WEB-INF/tags" prefix="tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
		<script type="text/javascript" src="js/jquery-ui-1.8.4.custom.min.js"></script>
        <title>Listar Clientes</title>
    </head>
    <body>
   
        <!-- importa o cabeçalho -->
        <c:import url="cabecalho.jsp" />


		<script type="text/javascript">
			function deletarCliente(id){
				$.post("excluirCliente", {'id' : id}, function(dados){
					$("#cliente-tr"+id).closest("tr").hide();
					});
			}
		</script>

        <!-- cria lista -->
        <br><br>
        <a href="/locadora/cadastrar-cliente.jsp"><img alt="" align="middle" src="images/novo.bmp" width="21" height="21" border="0" />  Novo Cliente  </a>
        <table border="1">
            <tr>
                <th>ID</th>
                <th>NOME</th>
                <th>EMAIL</th>
                <th>ENDEREÇO</th>
                <th>DATA NASCIMENTO</th>
                <th COLSPAN="2">ACOES</th>
            </tr>
            <!-- for -->
            <c:forEach items="${clientes}" var="cliente" varStatus="id" >
                <tr bgcolor="#${id.count %2 == 0 ? 'aaee88' : 'ffffff' }" id="cliente-tr${cliente.id}">
                    <td>${cliente.id}</td>
                    <td>${cliente.nome}</td>
                    
                    <td>
                        <c:if test="${not empty cliente.email}">
                            <a href="mailto:${cliente.email}">${cliente.email}</a>
                        </c:if>

                        <c:if test="${empty cliente.email}">
                            E-mail não informado
                        </c:if>
                    </td>
                    <td>${cliente.endereco}</td>
                    <td><fmt:formatDate value="${cliente.dataNascimento.time}" pattern="dd/MM/yyyy" /></td>
                    <td width="22" align="center"><a href="mostrarCliente?id=${cliente.id}"><img alt="" src="images/exibir.bmp" width="21" height="21" border="0" /></a></td>
                    <td width="22" align="center"><a href="#" onClick="deletarCliente(${cliente.id})"><img alt="" src="images/eliminar.bmp" width="21" height="21" border="0" /></a></td>
                </tr>
            </c:forEach>
        </table>

        <!-- importa o rodape -->
        <c:import url="rodape.jsp" />

    </body>
</html>

MostrarClientesAction

package br.com.locadora.action;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import br.com.locadora.dao.ClienteDAO;
import br.com.locadora.modelo.Cliente;

public class MostrarClienteAction {
	private Long id;
	private Cliente cliente;
	
	@Action(value="mostrarCliente", results={
			@Result(name="ok", location="/mostrar-cliente.jsp")
	})
	public String execute(){
		cliente = new ClienteDAO().consultarId(id);
		return "ok";
	}
	
	public void setId(Long id){
		this.id = id;
	}
	
	public Cliente getCliente(){
		return cliente;
	}
}

ClienteDAO

package br.com.locadora.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import br.com.locadora.jdbc.FabricaConexao;
import br.com.locadora.modelo.Cliente;

public class ClienteDAO {
	Connection connection;
	
	public ClienteDAO(){
		this.connection = new FabricaConexao().getConnection();
	}
	
    public void cadastrar(Cliente cliente) {
//        String sql = "insert into clientes values (seq_clientes.nextval,?,?,?,?,?,?,?,?,?,?)";
        String sql = "insert into clientes (nome,endereco,bairro,cidade,uf,cep,telres,telcel,email,datanascimento) values (?,?,?,?,?,?,?,?,?,?)";


        try {
            // prepared statement para cadastro
            PreparedStatement stmt = connection.prepareStatement(sql);

            // seta os valores
            stmt.setString(1, cliente.getNome());
            stmt.setString(2, cliente.getEndereco());
            stmt.setString(3, cliente.getBairro());
            stmt.setString(4, cliente.getCidade());
            stmt.setString(5, cliente.getUf());
            stmt.setString(6, cliente.getCep());
            stmt.setString(7, cliente.getTelres());
            stmt.setString(8, cliente.getTelcel());
            stmt.setString(9, cliente.getEmail());
            
            if(cliente.getDataNascimento() == null) {
            	stmt.setNull(10, java.sql.Types.DATE);
            }
            else {
            	stmt.setDate(10, new java.sql.Date( cliente.getDataNascimento().getTimeInMillis() ));
            }
            
            // executa
            System.out.println("Executando query ... " + stmt);
            stmt.execute();
            stmt.close();
            connection.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public List<Cliente> listar() {

        try {
            List<Cliente> clientes = new ArrayList<Cliente>();
 //          PreparedStatement stmt = this.connection.prepareStatement("select * from clientes");
           PreparedStatement stmt = this.connection.prepareStatement("select * from clientes");
            // executa um select
            ResultSet rs = stmt.executeQuery();

            // itera no ResulSet
            while (rs.next()) {
                // criando o objeto Contato
                Cliente cliente = new Cliente();
                cliente.setId(rs.getLong("id"));
                cliente.setNome(rs.getString("nome"));
                cliente.setEndereco(rs.getString("endereco"));
                cliente.setBairro(rs.getString("bairro"));
                cliente.setCidade(rs.getString("cidade"));
                cliente.setUf(rs.getString("uf"));
                cliente.setCep(rs.getString("cep"));
                cliente.setTelres(rs.getString("telres"));
                cliente.setTelcel(rs.getString("telcel"));
                cliente.setEmail(rs.getString("email"));

				if(rs.getDate("dataNascimento") != null)
				{
	                //montando a data atraves do Calendar
	                Calendar data = Calendar.getInstance();
	                data.setTime(rs.getDate("dataNascimento"));
	                cliente.setDataNascimento(data);
				}

                // adicionando o objeto à lista
                clientes.add(cliente);
            }

            // executa
            System.out.println("Executando query ... " + stmt);
            stmt.execute();
            stmt.close();
            connection.close();
            return clientes;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public Cliente consultarId(Long id) {
//        String sql = "select * from clientes where id =?";
       String sql = "select * from clientes";

        try {
        	PreparedStatement stmt = this.connection.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery();

			while(rs.next())
			{
				//System.out.println(rs.getLong("id")+ " // " + id);
				if(id == rs.getLong("id"))
				{
		            // criando o objeto Cliente
		            Cliente cliente = new Cliente();
	                cliente.setId(rs.getLong("id"));
	                cliente.setNome(rs.getString("nome"));
	                cliente.setEndereco(rs.getString("endereco"));
	                cliente.setBairro(rs.getString("bairro"));
	                cliente.setCidade(rs.getString("cidade"));
	                cliente.setUf(rs.getString("uf"));
	                cliente.setCep(rs.getString("cep"));
	                cliente.setTelres(rs.getString("telres"));
	                cliente.setTelcel(rs.getString("telcel"));
	                cliente.setEmail(rs.getString("email"));

					if(rs.getDate("dataNascimento") != null)
					{
		                //montando a data atraves do Calendar
		                Calendar data = Calendar.getInstance();
		                data.setTime(rs.getDate("dataNascimento"));
		                cliente.setDataNascimento(data);
					}
					System.out.println("consulta por cliente.ID: " + cliente.getId());
					return cliente;
				}
			}
				return null;
			}catch(SQLException e){
				throw new RuntimeException(e);
			}	
    }

    public void alterar(Cliente cliente) {
//        String sql = "update clientes set nome=?, email=?, endereco=?, dataNascimento=? where id=?";
        String sql = "update clientes set nome=?, email=?, endereco=?, dataNascimento=? where id=?";

        try {
            PreparedStatement stmt = connection.prepareStatement(sql);
            stmt.setString(1, cliente.getNome());
            stmt.setString(2, cliente.getEmail());
            stmt.setString(3, cliente.getEndereco());
            
            if(cliente.getDataNascimento() == null) {
            	stmt.setNull(4, java.sql.Types.DATE);
            }
            else {
            	stmt.setDate(4, new java.sql.Date( cliente.getDataNascimento().getTimeInMillis() ));
            }
            stmt.setLong(5, cliente.getId());
            // executa
            System.out.println("Executando query ... " + stmt);
            stmt.execute();
            stmt.close();
            connection.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public void excluir(Cliente cliente) {
        try {
//            PreparedStatement stmt = connection.prepareStatement("delete from clientes where id=?");
            PreparedStatement stmt = connection.prepareStatement("delete from clientes where id=?");
            stmt.setLong(1, cliente.getId());
            // executa
            System.out.println("Executando query ... " + stmt);
            stmt.execute();
            stmt.close();

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
	

mostrar-cliente.jsp


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@taglib tagdir="/WEB-INF/tags" prefix="tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
   
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<link type="text/css" href="css/ui-lightness/jquery-ui-1.8.4.custom.css" rel="stylesheet" />
		<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
		<script type="text/javascript" src="js/jquery-ui-1.8.4.custom.min.js"></script>
    </head>
    <body>
		<!-- importa o cabeçalho -->
		<c:import url="cabecalho.jsp" />
		
		<h3>Alterar Cliente ID: ${cliente.id}</h3>
		
		<form action="alterarCliente" method="POST">
			<input type="hidden" name="cliente.id" value="${cliente.id}"/>
		    Nome: <input type="text" name="cliente.nome" value="${cliente.nome}"/><br/>
		    E-mail: <input type="text" name="cliente.email" value="${cliente.email}"/><br/>
		    Endereço: <input type="text" name="cliente.endereco" value="${cliente.endereco}"/><br/>
		    Data de Nascimento: <tags:campoData_value id="dataNascimento" value="${cliente.dataNascimento.date}"/><br />

		    <br/>
		    <input type="submit" value="Alterar"/>
		</form>
		
		<!-- importa o rodape -->
		<c:import url="rodape.jsp" />
    </body>
</html>

campoData_value.tag

<%-- 
    Document   : campoData
    Created on : Aug 22, 2010, 12:07:51 PM
    Author     : remofurlanetto
--%>

<%@tag description="datapicker" pageEncoding="UTF-8"%>

<%-- The list of normal or fragment attributes can be specified here: --%>
<%@attribute name="id" required="true" %>
<%@attribute name="value" required="true" %>  

<script type="text/javascript">  
    $(function() {  
    $("#${id}").datepicker({dateFormat: 'dd/mm/yy'});  
    $("#${value}").datepicker({dateFormat: 'dd/mm/yy'});  
    });  
</script>  
    

<%-- any content can be specified here e.g.: --%>
<input type="text" id="${id}" name="${id}" value="${value}"  />  

Leonardo,

Você deve “descer um nível” (…/) na chamada dos arquivos do jquery, imagens e imports, conforme exemplo abaixo:

<%--
    Document   : cadastrar-cliente
    Created on : Jul 9, 2010, 12:36:49 AM
    Author     : remofurlanetto
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib tagdir="/WEB-INF/tags" prefix="tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link type="text/css" href="../css/ui-lightness/jquery-ui-1.8.4.custom.css" rel="stylesheet" />
        <script type="text/javascript" src="../js/jquery-1.4.2.min.js"></script>
        <script type="text/javascript" src="../js/jquery-ui-1.8.4.custom.min.js"></script>        
        <title>Cadastro</title>
        <script type="text/javascript">
            $(function() {
                // Accordion
                $("#accordion-cliente").accordion({ header: "h3" });

                // Tabs
                $('#tabs').tabs();
            })
        </script>
		<script>
		$(function() {
			$( "#datepicker" ).datepicker({
				showOn: "button",
				buttonImage: "../images/calendar.gif",
				buttonImageOnly: true
			});
		});
		</script>
        
	<style type="text/css">
	<!--
	.style1 {font-size: 12px}
	.style3 {font-size: 14px; font-weight: bold; }
	.style5 {font-size: 24px; font-weight: bold; }
	-->
	</style> 
    </head>
  <body>
        <!-- importa o cabeçalho -->
        <c:import url="../cabecalho.jsp" />
<!-- 		<div id="accordion-cliente"> -->
			<h3><a href="#">Cadastro</a></h3>
	        <form action="cadastrarCliente" method="POST">
	            Nome: <input type="text" name="cliente.nome" /><br/>
	            E-mail: <input type="text" name="cliente.email" /><br/>
	            Endereço: <input type="text" name="cliente.endereco" /><br/>
	            Data de Nascimento: <tags:campoData id="dataNascimento" /><br />
				Date: <input type="text" id="datepicker" ><br />
	            <input type="submit" value="Gravar"/>
	        </form>
<!--        </div> -->
        <!-- importa o rodape -->
        <c:import url="../rodape.jsp" />
  </body>
</html>

Olá. Obrigado pela resposta.

Estou implementando a apostila do zero, novamente. Como precisava aprender outros frameworks para o projeto que estou envolvido, deixei o estudo da FJ21 um pouco de lado.

Mas de qualquer forma, te agradeço pela ajuda.

Abraço!

Alguem poderia me ajduar com o problema que eu tinha postado? (minha citação)

Obrigado!

Remo

[quote=remofurlanetto]Ok, segue abaixo:

Estou me baseando pela apostila FJ21 da Caelum.

Acesso a lista através da action listarClientes que executa a query no banco de dados e retorna a lista no JSP listar-clientes.jsp.

Através deste JSP eu clico no botão para alterar/mostrar o cliente (Action: mostrarCliente) e então o JSP mostrar-cliente.jsp é populado com os dados (cada value dos inputs são populados).

O JSP que está vindo com a data desformatada é a Data de Nascimento:

listar-clientes.jsp

<%--
    Document   : listar-contatos
    Created on : Jul 9, 2010, 12:25:12 PM
    Author     : remofurlanetto
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.util.*, br.com.locadora.jdbc.*, br.com.locadora.dao.*, br.com.locadora.modelo.*, java.text.*"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@taglib tagdir="/WEB-INF/tags" prefix="tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
		<script type="text/javascript" src="js/jquery-ui-1.8.4.custom.min.js"></script>
        <title>Listar Clientes</title>
    </head>
    <body>
   
        <!-- importa o cabeçalho -->
        <c:import url="cabecalho.jsp" />


		<script type="text/javascript">
			function deletarCliente(id){
				$.post("excluirCliente", {'id' : id}, function(dados){
					$("#cliente-tr"+id).closest("tr").hide();
					});
			}
		</script>

        <!-- cria lista -->
        <br><br>
        <a href="/locadora/cadastrar-cliente.jsp"><img alt="" align="middle" src="images/novo.bmp" width="21" height="21" border="0" />  Novo Cliente  </a>
        <table border="1">
            <tr>
                <th>ID</th>
                <th>NOME</th>
                <th>EMAIL</th>
                <th>ENDEREÇO</th>
                <th>DATA NASCIMENTO</th>
                <th COLSPAN="2">ACOES</th>
            </tr>
            <!-- for -->
            <c:forEach items="${clientes}" var="cliente" varStatus="id" >
                <tr bgcolor="#${id.count %2 == 0 ? 'aaee88' : 'ffffff' }" id="cliente-tr${cliente.id}">
                    <td>${cliente.id}</td>
                    <td>${cliente.nome}</td>
                    
                    <td>
                        <c:if test="${not empty cliente.email}">
                            <a href="mailto:${cliente.email}">${cliente.email}</a>
                        </c:if>

                        <c:if test="${empty cliente.email}">
                            E-mail não informado
                        </c:if>
                    </td>
                    <td>${cliente.endereco}</td>
                    <td><fmt:formatDate value="${cliente.dataNascimento.time}" pattern="dd/MM/yyyy" /></td>
                    <td width="22" align="center"><a href="mostrarCliente?id=${cliente.id}"><img alt="" src="images/exibir.bmp" width="21" height="21" border="0" /></a></td>
                    <td width="22" align="center"><a href="#" onClick="deletarCliente(${cliente.id})"><img alt="" src="images/eliminar.bmp" width="21" height="21" border="0" /></a></td>
                </tr>
            </c:forEach>
        </table>

        <!-- importa o rodape -->
        <c:import url="rodape.jsp" />

    </body>
</html>

MostrarClientesAction

package br.com.locadora.action;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import br.com.locadora.dao.ClienteDAO;
import br.com.locadora.modelo.Cliente;

public class MostrarClienteAction {
	private Long id;
	private Cliente cliente;
	
	@Action(value="mostrarCliente", results={
			@Result(name="ok", location="/mostrar-cliente.jsp")
	})
	public String execute(){
		cliente = new ClienteDAO().consultarId(id);
		return "ok";
	}
	
	public void setId(Long id){
		this.id = id;
	}
	
	public Cliente getCliente(){
		return cliente;
	}
}

ClienteDAO

package br.com.locadora.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import br.com.locadora.jdbc.FabricaConexao;
import br.com.locadora.modelo.Cliente;

public class ClienteDAO {
	Connection connection;
	
	public ClienteDAO(){
		this.connection = new FabricaConexao().getConnection();
	}
	
    public void cadastrar(Cliente cliente) {
//        String sql = "insert into clientes values (seq_clientes.nextval,?,?,?,?,?,?,?,?,?,?)";
        String sql = "insert into clientes (nome,endereco,bairro,cidade,uf,cep,telres,telcel,email,datanascimento) values (?,?,?,?,?,?,?,?,?,?)";


        try {
            // prepared statement para cadastro
            PreparedStatement stmt = connection.prepareStatement(sql);

            // seta os valores
            stmt.setString(1, cliente.getNome());
            stmt.setString(2, cliente.getEndereco());
            stmt.setString(3, cliente.getBairro());
            stmt.setString(4, cliente.getCidade());
            stmt.setString(5, cliente.getUf());
            stmt.setString(6, cliente.getCep());
            stmt.setString(7, cliente.getTelres());
            stmt.setString(8, cliente.getTelcel());
            stmt.setString(9, cliente.getEmail());
            
            if(cliente.getDataNascimento() == null) {
            	stmt.setNull(10, java.sql.Types.DATE);
            }
            else {
            	stmt.setDate(10, new java.sql.Date( cliente.getDataNascimento().getTimeInMillis() ));
            }
            
            // executa
            System.out.println("Executando query ... " + stmt);
            stmt.execute();
            stmt.close();
            connection.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public List<Cliente> listar() {

        try {
            List<Cliente> clientes = new ArrayList<Cliente>();
 //          PreparedStatement stmt = this.connection.prepareStatement("select * from clientes");
           PreparedStatement stmt = this.connection.prepareStatement("select * from clientes");
            // executa um select
            ResultSet rs = stmt.executeQuery();

            // itera no ResulSet
            while (rs.next()) {
                // criando o objeto Contato
                Cliente cliente = new Cliente();
                cliente.setId(rs.getLong("id"));
                cliente.setNome(rs.getString("nome"));
                cliente.setEndereco(rs.getString("endereco"));
                cliente.setBairro(rs.getString("bairro"));
                cliente.setCidade(rs.getString("cidade"));
                cliente.setUf(rs.getString("uf"));
                cliente.setCep(rs.getString("cep"));
                cliente.setTelres(rs.getString("telres"));
                cliente.setTelcel(rs.getString("telcel"));
                cliente.setEmail(rs.getString("email"));

				if(rs.getDate("dataNascimento") != null)
				{
	                //montando a data atraves do Calendar
	                Calendar data = Calendar.getInstance();
	                data.setTime(rs.getDate("dataNascimento"));
	                cliente.setDataNascimento(data);
				}

                // adicionando o objeto à lista
                clientes.add(cliente);
            }

            // executa
            System.out.println("Executando query ... " + stmt);
            stmt.execute();
            stmt.close();
            connection.close();
            return clientes;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public Cliente consultarId(Long id) {
//        String sql = "select * from clientes where id =?";
       String sql = "select * from clientes";

        try {
        	PreparedStatement stmt = this.connection.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery();

			while(rs.next())
			{
				//System.out.println(rs.getLong("id")+ " // " + id);
				if(id == rs.getLong("id"))
				{
		            // criando o objeto Cliente
		            Cliente cliente = new Cliente();
	                cliente.setId(rs.getLong("id"));
	                cliente.setNome(rs.getString("nome"));
	                cliente.setEndereco(rs.getString("endereco"));
	                cliente.setBairro(rs.getString("bairro"));
	                cliente.setCidade(rs.getString("cidade"));
	                cliente.setUf(rs.getString("uf"));
	                cliente.setCep(rs.getString("cep"));
	                cliente.setTelres(rs.getString("telres"));
	                cliente.setTelcel(rs.getString("telcel"));
	                cliente.setEmail(rs.getString("email"));

					if(rs.getDate("dataNascimento") != null)
					{
		                //montando a data atraves do Calendar
		                Calendar data = Calendar.getInstance();
		                data.setTime(rs.getDate("dataNascimento"));
		                cliente.setDataNascimento(data);
					}
					System.out.println("consulta por cliente.ID: " + cliente.getId());
					return cliente;
				}
			}
				return null;
			}catch(SQLException e){
				throw new RuntimeException(e);
			}	
    }

    public void alterar(Cliente cliente) {
//        String sql = "update clientes set nome=?, email=?, endereco=?, dataNascimento=? where id=?";
        String sql = "update clientes set nome=?, email=?, endereco=?, dataNascimento=? where id=?";

        try {
            PreparedStatement stmt = connection.prepareStatement(sql);
            stmt.setString(1, cliente.getNome());
            stmt.setString(2, cliente.getEmail());
            stmt.setString(3, cliente.getEndereco());
            
            if(cliente.getDataNascimento() == null) {
            	stmt.setNull(4, java.sql.Types.DATE);
            }
            else {
            	stmt.setDate(4, new java.sql.Date( cliente.getDataNascimento().getTimeInMillis() ));
            }
            stmt.setLong(5, cliente.getId());
            // executa
            System.out.println("Executando query ... " + stmt);
            stmt.execute();
            stmt.close();
            connection.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public void excluir(Cliente cliente) {
        try {
//            PreparedStatement stmt = connection.prepareStatement("delete from clientes where id=?");
            PreparedStatement stmt = connection.prepareStatement("delete from clientes where id=?");
            stmt.setLong(1, cliente.getId());
            // executa
            System.out.println("Executando query ... " + stmt);
            stmt.execute();
            stmt.close();

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
	

mostrar-cliente.jsp


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@taglib tagdir="/WEB-INF/tags" prefix="tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
   
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<link type="text/css" href="css/ui-lightness/jquery-ui-1.8.4.custom.css" rel="stylesheet" />
		<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
		<script type="text/javascript" src="js/jquery-ui-1.8.4.custom.min.js"></script>
    </head>
    <body>
		<!-- importa o cabeçalho -->
		<c:import url="cabecalho.jsp" />
		
		<h3>Alterar Cliente ID: ${cliente.id}</h3>
		
		<form action="alterarCliente" method="POST">
			<input type="hidden" name="cliente.id" value="${cliente.id}"/>
		    Nome: <input type="text" name="cliente.nome" value="${cliente.nome}"/><br/>
		    E-mail: <input type="text" name="cliente.email" value="${cliente.email}"/><br/>
		    Endereço: <input type="text" name="cliente.endereco" value="${cliente.endereco}"/><br/>
		    Data de Nascimento: <tags:campoData_value id="dataNascimento" value="${cliente.dataNascimento.date}"/><br />

		    <br/>
		    <input type="submit" value="Alterar"/>
		</form>
		
		<!-- importa o rodape -->
		<c:import url="rodape.jsp" />
    </body>
</html>

campoData_value.tag

[code]
<%–
Document : campoData
Created on : Aug 22, 2010, 12:07:51 PM
Author : remofurlanetto
–%>

<%@tag description=“datapicker” pageEncoding=“UTF-8”%>

<%-- The list of normal or fragment attributes can be specified here: --%>
<%@attribute name=“id” required=“true” %>
<%@attribute name=“value” required=“true” %>

<%-- any content can be specified here e.g.: --%>

[/code][/quote]

arranjei uma solução mas o script tem q ficar na pagina e não em um arquivo separado

[quote=remofurlanetto]Alguem poderia me ajduar com o problema que eu tinha postado? (minha citação)

Obrigado!

Remo

[quote=remofurlanetto]Ok, segue abaixo:

Estou me baseando pela apostila FJ21 da Caelum.

Acesso a lista através da action listarClientes que executa a query no banco de dados e retorna a lista no JSP listar-clientes.jsp.

Através deste JSP eu clico no botão para alterar/mostrar o cliente (Action: mostrarCliente) e então o JSP mostrar-cliente.jsp é populado com os dados (cada value dos inputs são populados).

O JSP que está vindo com a data desformatada é a Data de Nascimento:

listar-clientes.jsp

<%--
    Document   : listar-contatos
    Created on : Jul 9, 2010, 12:25:12 PM
    Author     : remofurlanetto
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.util.*, br.com.locadora.jdbc.*, br.com.locadora.dao.*, br.com.locadora.modelo.*, java.text.*"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@taglib tagdir="/WEB-INF/tags" prefix="tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
		<script type="text/javascript" src="js/jquery-ui-1.8.4.custom.min.js"></script>
        <title>Listar Clientes</title>
    </head>
    <body>
   
        <!-- importa o cabeçalho -->
        <c:import url="cabecalho.jsp" />


		<script type="text/javascript">
			function deletarCliente(id){
				$.post("excluirCliente", {'id' : id}, function(dados){
					$("#cliente-tr"+id).closest("tr").hide();
					});
			}
		</script>

        <!-- cria lista -->
        <br><br>
        <a href="/locadora/cadastrar-cliente.jsp"><img alt="" align="middle" src="images/novo.bmp" width="21" height="21" border="0" />  Novo Cliente  </a>
        <table border="1">
            <tr>
                <th>ID</th>
                <th>NOME</th>
                <th>EMAIL</th>
                <th>ENDEREÇO</th>
                <th>DATA NASCIMENTO</th>
                <th COLSPAN="2">ACOES</th>
            </tr>
            <!-- for -->
            <c:forEach items="${clientes}" var="cliente" varStatus="id" >
                <tr bgcolor="#${id.count %2 == 0 ? 'aaee88' : 'ffffff' }" id="cliente-tr${cliente.id}">
                    <td>${cliente.id}</td>
                    <td>${cliente.nome}</td>
                    
                    <td>
                        <c:if test="${not empty cliente.email}">
                            <a href="mailto:${cliente.email}">${cliente.email}</a>
                        </c:if>

                        <c:if test="${empty cliente.email}">
                            E-mail não informado
                        </c:if>
                    </td>
                    <td>${cliente.endereco}</td>
                    <td><fmt:formatDate value="${cliente.dataNascimento.time}" pattern="dd/MM/yyyy" /></td>
                    <td width="22" align="center"><a href="mostrarCliente?id=${cliente.id}"><img alt="" src="images/exibir.bmp" width="21" height="21" border="0" /></a></td>
                    <td width="22" align="center"><a href="#" onClick="deletarCliente(${cliente.id})"><img alt="" src="images/eliminar.bmp" width="21" height="21" border="0" /></a></td>
                </tr>
            </c:forEach>
        </table>

        <!-- importa o rodape -->
        <c:import url="rodape.jsp" />

    </body>
</html>

MostrarClientesAction

package br.com.locadora.action;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import br.com.locadora.dao.ClienteDAO;
import br.com.locadora.modelo.Cliente;

public class MostrarClienteAction {
	private Long id;
	private Cliente cliente;
	
	@Action(value="mostrarCliente", results={
			@Result(name="ok", location="/mostrar-cliente.jsp")
	})
	public String execute(){
		cliente = new ClienteDAO().consultarId(id);
		return "ok";
	}
	
	public void setId(Long id){
		this.id = id;
	}
	
	public Cliente getCliente(){
		return cliente;
	}
}

ClienteDAO

package br.com.locadora.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import br.com.locadora.jdbc.FabricaConexao;
import br.com.locadora.modelo.Cliente;

public class ClienteDAO {
	Connection connection;
	
	public ClienteDAO(){
		this.connection = new FabricaConexao().getConnection();
	}
	
    public void cadastrar(Cliente cliente) {
//        String sql = "insert into clientes values (seq_clientes.nextval,?,?,?,?,?,?,?,?,?,?)";
        String sql = "insert into clientes (nome,endereco,bairro,cidade,uf,cep,telres,telcel,email,datanascimento) values (?,?,?,?,?,?,?,?,?,?)";


        try {
            // prepared statement para cadastro
            PreparedStatement stmt = connection.prepareStatement(sql);

            // seta os valores
            stmt.setString(1, cliente.getNome());
            stmt.setString(2, cliente.getEndereco());
            stmt.setString(3, cliente.getBairro());
            stmt.setString(4, cliente.getCidade());
            stmt.setString(5, cliente.getUf());
            stmt.setString(6, cliente.getCep());
            stmt.setString(7, cliente.getTelres());
            stmt.setString(8, cliente.getTelcel());
            stmt.setString(9, cliente.getEmail());
            
            if(cliente.getDataNascimento() == null) {
            	stmt.setNull(10, java.sql.Types.DATE);
            }
            else {
            	stmt.setDate(10, new java.sql.Date( cliente.getDataNascimento().getTimeInMillis() ));
            }
            
            // executa
            System.out.println("Executando query ... " + stmt);
            stmt.execute();
            stmt.close();
            connection.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public List<Cliente> listar() {

        try {
            List<Cliente> clientes = new ArrayList<Cliente>();
 //          PreparedStatement stmt = this.connection.prepareStatement("select * from clientes");
           PreparedStatement stmt = this.connection.prepareStatement("select * from clientes");
            // executa um select
            ResultSet rs = stmt.executeQuery();

            // itera no ResulSet
            while (rs.next()) {
                // criando o objeto Contato
                Cliente cliente = new Cliente();
                cliente.setId(rs.getLong("id"));
                cliente.setNome(rs.getString("nome"));
                cliente.setEndereco(rs.getString("endereco"));
                cliente.setBairro(rs.getString("bairro"));
                cliente.setCidade(rs.getString("cidade"));
                cliente.setUf(rs.getString("uf"));
                cliente.setCep(rs.getString("cep"));
                cliente.setTelres(rs.getString("telres"));
                cliente.setTelcel(rs.getString("telcel"));
                cliente.setEmail(rs.getString("email"));

				if(rs.getDate("dataNascimento") != null)
				{
	                //montando a data atraves do Calendar
	                Calendar data = Calendar.getInstance();
	                data.setTime(rs.getDate("dataNascimento"));
	                cliente.setDataNascimento(data);
				}

                // adicionando o objeto à lista
                clientes.add(cliente);
            }

            // executa
            System.out.println("Executando query ... " + stmt);
            stmt.execute();
            stmt.close();
            connection.close();
            return clientes;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public Cliente consultarId(Long id) {
//        String sql = "select * from clientes where id =?";
       String sql = "select * from clientes";

        try {
        	PreparedStatement stmt = this.connection.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery();

			while(rs.next())
			{
				//System.out.println(rs.getLong("id")+ " // " + id);
				if(id == rs.getLong("id"))
				{
		            // criando o objeto Cliente
		            Cliente cliente = new Cliente();
	                cliente.setId(rs.getLong("id"));
	                cliente.setNome(rs.getString("nome"));
	                cliente.setEndereco(rs.getString("endereco"));
	                cliente.setBairro(rs.getString("bairro"));
	                cliente.setCidade(rs.getString("cidade"));
	                cliente.setUf(rs.getString("uf"));
	                cliente.setCep(rs.getString("cep"));
	                cliente.setTelres(rs.getString("telres"));
	                cliente.setTelcel(rs.getString("telcel"));
	                cliente.setEmail(rs.getString("email"));

					if(rs.getDate("dataNascimento") != null)
					{
		                //montando a data atraves do Calendar
		                Calendar data = Calendar.getInstance();
		                data.setTime(rs.getDate("dataNascimento"));
		                cliente.setDataNascimento(data);
					}
					System.out.println("consulta por cliente.ID: " + cliente.getId());
					return cliente;
				}
			}
				return null;
			}catch(SQLException e){
				throw new RuntimeException(e);
			}	
    }

    public void alterar(Cliente cliente) {
//        String sql = "update clientes set nome=?, email=?, endereco=?, dataNascimento=? where id=?";
        String sql = "update clientes set nome=?, email=?, endereco=?, dataNascimento=? where id=?";

        try {
            PreparedStatement stmt = connection.prepareStatement(sql);
            stmt.setString(1, cliente.getNome());
            stmt.setString(2, cliente.getEmail());
            stmt.setString(3, cliente.getEndereco());
            
            if(cliente.getDataNascimento() == null) {
            	stmt.setNull(4, java.sql.Types.DATE);
            }
            else {
            	stmt.setDate(4, new java.sql.Date( cliente.getDataNascimento().getTimeInMillis() ));
            }
            stmt.setLong(5, cliente.getId());
            // executa
            System.out.println("Executando query ... " + stmt);
            stmt.execute();
            stmt.close();
            connection.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public void excluir(Cliente cliente) {
        try {
//            PreparedStatement stmt = connection.prepareStatement("delete from clientes where id=?");
            PreparedStatement stmt = connection.prepareStatement("delete from clientes where id=?");
            stmt.setLong(1, cliente.getId());
            // executa
            System.out.println("Executando query ... " + stmt);
            stmt.execute();
            stmt.close();

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
	

mostrar-cliente.jsp


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@taglib tagdir="/WEB-INF/tags" prefix="tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
   
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<link type="text/css" href="css/ui-lightness/jquery-ui-1.8.4.custom.css" rel="stylesheet" />
		<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
		<script type="text/javascript" src="js/jquery-ui-1.8.4.custom.min.js"></script>
    </head>
    <body>
		<!-- importa o cabeçalho -->
		<c:import url="cabecalho.jsp" />
		
		<h3>Alterar Cliente ID: ${cliente.id}</h3>
		
		<form action="alterarCliente" method="POST">
			<input type="hidden" name="cliente.id" value="${cliente.id}"/>
		    Nome: <input type="text" name="cliente.nome" value="${cliente.nome}"/><br/>
		    E-mail: <input type="text" name="cliente.email" value="${cliente.email}"/><br/>
		    Endereço: <input type="text" name="cliente.endereco" value="${cliente.endereco}"/><br/>
		    Data de Nascimento: <tags:campoData_value id="dataNascimento" value="${cliente.dataNascimento.date}"/><br />

		    <br/>
		    <input type="submit" value="Alterar"/>
		</form>
		
		<!-- importa o rodape -->
		<c:import url="rodape.jsp" />
    </body>
</html>

campoData_value.tag

<%-- 
    Document   : campoData
    Created on : Aug 22, 2010, 12:07:51 PM
    Author     : remofurlanetto
--%>

<%@tag description="datapicker" pageEncoding="UTF-8"%>

<%-- The list of normal or fragment attributes can be specified here: --%>
<%@attribute name="id" required="true" %>
<%@attribute name="value" required="true" %>  

<script type="text/javascript">  
    $(function() {  
    $("#${id}").datepicker({dateFormat: 'dd/mm/yy'});  
    $("#${value}").datepicker({dateFormat: 'dd/mm/yy'});  
    });  
</script>  
    

<%-- any content can be specified here e.g.: --%>
<input type="text" id="${id}" name="${id}" value="${value}"  />  
[/code][/quote][/quote]

lendo sobre o jquery descobrir q  a linha    $("#${value}").datepicker({dateFormat: 'dd/mm/yy'}); não serve para nada porq o jogo da velha # serve para disser q o valor se refere ao campo id ou seja ele manda fazer essa formatação nas tags q  o id for igual ao conteúdo da variável value e isso nao existe no nosso código
e o dateFormat só formata as datas setadas pelo datepicker ( o calendário q aparece quando vc clica no campo) 

minha primeira ideia foi passar [color=red]<fmt:formatDate value="${tarefa.dataFinalizacao.time}" pattern="dd/MM/yyyy" />"[/color] como  value da tag que  foi criada e a mesma não aceitava e dava erro,  acho que a tag não consegue ler a biblioteca fmt
a solução foi criar o script dentro da pagina  q mostra a tarefa e  criar um datepicker em toda tag q tenha um certo id q eu escolhi data  mas poderia ser dataNascimento

eu estou tendo esse problema no exercício de tarefas  mas  vou tentar adaptar o código para o seu problema 
cole esse código no começo da pagina jsp logo abaixo das declarações das bibliotecas dos scripts

[code]<script type="text/javascript">
	$(document).ready(function() {
		$("#data").datepicker({
			dateFormat : 'dd/mm/yy'
		});
	});
</script>[/code]

e troque o[code] <tags:campoData_value id="dataNascimento" value="${cliente.dataNascimento.date}"/><br />  [/code] por 
[code]<input type="text" id="data"
			name="dataNascimento"
			value="<fmt:formatDate value="${cliente.dataNascimento.time}" pattern="dd/MM/yyyy" />" />

essa foi a solução q encontrei mas se alguém souber como fazer isso criando uma nova tag posta ai por favor

Oi Pessoal,

no meu caso tive um problema quanto a descrição dos arquivos, contidos nas pastas js e css.
No caso baixei os arquivos diretamente no site, conforme indicado na apostila do exercício, porém meus arquivos estavam com nomes diferentes para funcionar tive que alterar a importação dos arquivos no adiciona contatos no seguinte bloco:

tive que alterar, conforme os arquivos baixados da jQuery, conforme abaixo:

<head>
	<link href="[b]css/ui-lightness/jquery-ui-1.9.2.custom.css[/b]" rel="stylesheet">
	<script src="[b]js/jquery-1.8.3.js[/b]"></script>
	<script src="[b]js/jquery-ui-1.9.2.custom.js[/b]"></script>
</head>

Grande abraço…

deu certo aqui seguindo seu exemplo tiagorv, valeu!

Fabio você poderia postar como fez a tag? baixei as mesmas versões citadas pelo @tiagorv, porém sem nenhum sucesso.

Inclusive fiz um teste no meu formulário, para chamar o datepicker direto pelo input mas também não consegui.

Se alguém puder me ajudar… eu fiz dessa forma:
`

`

<input id="dataNascimento" name="dataNascimento"> <script> $(document).ready(function() { $("#dataNascimento").datepicker(); }); </script>

Claro Diego. Vou enviar um print, acho que a visão fica mais ampla. Segue:

Já na tag campoData, está idêntico o que a apostila da Caelum instruiu.

Muito obrigado Fabio!! Fazia duas semanas que estava tentando e não conseguia de jeito nenhum!! Por fim revisando o meu código e comparando com o seu percebi que tinha um “J” a mais no nome da lib do jquery! :sleeping:
Valeu pela força!

Boa Diego. Essas paradas tiram sono, pelo menos comigo é assim :disappointed:. Ainda bem que funcionou.

Abs

Jovem, tive o mesmo problema.
Solução:

< link href=“css/jquery.css” rel=“stylesheet”>
< script src=“jquery.js”>
< script src=“jquery-ui.js”>

EXPLICAÇÃO:
Na apostila temos a seguinte situação:
"Copie os diretórios js e css e cole-os dentro do webcontente do seu projeto"
Ai a gente vai la e faz isso, certo.
Mas quando vamos passar o caminho:

< html>
< head>
< link href=“css/jquery.css” rel=“stylesheet”>
< script src=“js/jquery.js”>
< script src=“js/jquery-ui.js”>
< /head>

Temos isso: src=“js/jquery.js” e isso: src=“js/jquery-ui.js”>
Estamos dizendo que os arquivos estão na pasta js dentro da pasta webcontente.

Então, se tirarmos o js: src=“jquery.js” e “jquery-ui.js” ele deve funcionar.