Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

mateusraony

Calculo Monetário

Recommended Posts

Ola, estou tendo problemas para realiza cálculos monetários contendo mais de um calculo e também contendo soma total de itens, conforme abaixo.

 

Gostaria que fosse feito a multiplicação dos itens:

Quantidade X Referencia = Total Referencia

Quantidade X C.Unitario = Custo Total

Custo Total + 11% = Custo Imposto

Total Referencia - Custo Imposto = Lucro

 

Lembrando que as linhas são adicionadas e em cima no campo Total Venda somasse o Total Referencia e o no campo Total Lucro somasse o Lucro.

 

Obs: Preciso que seja cálculos monetários.

 

Segue abaixo o codigo:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "[url=http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">[/url]
<html xmlns="[url=http://www.w3.org/1999/xhtml]http://www.w3.org/1999/xhtml"><head>[/url]
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
[font='Helvetica Neue', Arial, Verdana, sans-serif]        [/font]
    <!--CSS-->    
        <link href='[url=http://fonts.googleapis.com/css?family=Oswald:400,300,700]http://fonts.googleapis.com/css?family=Oswald:400,300,700[/url]' rel='stylesheet' type='text/css'/>
[font='Helvetica Neue', Arial, Verdana, sans-serif]        <link href='[url=http://fonts.googleapis.com/css?family=Terminal+Dosis]http://fonts.googleapis.com/css?family=Terminal+Dosis[/url]' rel='stylesheet' type='text/css' /> [/font]
[font='Helvetica Neue', Arial, Verdana, sans-serif]    [/font]
<!-- jquery de Calculo CalcMoeda_Mask-->
<script language="JavaScript" type="text/javascript" src="js/CalcMoeda_Mask.js"></script>
 
    <!--jquery para duplicar-->
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">

$(function () {
    function removeCampo() {
        $(".removerCampo").unbind("click");
        $(".removerCampo").bind("click", function () {
            if($("div.tabelasDuplicar").length > 1){
                $(this).parents("div.tabelasDuplicar").remove();
            }
        });
    }
 
    $(".adicionarCampo").click(function () {
        novoCampo = $("div.tabelasDuplicar:first").clone();
        novoCampo.find("input").val("");
        novoCampo.insertAfter("div.tabelasDuplicar:last");
        removeCampo();
    });
});

</script>
        
