Várias actions no JSP

6 respostas
C
Olá pessoal, estou com uma grande dúvida num formulário de cadastro que estou criando, atualmente meu formulário tem um campo "Cod_orcamento" onde o usuário digita o código de um orçamento, logo ao lado deste campo tem um botão chamado "Carregar Dados Orçamento" que ao ser clicado chama a servlet chamada "ServletPesquisaOrcamentoVenda" que carrega dados do orçamento nos outros campos deste mesmo formulário. Acontece que o usuário vai precisar preencher mais alguns dados e clicar no botão "Enviar" que executa a servlet chamada "ServletVenda" que captura todos os dados dos campos e salvo no banco. Meu problema está em utilizar estas duas ACTIONS desses botões, atualmente a declaração da tag
do meu JSP está assim:
<form id="cadastro" name="venda" method="post" action="ServletPesquisaOrcamentoVenda">
Ou seja, executa apenas a consulta do evento do botão "Carregar Dados Orçamento", sem ter como executar a ação do botão "Enviar" que chama a servlet "ServletVenda". Qual a forma mais simples de fazer isto? Deve remover a action do meu form e chamar as servlets através do evento onclick de cada botão?? Abaixo minhas classes: Minha ServletPesquisaOrcamentoVenda:
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("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("cod_orcamento")));
			if(pesquisaVendaOrcamento.isEmpty()){

				writer.println("<SCRIPT language='JavaScript'> alert('Nenhum orçamento encontrado!!'); </SCRIPT>");
			}else{
				request.setAttribute("dadosOrcamento", pesquisaVendaOrcamento);
				request.getRequestDispatcher("Venda.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 ServletVenda:
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("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("cod_orcamento")));
			if(pesquisaVendaOrcamento.isEmpty()){

				writer.println("<SCRIPT language='JavaScript'> alert('Nenhum orçamento encontrado!!'); </SCRIPT>");
			}else{
				request.setAttribute("dadosOrcamento", pesquisaVendaOrcamento);
				request.getRequestDispatcher("Venda.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
	}
}
Meu JSP:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!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>Venda</title>
<script language="JavaScript" type="text/javascript">
	function validaFormulario() {
		var f = document.cadastro;
		if (f.cod_cliente.value == "") {
			alert("Preencha o código do cliente!!");
			return false;
		}
		return true;
	}
</script>

</head>
<body>
Seja Bem-Vindo
<b>${funcionario.nome}</b>
<form id="cadastro" name="venda" method="post" action="ServletPesquisaOrcamentoVenda">
<table width="540" border="0" align="center">
	<!-- 
	<tr>
		<td width="76">Cod Cliente:</td>
		<td width="538"><input name="cod_cliente" type="text" id="cod_cliente" size="10" maxlength="10" />
	</tr>
	 -->

	<tr>
		<td width="76">Cod Orcamento:</td>
		<td width="538"><input name="cod_orcamento" type="text"
			id="cod_orcamento" size="10" maxlength="10" /> <input name="enviar"
			type="submit" id="enviar" value="Carregar Dados Orcamento" />
	</tr>

	<c:forEach items="${dadosOrcamento}" var="pesquisa">
		<tr>
			<td width="76">Cliente:</td>
			<td width="538"><input name="cliente" type="text"
				id="cliente" size="10" maxlength="10" value="${pesquisa.nome_cliente}"/>
		</tr>
		
		<tr>
			<td width="76">Vendedor:</td>
			<td width="538"><input name="vendedor" type="text"
				id="vendedor" size="10" maxlength="10" value="${pesquisa.nome_funcionario}"/>
		</tr>
		
		<tr>
			<td width="76">Data Fechamento Orçamento:</td>
			<td width="538"><input name="data_fechamento" type="text"
				id="data_fechamento" size="10" maxlength="10" value="${pesquisa.data_fechamento}"/>
		</tr>

		<!--  
	<tr>
		<td width="76">Status Venda:</td>
		<td width="538"><input name="status_venda" type="text"
			id="status_venda" size="10" maxlength="10" />
	</tr>
	-->

		<tr>
			<td width="76">Valor Unitário:</td>
			<td width="538"><input name="valor_unitario" type="text"
				id="valor_unitario" size="7" maxlength="7" value="${pesquisa.valor_unitario}"/>
		</tr>

		<tr>
			<td width="76">Valor Total:</td>
			<td width="538"><input name="valor_total" type="text"
				id="valor_total" size="7" maxlength="7" />
		</tr>

	</c:forEach>


	<tr>
		<td width="76">Data Venda:</td>
		<td width="538"><input name="data_venda" type="text"
			id="data_venda" size="10" maxlength="10" />
	</tr>

	<tr>
		<td width="76">Desconto:</td>
		<td width="538"><input name="desconto" type="text" id="desconto"
			size="7" maxlength="7" />
	</tr>


	<!-- 
	<tr>
		<td width="76">Tipo Venda:</td>
		<td width="538"><input name="tipo_venda" type="text"
			id="tipo_venda" size="10" maxlength="10" />
	</tr>
	
 -->
 
	<tr>
		<td width="76">Forma de Pagamento:</td>
		<td width="538"><input name="tipo_pagamento" type="text"
			id="tipo_pagamento" size="100" maxlength="100" />
	</tr>

	<tr>
		<td colspan="2" align="center">
		<p><input name="enviar" type="submit" id="enviar" value="Enviar" />

		<input name="cancelar" type="reset" id="cancelar" value="Cancelar" />
		</td>
	</tr>
</table>
</body>
</html>

6 Respostas

C

Pessoal alguém tem alguma idéia?

J

Acredito que você precisa de um formulário por ação, ou seja, cadastro , alteração, exclusão.

C

Certo, mas se vc olhar bem verá que é um formulário só, quando o usuário preenche o campo Cod_orcamento e clica no botão “Carregar Dados Orçamento” alguns campos deste formulário são preenchidos, o usuário precisa preencher o restante dos campos e clicar no botão “Enviar” para salvar os dados no banco, já fiz minhas servlets mas não sei como trabalhar com estas actions neste formulário, pois uma servlet executa a pesquisa quando o usuário clica em “Carregar Dados Orçamento” e a outra servlet salva no banco os dados que foram carregados no formulário pela outra servlet + os dados prrenchidos manualmente. Tem como eu chamar uma servlet no evento onclick do botão??

J

eu posso estar errado pois não trabalho desta forma, mas acho você consegue chamar apenas uma servlet por vez, porque a action do form está direcionado para esta servlet “ServletPesquisaOrcamentoVenda”.

Para trabalhar de outra forma você pode pegar uma apostila no site da caelum “fj20” que explica como fazer uma servlet controladora.

C

Exatamente isso, da forma que fiz só consigo usar uma servlet por vez, fiz uns testes aqui e criei duas funções javascript, uma que chama a servlet e outra que chama a servlet de inserção no banco, daí faço a chamada delas em cada botão, desta forma funciona perfeitamente mas sabe como é né… Ficou uma coisa muito “POG”, vou dar uma olhada na apostila que você disse, e acredito que com certeza vai quebrar um grande galho.

S

Voce preenche os campos (retorno da pesquisa) com um request certo?

Algo assim:

<%String codOrcamento = request.getParameter("cod"); %>

Faz <form name=" frmpes" (Um form para pesquisa )
e

<form name=" frmenv" com os campos que serao preenchdos posteriormente e como voce tem esssa string, coloca ela em um campo type = "hidden" assim:

Repare que: <%=codOrcamento%> é a string que retornou da pesquisa no request

Criado 23 de março de 2010
Ultima resposta 24 de mar. de 2010
Respostas 6
Participantes 3