Dúvida em setar campos em formulário JSP

1 resposta
C
Olá, estou desenvolvendo um sistema para meu TCC e tenho um formulário que foi criado no Dreamweaver, minha servlet já está pronta e funcionanado em outro formulário mais simples. Acontece que nesse formulário que foi gerado no Dreamweaver estou tendo dificuldades em chamar minha servlet. O processo consistem em o cliente preencher o campo "Cod Orçamento" e clicar no botão "Carregar Orçamento", com isso o formulário seria preenchido com dados em alguns campos. Meu formulário:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Vendas3</title>
<script src="Scripts/AC_RunActiveContent.js" type="text/javascript"></script>

<style type="text/css">
<!--
.style4 {color: #FFFFFF}
#apDiv1 {
	position:absolute;
	left:38px;
	top:200px;
	width:195px;
	height:703px;
	z-index:1;
}
.BMWEB {
	font-size: 9px;
	font-family: Tahoma;
	font-weight: bold;
	font-style: italic;
}
.style22 {color: #CCCCCC}
-->
</style>

<style type="text/css">
<!--
#apDiv2 {
	position:absolute;
	left:231px;
	top:202px;
	width:468px;
	height:496px;
	z-index:2;
}
#apDiv3 {
	position:absolute;
	left:12px;
	top:17px;
	width:715px;
	height:388px;
	z-index:2;
}
.style29 {color: #999999}
.style30 {font-size: 11px}
.style36 {color: #FFFF99}
-->
</style>
</head>

<body bgcolor="#000000">
<form id="cadastro" name="venda" method="post">
<div id="apDiv3">
  <table width="717">
    <tr>
      <th height="21" colspan="2" scope="col"><span class="BMWEB style30 style4">Seja Bem Vindo Consultor: </span></th>
      <th width="131" scope="col"><form id="form1" name="form1" method="post" action="">
        <label>
          <div align="left">
            <input name="Id_Nome_Consultor" type="text" class="BMWEB" id="Id_Nome_Consultor" readonly="true" value="${funcionario.nome}"/>
          </div>
        </label>
      </form>
      <label></label></th>
      <th width="9" scope="col">&nbsp;</th>
      <th width="247" scope="col">&nbsp;</th>
      <th width="1" scope="col">&nbsp;</th>
      <th width="133" scope="col">&nbsp;</th>
    </tr>
    <tr class="BMWEB">
      <td width="44" height="24" class="BMWEB style29">&nbsp;</td>
      <td width="120">&nbsp;</td>
      <td class="BMWEB style29">&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <td height="21">&nbsp;</td>
      <td class="BMWEB style22 style30">Cod Orçamento:</td>
      <td>
        <div align="left">
          <input name="Id_Cod_Orcamento" type="text" class="BMWEB" id="Id_Cod_Orcamento"/>
        </div></td>
      <td>&nbsp;</td>
      <td><form id="form4" name="form4" method="post" action="">
        <label>
          <input name="Id_Carregar_Orcamento" type="submit" class="BMWEB" id="Id_Carregar_Orcamento" value="Carregar Orçamento" onclick="pesquisa()"/>
          </label>
      </form>      </td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr class="BMWEB">
      <td height="13" class="BMWEB style29">&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr class="BMWEB">
      <td height="17" class="BMWEB style29">&nbsp;</td>
       <c:forEach items="${dadosOrcamento}" var="pesquisa">
      <td><span class="style30 style36">Data Orçamento:</span></td>
      <td>
        <div align="left">
          <input name="Id_Data_Orcamento" type="text" class="BMWEB" id="Id_Data_Orcamento" value=""  readonly="true" value="${pesquisa.data_fechamento}"/>
        </div></td>
        </c:forEach>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr class="BMWEB">
      <td height="13" class="BMWEB style29">&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <td height="21">&nbsp;</td>
      <td class="BMWEB style22 style30">Data Venda:</td>
      <td>
        <div align="left">
          <input name="Id_Data_Venda" type="text" class="BMWEB" id="Id_Data_Venda" value="" />
        </div></td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr class="BMWEB">
      <td height="13" class="BMWEB style29">&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <td height="21">&nbsp;</td>
      <td class="BMWEB style22 style30">Status Venda:</td>
      <td><form id="form3" name="form3" method="post" action="">
        <label>
          
          <div align="left">
              <select name="Id_Status_Venda" class="BMWEB" id="Id_Status_Venda">
                <option>Aberto</option>
                <option>Aguardando</option>
                <option>Fechado</option>
              </select>
          </div>
        </label>
      </form>      </td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr class="BMWEB">
      <td height="13" class="BMWEB style29">&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td colspan="3"><div align="center"><span class="BMWEB style22 style30">Itens Orçados</span></div></td>
    </tr>
    <tr>
      <td height="21">&nbsp;</td>
      <td class="BMWEB style30 style36">Valor Unitário:</td>
      <td>
        <div align="left">
          <input name="Id_Valor_Unitario" type="text" class="BMWEB" id="Id_Valor_Unitario" value="" readonly="true" />
        </div></td>
      <td>&nbsp;</td>
      <td colspan="3" rowspan="6"><div align="center">
        <textarea name="Id_Itens_Orcamento" id="Id_Itens_Orcamento" cols="40" rows="6"></textarea>
      </div></td>
    </tr>
    <tr class="BMWEB">
      <td height="13" class="BMWEB style29">&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <td height="21">&nbsp;</td>
      <td class="BMWEB style30 style36">Valor Total:</td>
      <td>
        <div align="left">
          <input name="Id_Data_Fechamento4" type="text" class="BMWEB" id="Id_Data_Fechamento4" value="" readonly="true"/>
        </div></td>
      <td>&nbsp;</td>
    </tr>
    <tr class="BMWEB">
      <td height="13" class="BMWEB style29">&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <td height="21">&nbsp;</td>
      <td class="BMWEB style22 style30">Desconto:</td>
      <td>
        <div align="left">
          <input name="Id_Desconto" type="text" class="BMWEB" id="Id_Desconto" value="" />
        </div></td>
      <td>&nbsp;</td>
    </tr>
    <tr class="BMWEB">
      <td height="13" class="BMWEB style29">&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <td height="21">&nbsp;</td>
      <td class="BMWEB style22 style30">Forma Pagamento:</td>
      <td><select name="Id_Status_Venda2" class="BMWEB" id="Id_Status_Venda2">
        <option>A Vista</option>
        <option>Cheque</option>
        <option>Pague Seguro Uol</option>
                              </select></td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr class="BMWEB">
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td><form id="form2" name="form2" method="post" action="">
        <label>
          <div align="center">
            <input name="Id_Enviar" type="submit" class="BMWEB" id="Id_Enviar" value="Enviar" />
          </div>
        </label>
      </form>      </td>
      <td><form id="form5" name="form5" method="post" action="">
        <label>
          <input name="Id_Pesquisar_Orcamento" type="submit" class="BMWEB" id="Id_Pesquisar_Orcamento" value="Pesquisar Orçamentos" />
          </label>
      </form>      </td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
  </table>
</div>
<div class="style4">
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p align="center" class="style22">&nbsp;</p>
  <p align="center" class="style22">_____________________________________________________________________________________________<br />
    <span class="BMWEB">BMWEB © 2010 Todos os direitos reservados</span> </p>
</div>
<p class="style4">&nbsp;</p>
<p class="style4">&nbsp;</p>
</form>
</body>
<script language="JavaScript" type="text/javascript">
	//var f = document.cadastro;

	function pesquisa(){
		alert("Opa");
		document.cadastro.action = "ServletPesquisaOrcamentoVenda";
		if (f.Id_Cod_Orcamento.value == "") {
			alert("Preencha o código do orçamento!!");
			f.Id_Cod_Orcamento.focus;
			return false;
		}
		return true;
	}
	
	function inserir(){
		f.action = "ServletVenda";
	}
	 $(document).ready(function(){
         $(function(){
             $.mask.addPlaceholder("~","[+-]");
             //$("#telefone").mask("([telefone removido]");
             //$("#Id_Data_Orcamento").mask("99/99/9999");
         });
     });
</script>
</html>
Minha servlet:
package br.bmweb.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.bmweb.dao.PesquisaOrcamentoVendaDao;
import br.bmweb.pojo.Funcionario;
import br.bmweb.pojo.Venda;

/**
 * Servlet implementation class Venda
 */
public class ServletPesquisaOrcamentoVenda extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ServletPesquisaOrcamentoVenda() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("Valor cod_orcamento na pesquisa: " + request.getParameter("Id_Cod_Orcamento"));
		PrintWriter writer = response.getWriter();
		HttpSession session = request.getSession(true);
		PesquisaOrcamentoVendaDao pesquisa = new PesquisaOrcamentoVendaDao(); 
		pesquisa.setFuncionario((Funcionario) (session.getAttribute("funcionario")));
		List<Venda> pesquisaVendaOrcamento;
		try {
			pesquisaVendaOrcamento = pesquisa.OrcamentoVenda(Integer.parseInt(request.getParameter("Id_Cod_Orcamento")));
			if(pesquisaVendaOrcamento.isEmpty()){

				writer.println("<SCRIPT language='JavaScript'> alert('Nenhum orçamento encontrado!!'); </SCRIPT>");
			}else{
				request.setAttribute("dadosOrcamento", pesquisaVendaOrcamento);
				request.getRequestDispatcher("Vendas2.jsp").forward(request, response);
				//writer.println("<SCRIPT language='JavaScript'> document.location=('Venda.jsp'); </SCRIPT>"); 
			}
		}catch (SQLException e) {
			writer
			.print("<p align=\"center\">Houve um erro ao tentar alterar o cliente! Tente novamente.<BR><a href=\"javascript:history.back(1);\">Clique aqui para voltar.</a></p><table style=width:\"100%\";>");
			
		}catch (Exception e) {
			e.printStackTrace();
			writer
			.print("<p align=\"center\">Houve um erro! Por favor tente novamente.<BR><a href=\"javascript:history.back(1);\">Clique aqui para voltar.</a></p><table style=width:\"100%\";>");
		}
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}
}
Minha DAO:
package br.bmweb.dao;

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