[font='Helvetica Neue', Arial, Verdana, sans-serif]<body>[/font]
 
    <form name="frmEnviar" action="" method="post">
 
    <table width="946" border="0" cellspacing="1" cellpadding="2" class="center-block" align="center">
    <br />
        <tr><td height="46" colspan="12" class="cabecario" >CADASTRO DE LICITAÇÕES</td></tr>
        <tr><th height="4" colspan="12"  scope="col"> </th></tr>
        <tr class="linha1">
            <td width="40">Orgão</td>
            <td width="43">UASG</td>
            <td width="47">Pregão</td>
            <td width="44">Objeto</td>
            <td width="51">Abertura</td>
            <td width="71">U.F.</td>
            <td width="121">Tipo Licitação</td>
            <td width="144">Situação</td>
            <td width="68">Finalizado</td>
            <td width="98">Anexar arquivo</td>
            <td width="79">Total Venda</td>
            <td width="79">Total Lucro</td>
        </tr>
    <tr>
        <td><label for="orgao"></label><input name="orgao" type="text" class="txt bradius" id="orgao" size="27" style="font-size: 10pt" /></td>
        <td><label for="uasg"></label><input type="text" name="uasg" id="uasg" class="txt bradius" size="4" style="text-align: center;"/></td>
        <td><label for="pregao"></label><input type="text" name="pregao" id="pregao" class="txt bradius" size="4" style="text-align: center;"/></td>
        <td><label for="objeto"></label><input type="text" name="objeto" id="objeto" class="txt bradius" size="37"/></td>
        <td ><label for="abertura"></label><input type="text" name="abertura" placeholder="DD/MM/YYYY" id="abertura" onkeyup="maskIt(this,event,'##/##/####')" class="txt bradius" size="16" style="text-align: center;"/></td>
        <td>
            <select name="situacao[]">
                <option value="" selected="selected">...</option>
                <option value="AC">AC</option>
                <option value="AL">AL</option>
                <option value="AP">AP</option>
                <option value="AM">AM</option>
                <option value="BA">BA</option>
                <option value="CE">CE</option>
                <option value="DF">DF</option>
                <option value="ES">ES</option>
                <option value="GO">GO</option>
                <option value="MA">MA</option>
                <option value="MT">MT</option>
                <option value="MS">MS</option>
                <option value="MG">MG</option>
                <option value="PA">PA</option>
                <option value="PB">PB</option>
                <option value="PR">PR</option>
                <option value="PE">PE</option>
                <option value="PI">PI</option>
                <option value="RJ">RJ</option>
                <option value="RN">RN</option>
                <option value="RS">RS</option>
                <option value="RO">RO</option>
                <option value="RR">RR</option>
                <option value="SC">SC</option>
                <option value="SP">SP</option>
                <option value="SE">SE</option>
                <option value="TO">TO</option>
            </select>
        </td>
        <td>
            <select name="tipolicitacao[]">
                <option value="" selected="selected">Selecione...</option>
                <option value="Servico">Serviço</option>
                <option value="Informatica">Informática</option>
                <option value="Eletronico">Eletrônico</option>
                <option value="Outros">Outros</option>
            </select>
        </td>
        <td>
            <select name="situacao[]">
                <option value="" selected="selected">Selecione...</option>
                <option value="Agendado">Agendado</option>
                <option value="Acompanhar">Acompanhar</option>
                <option value="EmAndamento">Em Andamento</option>
                <option value="Suspensao">Suspensão</option>
                <option value="Ganho">Ganho</option>
                <option value="NaoGanho">Não Ganho</option> 
            </select>
        </td>
        <td><label for="finalizado"></label><input type="text" name="finalizado" id="finalizado" onkeyup="maskIt(this,event,'##/##/####')" placeholder="DD/MM/YYYY"  class="txt bradius" size="16" style="text-align: center;"/></td>
        <td> </td>
        <td><label for="totalVenda"></label><input name="totalVenda" type="text" class="txt bradius" id="totalVenda" size="7" readonly="readonly" style="background-color: #f1f1f1; text-align:center" placeholder="R$0,00" /></td>
        <td><label for="totalLucro"></label><input name="totalLucro" type="text" class="txt bradius" id="totalLucro" size="7" readonly="readonly" style="background-color: #f1f1f1; text-align:center" placeholder="R$0,00" /></td>
    </tr>
    </table>
<br />
    <div class="tabelasDuplicar" style="border-bottom: 1px dashed #f1f1f1;padding: 10px 0;" id="tabelasDuplicar" align="center">
    <table width="946" border="0" cellspacing="1" cellpadding="2" class="center-block">
    <tr class="linha1">
        <td>ID</td>
        <td>Item</td>
        <td>Material</td>
        <td>Quantidade</td>
        <td>Referência</td>
        <td>Total Referência</td>
        <td>C. Unitário</td>
        <td>Custo Total</td>
        <td>Custo Imposto</td>
        <td>Lucro</td>
        <td> </td>
        <td> </td>
    </tr>
    <tr>
        <td><label for="ID"></label><input name="ID[]" type="text" class="txt bradius" id="ID" size="1"/></td>
        <td><label for="item"></label><input type="text" name="item[]" id="item" class="txt bradius" size="1"/></td>
        <td><label for="descricao"></label><input type="text" name="descricao[]" id="descricao" class="txt bradius" size="40" /></td>
        <td><label for="qty"></label><input type="text" name="qty[]" id="qty[]" class="txt bradius" value="" size="7" style="text-align: center;"></td>
        <td><label for="UnitValRef"></label><input type="text" name="UnitValRef[]" id="UnitValRef"  placeholder="R$ 0,00" class="txt bradius" value="" size="17" style="text-align: center;"></td>
        <td><label for="valorTotalRef"></label><input name="valorTotalRef[]" type="text" class="txt bradius" id="total" value="" size="10" readonly="readonly" style="background-color: #f1f1f1; text-align:center" placeholder="R$ 0,00"></td>
        <td><label for="custoUnit"></label><input type="text" name="custoUnit[]" id="custoUnit" onkeyup="soma2();numMoeda(event,this);numMoeda(event,custoTotal);" placeholder="R$ 0,00" value="" class="txt bradius" size="7" style="text-align: center;"/></td>
        <td><label for="custoTotal"></label><input name="custoTotal[]" type="text" class="txt bradius" id="custoTotal" placeholder="R$ 0,00" value="" size="10" readonly="readonly" style="text-align: center;"/></td>
        <td><label for="custoImposto"></label><input type="text" name="custoImposto[]" id="custoImposto" onkeyup="soma3();numMoeda(event,this);numMoeda(event,custoImposto);" placeholder="R$ 0,00" value="" class="txt bradius" size="10" style="text-align: center;"/></td>
        <td><label for="lucro"></label><input name="lucro[]" type="text" class="txt bradius" id="lucro" onkeyup="soma4();numMoeda(event,this);numMoeda(event,lucro);" value="" size="10" readonly="readonly" style="background-color: #f1f1f1; text-align:center" placeholder="R$ 0,00" /></td>
        <td> </td>
        <td> </td>
    </tr>
    </table>
 
    <table id="products-table" width="946" border="0" cellspacing="1" cellpadding="2" class="center-block">
    <tbody>
        <tr class="linha1">
            <td>Fornecedor</td>
            <td>Prazo Fornecedor</td>
            <td>Prazo Cliente</td>
            <td>Transportadora</td>
            <td>Observação</td>
            <td> </td>
            <td>Status</td>
            <td>Motivo</td>
            <td> </td>
            <td> </td>
            <td> </td>
            <td> </td>
        </tr>
        <tr>
            <td><label for="fornecedor"></label><input type="text" name="fornecedor[]" id="fornecedor" class="txt bradius" size="5"/></td>
            <td><label for="prazoFornecedor"></label><input type="text" name="prazoFornecedor[]" id="prazoFornecedor" class="txt bradius" size="11" style="text-align: center;"/></td>
            <td><label for="prazoCliente"></label><input type="text" name="prazoCliente[]" id="prazoCliente" class="txt bradius" size="7"style="text-align: center;"/></td>
            <td><label for="transportadora"></label><input type="text" name="transportadora[]" id="transportadora" class="txt bradius"size="9"/></td>
            <td><label for="observacao"></label><input type="text" name="observacao[]" id="observacao" class="txt bradius"size="47"/></td>
            <td> </td>
            <td><label for="status"></label><input type="text" name="status[]" id="status" class="txt bradius"size="10"/></td>
            <td><label for="motivo"></label><input type="text" name="motivo[]" id="motivo" class="txt bradius"size="10"/></td>
            <td> </td>
            <td> </td>
            <td class="actions">
                <button class="btn btn-large btn-danger removerCampo" type="button" id="btn-remove">Remover</button>
            </td>
            <td> </td>
            <td> </td>
        </tr>
    </tbody>
    </table>
    </div>
 
    <!-- botao adicionar -->
    <table width="946" border="0" cellspacing="1" cellpadding="2" class="center-block" align="center">
        <tr><td> </td></tr>
        <tr>
            <td><button class="btn btn-large btn-success adicionarCampo" type="button" id="btn-adiciona">Adicionar Produto</button>
            <button class="btn btn-large" type="submit">CADASTRAR</button></td>
        </tr>
    </table>
 
    </form>
    <!-- /[] -->
 
</body>

Compartilhar este post


Link para o post
Compartilhar em outros sites

Corrigindo o HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml]http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <link href='http://fonts.googleapis.com/css?family=Oswald:400,300,700' rel='stylesheet' type='text/css'/>
  <link href='http://fonts.googleapis.com/css?family=Terminal+Dosis' rel='stylesheet' type='text/css' />

  <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
  <script type="text/javascript" src="calc.js"></script>