import br.bmweb.pojo.Cliente;
import br.bmweb.pojo.Funcionario;
import br.bmweb.pojo.Orcamento;
import br.bmweb.pojo.Venda;
import br.bmweb.pojo.VendaOrcamento;
import br.bmweb.util.Conexao;
import br.bmweb.util.Data;

public class PesquisaOrcamentoVendaDao {
	Connection conn = new Conexao().conecta();
	private Funcionario funcionario;

	public Funcionario getFuncionario() {
		return funcionario;
	}

	public void setFuncionario(Funcionario funcionario) {
		this.funcionario = funcionario;
	}

	public List OrcamentoVenda (int cod_orcamento) throws SQLException{
		String sql =     "SELECT tb_orcamento.or_data_orcamento, tb_orcamento.or_data_fechamento, tb_orcamento.or_valor_unit, tb_orcamento.or_valor_total, " + 
		                         "tb_orcamento.or_tipo_orcamento, tb_orcamento.or_status_orcamento, tb_cliente.cl_cod_cliente, tb_cliente.cl_nome, " + 
		                         "tb_funcionario.fu_cod_funcionario, tb_funcionario.fu_nome, tb_orcamento.or_cod_orcamento " +
		                   "FROM tb_orcamento " +
		             "INNER JOIN tb_cliente " +
		                     "ON tb_orcamento.or_cod_cliente = tb_cliente.cl_cod_cliente " +
		             "INNER JOIN tb_funcionario " +
		                     "ON tb_orcamento.or_cod_funcionario = tb_funcionario.fu_cod_funcionario " +
		                  "WHERE tb_orcamento.or_cod_orcamento = ?"; 
		try {
			PreparedStatement smt = conn.prepareStatement(sql);
			List<VendaOrcamento> arrayLista = new ArrayList<VendaOrcamento>();
			smt.setInt(1, cod_orcamento);
			ResultSet rs = smt.executeQuery();
			while (rs.next()) {
				VendaOrcamento vendaorcamento = new VendaOrcamento();
				vendaorcamento.setCod_orcamento(Integer.parseInt(rs.getString("tb_orcamento.or_cod_orcamento")));
				vendaorcamento.setCod_cliente(Integer.parseInt(rs.getString("tb_cliente.cl_cod_cliente")));
				vendaorcamento.setNome_cliente(rs.getString("tb_cliente.cl_nome"));
				System.out.println("Nome do cliente do orçamento: " + vendaorcamento.getNome_cliente());
				vendaorcamento.setNome_funcionario(rs.getString("tb_funcionario.fu_nome"));  
				System.out.println("Vendedor: " + vendaorcamento.getNome_funcionario());
				vendaorcamento.setData_orcamento(rs.getDate("tb_orcamento.or_data_orcamento"));
				vendaorcamento.setData_fechamento(rs.getDate("tb_orcamento.or_data_fechamento"));
				vendaorcamento.setValor_unitario(rs.getDouble("tb_orcamento.or_valor_unit"));
				vendaorcamento.setValor_total(rs.getDouble("tb_orcamento.or_valor_total"));
				vendaorcamento.setTipo_orcamento(rs.getString("tb_orcamento.or_tipo_orcamento"));
				vendaorcamento.setStatus_orcamento(rs.getString("tb_orcamento.or_status_orcamento"));
				vendaorcamento.setCod_funcionario(rs.getInt("tb_funcionario.fu_cod_funcionario"));
				arrayLista.add(vendaorcamento);
			}
			return arrayLista ;
		} finally {

		}
	}
}
Pelo que vi o problema está na linha 95 do JSP, alí chamo uma função JavaScript que seta a action pro HTML, ele até entra na função para parece que a action não é executada.

A servlet é responsável em setar o campo da linha 116 do JSP.

Estou sem saber o que fazer, alguém tem alguma idéia??

1 Resposta

B

Bom, já que é um trabalho de TCC você poderia caprichar mais nas suas camadas…Utilizar um framework MVC ao invés de servlets, um framework para persistência ao invés de jdbc direto…Você irá codificar muito menos,terá um código mais limpo e menos sujeito a erros…

Mas a respeito do seu problema eu faria algumas modificações no seu Servlet, não é adequado sobrescrever o método service(é de responsabilidade do container chamalo e após isso chamar seu método de serviço, no seu caso o post… Mais detalhes do ciclo de vida de um servlet) ,por isso remova o método service e coloque o conteúdo que está no método service no seu método doPost…

Além disso na sua tag form coloque o atributo action e nele coloque a url pattern do seu servlet, para o container carregar seu servlet e invocar seu método…

Criado 26 de março de 2010
Ultima resposta 26 de mar. de 2010
Respostas 1
Participantes 2