</head>
<body>
<form name="frmEnviar" action="" method="post">

  <table width="946" border="0" cellspacing="1" cellpadding="2" class="center-block" align="center">
    <tr><td height="46" colspan="12" class="cabecario" >CADASTRO DE LICITAÇÕES</td></tr>
    <tr><th height="4" colspan="12"  scope="col"> </th></tr>
    <tr class="linha1">
      <td width="40">Orgão</td>
      <td width="43">UASG</td>
      <td width="47">Pregão</td>
      <td width="44">Objeto</td>
      <td width="51">Abertura</td>
      <td width="71">U.F.</td>
      <td width="121">Tipo Licitação</td>
      <td width="144">Situação</td>
      <td width="68">Finalizado</td>
      <td width="98">Anexar arquivo</td>
      <td width="79">Total Venda</td>
      <td width="79">Total Lucro</td>
    </tr>
    <tr>
      <td><label></label><input name="orgao" type="text" class="txt bradius" size="27" style="font-size: 10pt" /></td>
      <td><label></label><input type="text" name="uasg" class="txt bradius" size="4" style="text-align: center;"/></td>
      <td><label></label><input type="text" name="pregao" class="txt bradius" size="4" style="text-align: center;"/></td>
      <td><label></label><input type="text" name="objeto" class="txt bradius" size="37"/></td>
      <td ><label></label><input type="text" name="abertura" placeholder="DD/MM/YYYY" class="txt bradius" size="16" style="text-align: center;"/></td>
      <td>
        <select name="situacao[]">
          <option value="" selected="selected">...</option>
          <option value="AC">AC</option>
          <option value="AL">AL</option>
          <option value="AP">AP</option>
          <option value="AM">AM</option>
          <option value="BA">BA</option>
          <option value="CE">CE</option>
          <option value="DF">DF</option>
          <option value="ES">ES</option>
          <option value="GO">GO</option>
          <option value="MA">MA</option>
          <option value="MT">MT</option>
          <option value="MS">MS</option>
          <option value="MG">MG</option>
          <option value="PA">PA</option>
          <option value="PB">PB</option>
          <option value="PR">PR</option>
          <option value="PE">PE</option>
          <option value="PI">PI</option>
          <option value="RJ">RJ</option>
          <option value="RN">RN</option>
          <option value="RS">RS</option>
          <option value="RO">RO</option>
          <option value="RR">RR</option>
          <option value="SC">SC</option>
          <option value="SP">SP</option>
          <option value="SE">SE</option>
          <option value="TO">TO</option>
        </select>
      </td>
      <td>
        <select name="tipolicitacao[]">
          <option value="" selected="selected">Selecione...</option>
          <option value="Servico">Serviço</option>
          <option value="Informatica">Informática</option>
          <option value="Eletronico">Eletrônico</option>
          <option value="Outros">Outros</option>
        </select>
      </td>
      <td>
        <select name="situacao[]">
          <option value="" selected="selected">Selecione...</option>
          <option value="Agendado">Agendado</option>
          <option value="Acompanhar">Acompanhar</option>
          <option value="EmAndamento">Em Andamento</option>
          <option value="Suspensao">Suspensão</option>
          <option value="Ganho">Ganho</option>
          <option value="NaoGanho">Não Ganho</option>
        </select>
      </td>
      <td><label></label><input type="text" name="finalizado" placeholder="DD/MM/YYYY" class="txt bradius" size="16" style="text-align: center;"/></td>
      <td> </td>
      <td><label></label><input name="totalVenda" type="text" class="txt bradius" size="7" readonly="readonly" style="background-color: #f1f1f1; text-align:center" placeholder="R$0,00" /></td>
      <td><label></label><input name="totalLucro" type="text" class="txt bradius" size="7" readonly="readonly" style="background-color: #f1f1f1; text-align:center" placeholder="R$0,00" /></td>
    </tr>
  </table>

<br />

  <div class="tabelasDuplicar" style="border-bottom: 1px dashed #f1f1f1;padding: 10px 0;" align="center">
  <table width="946" border="0" cellspacing="1" cellpadding="2" class="center-block">
    <tr class="linha1">
      <td>ID</td>
      <td>Item</td>
      <td>Material</td>
      <td>Quantidade</td>
      <td>Referência</td>
      <td>Total Referência</td>
      <td>C. Unitário</td>
      <td>Custo Total</td>
      <td>Custo Imposto</td>
      <td>Lucro</td>
      <td> </td>
      <td> </td>
    </tr>
    <tr>
      <td><label></label><input name="ID[]" type="text" class="txt bradius"  size="1"/></td>
      <td><label></label><input type="text" name="item[]" class="txt bradius" size="1"/></td>
      <td><label></label><input type="text" name="descricao[]" class="txt bradius" size="40" /></td>
      <td><label></label><input type="text" name="qty[]" class="txt bradius" value="" size="7" style="text-align: center;"></td>
      <td><label></label><input type="text" name="UnitValRef[]" placeholder="R$ 0,00" class="txt bradius" value="" size="17" style="text-align: center;"></td>
      <td><label></label><input name="valorTotalRef[]" type="text" class="txt bradius"  value="" size="10" readonly="readonly" style="background-color: #f1f1f1; text-align:center" placeholder="R$ 0,00"></td>
      <td><label></label><input type="text" name="custoUnit[]" placeholder="R$ 0,00" value="" class="txt bradius" size="7" style="text-align: center;"/></td>
      <td><label></label><input name="custoTotal[]" type="text" class="txt bradius" placeholder="R$ 0,00" value="" size="10" readonly="readonly" style="text-align: center;"/></td>
      <td><label></label><input type="text" name="custoImposto[]" placeholder="R$ 0,00" value="" class="txt bradius" size="10" style="text-align: center;"/></td>
      <td><label></label><input name="lucro[]" type="text" class="txt bradius" value="" size="10" readonly="readonly" style="background-color: #f1f1f1; text-align:center" placeholder="R$ 0,00" /></td>
      <td> </td>
      <td> </td>
    </tr>
  </table>

  <table width="946" border="0" cellspacing="1" cellpadding="2" class="center-block">
    <tbody>
      <tr class="linha1">
        <td>Fornecedor</td>
        <td>Prazo Fornecedor</td>
        <td>Prazo Cliente</td>
        <td>Transportadora</td>
        <td>Observação</td>
        <td> </td>
        <td>Status</td>
        <td>Motivo</td>
        <td> </td>
        <td> </td>
        <td> </td>
        <td> </td>
      </tr>
      <tr>
        <td><label></label><input type="text" name="fornecedor[]" class="txt bradius" size="5"/></td>
        <td><label></label><input type="text" name="prazoFornecedor[]" class="txt bradius" size="11" style="text-align: center;"/></td>
        <td><label></label><input type="text" name="prazoCliente[]" class="txt bradius" size="7"style="text-align: center;"/></td>
        <td><label></label><input type="text" name="transportadora[]" class="txt bradius"size="9"/></td>
        <td><label></label><input type="text" name="observacao[]" class="txt bradius"size="47"/></td>
        <td> </td>
        <td><label></label><input type="text" name="status[]" class="txt bradius"size="10"/></td>
        <td><label></label><input type="text" name="motivo[]" class="txt bradius"size="10"/></td>
        <td> </td>
        <td> </td>
        <td class="actions">
            <button class="btn btn-large btn-danger removerCampo" type="button" id="btn-remove">Remover</button>
        </td>
        <td> </td>
        <td> </td>
      </tr>
    </tbody>
  </table>
  </div>

  <!-- botao adicionar -->
  <table width="946" border="0" cellspacing="1" cellpadding="2" class="center-block" align="center">
    <tr><td> </td></tr>
    <tr>
      <td><button class="btn btn-large btn-success adicionarCampo" type="button" id="btn-adiciona">Adicionar Produto</button>
      <button class="btn btn-large" type="submit">CADASTRAR</button></td>
    </tr>
  </table>

</form>
</body>
</html>
Fiz o JavaScript para uma linha

 

calc.js

$(document).ready(function () {
  var $adicionarCampo = $(".adicionarCampo");
  function removeCampo() {
    $(".removerCampo").off("click");
    $(".removerCampo").on("click", function () {
      if($("div.tabelasDuplicar").length > 1){
        $(this).parents("div.tabelasDuplicar").remove();
      }
    });
  }

  $adicionarCampo.on('click', function () {
    novoCampo = $("div.tabelasDuplicar:first").clone();
    novoCampo.find("input").val("");
    novoCampo.insertAfter("div.tabelasDuplicar:last");
    removeCampo();
  });

  $('input[name="qty[]"]').keyup(calcTotal);
  $('input[name="UnitValRef[]"]').keyup(calcTotal);
  $('input[name="custoUnit[]"]').keyup(calcTotal);
  $('input[name="custoImposto[]"]').keyup(calcLucro);

  $('input[name="UnitValRef[]"]').on('keyup', maskMoney)
  $('input[name="custoUnit[]"]').on('keyup', maskMoney)
  $('input[name="custoImposto[]"]').on('keyup', maskMoney)
  // $('input[name="custoTotal[]"]').on('keyup', maskMoney)
  // $('input[name="valorTotalRef[]"]').on('keyup', maskMoney)
  // $('input[name="lucro[]"]').on('keyup', maskMoney)

});

var calcLucro = function(event) {
  var $lucro = $('input[name="lucro[]"]')
  var imposto = $('input[name="custoImposto[]"]').val().toFloat() || 0;
  var custo = $('input[name="custoTotal[]"]').val().toFloat() || 0;

  var total = custo - imposto;
  $lucro.val(String(total.toFixed(2)).formatMoney());
};

var calcTotal = function(event) {
  var qty = $('input[name="qty[]"]').val().toFloat() || 0;
  var ref = $('input[name="UnitValRef[]"]').val().toFloat() || 0;
  var unit = $('input[name="custoUnit[]"]').val().toFloat() || 0;

  var totalRef = qty * ref;
  var totalCusto = qty * unit;
  $('input[name="valorTotalRef[]"]').val(String(totalRef.toFixed(2)).formatMoney());
  $('input[name="custoTotal[]"]').val(String(totalCusto.toFixed(2)).formatMoney());
};

var maskMoney = function(event) {
  var $this = $(this);
  mascara($this, mvalor);
};

String.prototype.formatMoney = function() {
  var v = this;

  if(v.indexOf('.') === -1) {
    v = v.replace(/([\d]+)/, "$1,00");
  }

  v = v.replace(/([\d]+)\.([\d]{1})$/, "$1,$20");
  v = v.replace(/([\d]+)\.([\d]{2})$/, "$1,$2");
  v = v.replace(/([\d]+)([\d]{3}),([\d]{2})$/, "$1.$2,$3");

  return v;
};
String.prototype.toFloat = function() {
  var v = this;

  if (!v) return 0;
  return parseFloat(v.replace(/[\D]+/g, '' ).replace(/([\d]+)(\d{2})$/, "$1.$2"), 10);
};
function mascara(o,f){
  v_obj=o
  v_fun=f
  setTimeout(execmascara,1);
}
function execmascara(){
  v_obj.val(v_fun(v_obj.val()))
}
function mvalor(v){
  v=v.replace(/\D/g,"");
  v=v.replace(/(\d)(\d{8})$/,"$1.$2");
  v=v.replace(/(\d)(\d{5})$/,"$1.$2");

  v=v.replace(/(\d)(\d{2})$/,"$1,$2");
  return v;
}

Compartilhar este post


Link para o post
Compartilhar em outros sites

Boa tarde!

William, não consigo fazer o calculo de +11% no campo custo imposto e também quando adiciona a linha nas demais não funciona o calculo nem na soma total de Venda e Lucro.

 

Poderia me ajudar?

 

Obrigado!

Compartilhar este post


Link para o post
Compartilhar em outros sites

  • Conteúdo Similar

    • Por violin101
      Caros amigos, saudações.
       
      Estou escrevendo um Sistema em JAVA Web Servlet, estou tendo problema para Invalidar Sessão.

      Toda vez que o usuário faz o LOGOUT, o sistema permite que o Navegar retorna para a página anterior.

      Como consigo bloquear/destruir a sessão para o Sistema quando o usuário sair, voltar sempre para o Login.

      o meu Servlet está assim:
       
      package br.com.rc.controlador; import br.com.rc.dao.UserDAO; import br.com.rc.modelo.Usuario; import br.com.rc.seguranca.Criptografia; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet - Autenticação Usuário */ public class AuthControlador extends HttpServlet { private UserDAO authDao = new UserDAO(); private final String PagIndex = "index.jsp"; private final String PagHome = "home.jsp"; private final String PagLogout = "deslogar.jsp"; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String accion = request.getParameter("accion"); switch (accion) { case "login": Login(request, response); break; case "logout": Logout(request, response); break; default: throw new AssertionError(); } } protected void Login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); request.getRequestDispatcher(PagIndex).forward(request, response); } /* * O problema está aqui, não invalida a sessão e permite que volta * para a página anterior. */ protected void Logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); HttpSession session = request.getSession(); session.setAttribute("users", null); session.removeAttribute("users"); session.invalidate(); response.sendRedirect(PagLogout); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override public String getServletInfo() { return "Short description"; } }
      Deslogar.JSP
      página criada para impedir que volte para a anterior.
      <% //Destrói Sessão session.invalidate(); //Redirecionar Página Login response.sendRedirect("index.jsp"); %>

      Grato,

      Cesar
    • Por violin101
      Caros amigos, saudações.

      Estou escrevendo um Sistema em JAVA Web e estou encontrando um problema para fazer Paginação.

      O sistema informa o Limite de registro por página, mas não mostra abaixo da tabela a paginação.

      Alguém pode me ajudar ?

      Posto o Código abaixo.

      Controller - Servlet
       
      package br.com.rc.controlador; import br.com.rc.modelo.Cargo; import br.com.rc.modelo.dao.CargoDAO; import java.io.IOException; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet */ public class srvCargos extends HttpServlet { private CargoDAO crgDao = new CargoDAO(); private final String pagListar = "/views/cargos/cargos.jsp"; private final String pagNovo = "/views/cargos/cargoNovo.jsp"; private final String pagEditar = "/views/cargos/cargoEditar.jsp"; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String accion = request.getParameter("accion"); switch (accion) { case "listarCargos": listarCargos(request, response); break; default: throw new AssertionError(); } } protected void listarCargos(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); int paginaActual = 1; int registrosPorPagina = 5; // Qtde por Tabela if (request.getParameter(pagListar) != null) { paginaActual = Integer.parseInt(request.getParameter(pagListar)); } int offset = (paginaActual - 1) * registrosPorPagina; List<Cargo> lista = crgDao.ListarTodos(offset, registrosPorPagina); int totalRegistros = crgDao.contarTotal(); int totalPaginas = (int) Math.ceil((double) totalRegistros / registrosPorPagina); request.setAttribute("cargos", lista); request.setAttribute("totalPaginas", totalPaginas); request.setAttribute("paginaAtual", paginaActual); request.getRequestDispatcher(pagListar).forward(request, response); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }  
      Classe DAO
       
      package br.com.rc.modelo.dao; import br.com.rc.config.Conexion; import br.com.rc.modelo.Cargo; import java.sql.*; import java.util.ArrayList; import java.util.List; /** * Classe DAO */ public class CargoDAO { private Connection cn = null; private PreparedStatement ps = null; private ResultSet rs = null; private int noOfRecords; public ArrayList<Cargo> ListarTodos(int offset, int noOfRecords) { ArrayList<Cargo> lista = new ArrayList<>(); try { cn = Conexion.getConnection(); String sql = "select * from Cargo ORDER BY nombreCargo ASC limit " + offset + ", " + noOfRecords; ps = cn.prepareStatement(sql); rs = ps.executeQuery(); while (rs.next()) { Cargo obj = new Cargo(); obj.setIdCargo(rs.getInt("idCargo")); obj.setNombreCargo(rs.getString("nombreCargo")); obj.setEstado(rs.getBoolean("estado")); lista.add(obj); } } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (cn != null) { cn.close(); } if (rs != null) { rs.close(); } if (ps != null) { ps.close(); } } catch (Exception ex) { } } return lista; } public int contarTotal() { String sql = "Select Count(*) From Cargo"; try (PreparedStatement ps = cn.prepareStatement(sql)) { ResultSet rs = ps.executeQuery(); if (rs.next()) return rs.getInt(1); } catch (SQLException e) { e.printStackTrace(); } return 0; } public int getNoOfRecords() { return noOfRecords; } }
      Página JSP
      caminho: \web\views\cargos\cargos.jsp
      <%@page contentType="text/html" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <jsp:include page="../../estilo/header.jsp" /> <jsp:include page="../../estilo/menu.jsp" /> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <section class="content-header"> <h1>Página Cargos</h1> </section> <!-- Content Header (Page header) --> <section class="content-header"> <a href="srvCargos?accion=novo" class="btn btn-success"> <i class="fa fa-plus"></i> Novo Cargo </a> <ol class="breadcrumb"> <li><a href="srvCargos?accion=index"><i class="fa fa-dashboard"></i> Inicio</a></li> <li class="active">Cargos</li> </ol> </section> <section class="content"> <div class="box"> <div class="box-header with-border"> <h3 class="box-title">Lista de Cargos</h3> </div> <div class="box-body"> <div class="table-responsive" > <table class="table table-bordered table-striped dataTable table-hover" id="tablaCargos"> <thead> <tr> <th>Código</th> <th>Descrição</th> <th>Estado</th> <th>Ação</th> </tr> </thead> <tbody> <c:forEach items="${cargos}" var="item"> <tr> <td>${item.idCargo}</td> <td>${item.nombreCargo}</td> <c:if test="${item.estado == true}"> <td><span class="badge bg-green active">Ativo</span></td> </c:if> <c:if test="${item.estado == false}"> <td><span class="badge bg-red active">Inativo</span></td> </c:if> <td> <a href="srvCargos?accion=buscar&id=${item.idCargo}" class="btn btn-info btn-sm"> <i class="fa fa-edit"></i> </a> <a href="srvCargos?accion=eliminar&id=${item.idCargo}" onclick="return confirm('Deseja Realmente Excluir o Cargo com id ${item.idCargo}')" class="btn btn-danger btn-sm"> <i class="fa fa-trash"></i> </a> </td> </tr> </c:forEach> <c:if test="${cargos.size() == 0}"> <tr class="text-center"> <td colspan="6">Nenhum Registro Enconrado.</td> </tr> </c:if> </tbody> </table> <!--Aqui está o erro ===> a parte de Navegação não mostra--> <nav> <ul class="pagination"> <c:if test="${paginaActual > 1}"> <li class="page-item"><a class="page-link" href="srvCargos?accion=listarCargos?page=${paginaActual - 1}">Anterior</a></li> </c:if> <c:forEach var="i" begin="1" end="${totalPaginas}"> <li class="page-item ${i == paginaActual ? 'active' : ''}"> <a class="page-link" href="srvCargos?accion=listarCargos?page=${i}">${i}</a> </li> </c:forEach> <c:if test="${paginaActual < totalPaginas}"> <li class="page-item"><a class="page-link" href="srvCargos?accion=listarCargos?page=${paginaActual + 1}">Siguiente</a></li> </c:if> </ul> </nav> </div> </div> </div> </section> <!-- /.content --> </div> <!-- /.content-wrapper --> <jsp:include page="../../estilo/footer.jsp" />
      Grato,

      Cesar
    • Por violin101
      Caros amigos, saudações.

      Por favor, alguém pode me dar uma explicação referente o Template AdminLTE + Java Netbeans.

      Após importar para o Sistema Web. o componente para a pasta:
      WEB PAGES
      |___> bower_components - fica apresentando ERRO em algumas subpastas.

      Como consigo corrigir esses erros ?

      At.te,

      Cesar
    • Por violin101
      Caros amigos, saudações.

      Estou com uma dúvida em Sistema WEB em Java.

      O Código abaixo está na Página index.jsp
      <%@page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"/> </head> </html>
      O problema são os caracteres especiais que não consigo corrigir.

      Como consigo converter os Caracteres para o Padrão Português(BR) ?

      Grato,

      Cesar
    • Por violin101
      Caros amigos, saudações.
       
      Estou escrevendo um Sistema Java Web e quando clico no Botão Salvar, o Java acusa esse erro:

      ERROR: Cannot invoke "Object.toString()" because the return value of "java.util.Map.get(Object)" is null
       
      Já tentei de várias formas resolver esse problema, mas não estou conseguindo.

      Por favor, alguém pode me ajudar identificar a origem e resolver o problema acima ?

      Grato,
       
      Cesar
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.