How to call a Java method using jQuery?

Asked

Viewed 1,732 times

1

I need to call a method that adds in a ArrayList what the user reported in dynamically generated tags when clicking on "add". Any suggestions?

I was trying to do it using AJAX, but I haven’t succeeded yet. The value entered by the user is added to ArrayList, but when adding one more the first is no longer there, it seems that instance the action again.

I don’t know much about Struts 2 or AJAX.

Page JSP:

<table  id="tabelaCanais" style="width: 100%" class="tabela_interna">
                <tbody>
            <tr>
                <th colspan="3">Canal / Vigência</th>
            </tr>
                <tr>
              <th colspan="1"  align="center">Canal de Venda</th>
              <th  colspan="1"   align="center">Vigência</th>
              <th   align="center">Ações</th>
            </tr>
            <tr>

                <td colspan="" width="40%" align="center">  
                    <s:select name="vigenciaCanalVendaVO.canalVendaVO.nome" id="canal" value="vigenciaCanalVendaVO.canalVendaVO.nome" list="listaDeCanais" headerKey="0"  listKey="codigo" listValue="nome"/>
                </td>
                <td width="40%" align="center">
                     <s:textfield name="vigenciaCanalVendaVO.dataInicioVigencia" id="dataInicioVigencia" data-mask="data" data-date-type="default" size="12"/>
                     Até
                     <s:textfield name="vigenciaCanalVendaVO.dataFimVigencia" id="dataFimVigencia" data-mask="data" data-date-type="default" size="12"/>

               </td>
                <td align="center" width="10%">
                    <img src="<c:url value="/includes/images/bt_adicionar.gif" />" id="associar1"   style="cursor:pointer;cursor:hand;"/>
               </td>                    
            </tr>


    </tbody>
   </table>
        <br/><br/><br/><br/>
    <table id="tabela_botoes" style="width: 100%">
        <tr>
            <td align="center" width="100%">
                <img src="<c:url value="/includes/images/bt_incluir.gif" />" id="incluir" style="cursor:pointer;cursor:hand;"/>

File . js

$(document).ready(function(){ 

$("#siglaanterior").hide();
$("#nomeanterior").hide();

    $("#associar1").on("click", function(e){
            e.preventDefault();
            var codigo = $('#canal').val();
            var  dataInicioVigencia = $("#dataInicioVigencia").val();
            var dataFimVigencia = $("#dataFimVigencia").val();

            var rowCount = ($("#tabelaCanais tr").length - 3);
            var counts=rowCount;

            $("#canal option[value='"+$("#canal").val() +"']").remove();

            alert('Estou aqui'+$('#canal').val()+"  "+     $('#dataInicioVigencia').val()+"  "+$('#dataFimVigencia').val());
                     var coluna = "<tr>";
                     coluna += "<td width='40%'  align='center'><input type='text' id='id1'  value= "+$("#canal").val()+" name='vigenciaCanalVendaVO.canalVendaVO.codigo'/></td>";
                     coluna +="<td width='40%'  align='center'><input type='text' data-mask='data' data-date-type='default' size='12' maxlength='10'  value="+$("#dataInicioVigencia").val()+" name='vigenciaCanalVendaVO.dataInicioVigenciaAssociacaoPlano'/>"
                     coluna +="At&eacute;<input type='text'  data-mask='data' data-date-type='default' size='12' maxlength='10'  value="+$("#dataFimVigencia").val()+" name='vigenciaCanalVendaVO.dataFimVigenciaAssociacaoPlano'/></td>";
                     coluna +="<td align='center'><img src='/EEDI-Administrativo/includes/images/bt_remover.gif' id='remover' style='cursor:pointer;cursor:hand;'/></td>";
                     coluna += "</tr>";
                     //alert(coluna);


                ($('#tabelaCanais')).append(coluna);


                $.ajax({
                    type: "POST",
                    url:  $.url.get('salvarRelacaoCanalVendaPlano'  ),
                    data: {'vigenciaCanalVendaVO.canalVendaVO.codigo':$("#canal").val(), 'vigenciaCanalVendaVO.dataInicioVigenciaAssociacaoPlano' : $("#dataInicioVigencia").val(),
                        'vigenciaCanalVendaVO.dataFimVigenciaAssociacaoPlano':$("#dataFimVigencia").val()},
                    beforeSend: function() {
                            bloquearTela();
                    },
                    complete: function() {
                            desbloquearTela();
                    } ,success: function(data) {

                        //alert('sucess');

                    },
                    error: function(data){
                        alert('error');
                    }

                });       
    });
});

Struts . xml

<?xml version="1.0" encoding="UTF-8" ?>

<package name="plano" namespace="/plano" extends="default">

    <!-- Consulta de Plano -->
    <action name="listarPorFiltro" class="planoAction" method="listarPorFiltro">
        <result>/WEB-INF/pages/plano/consultar.jsp</result>
        <result name="input">/WEB-INF/pages/plano/consultar.jsp</result>
    </action>


    <!-- Cadastro de Plano -->
    <action name="iniciarIncluir" class="planoAction" method="iniciarIncluir">
        <result>/WEB-INF/pages/plano/incluir.jsp</result>
    </action>
    <action name="incluir" class="planoAction" method="incluir">
        <result type="saveErrorsAndRedirectAction">listarPorFiltro</result>
        <result name="input">/WEB-INF/pages/plano/incluir.jsp</result>
    </action>


        <!--Adicionar relação canal e plano -->
    <action name="salvarRelacaoCanalVendaPlano" class="planoAction" method="salvarRelacaoCanalVendaPlano">
            <result>/WEB-INF/pages/plano/incluircanal.jsp</result>
            <result name="input" >/WEB-INF/pages/plano/incluircanal.jsp</result>
    </action>

Action called:

@Controller
@Scope("request")
public class PlanoAction extends BaseAction {

    private static final long serialVersionUID = -1161409943678292285L;
    private static final Logger LOGGER = LoggerFactory.getLogger(PlanoAction.class);
    private List<PlanoVO> listaDePlanos;
    private List<String> listaDeStatus;
    private FiltroPlanoVO filtro = new FiltroPlanoVO();
    private PlanoVO planoVO = new PlanoVO();
    private Collection<VigenciaCanalVendaVO>listaDeVigenciasCanalVendaVO;
    private CanalVendaVO canalVendaVO = new CanalVendaVO();     
    private VigenciaCanalVendaVO vigenciaCanalVendaVO = new VigenciaCanalVendaVO(); 
    private Integer codigo;
    private LocalDate dataInicioVigencia;
    private LocalDate dataFimVigencia;
    //private Ca
    private List<CanalVendaVO> listaDeCanais;
    private List<PlanoVO> canaisPlano;
    private Map<String, String> mapTipoCobrancaEValor = Maps.newHashMap();
    private Map<String, String> mapTipoCobrancaEPeriodoCarencia = Maps.newHashMap();

    @Autowired
    private transient PlanoServiceFacade planoServiceFacade;

    @Autowired
    private transient CanalVendaServiceFacade canalVendaServiceFacade;

    @Autowired
    private transient VigenciaCanalVendaServiceFacade vigenciaCanalVendaServiceFacade;


    public String salvarRelacaoCanalVendaPlano(){
        listaDeCanais = canalVendaServiceFacade.listar();       

        planoVO.getListaDeVigenciasCanalVendaVO().add(vigenciaCanalVendaVO);

        return SUCCESS;
    }

    public String incluir() {

        //obter as informações de valores do plano (Titular/Dependente) por tipo de cobrança (Mensal/Anual)
        //capturarListaTipoCobrancaEValorDoPlano(Arrays.asList(TipoCobranca.values()));
        listaDeCanais = canalVendaServiceFacade.listar();
        //incluir as informações do plano 
        planoServiceFacade.incluir(planoVO);
        vigenciaCanalVendaServiceFacade.incluir(planoVO.getListaDeVigenciasCanalVendaVO());

        //exibir mensagem de sucesso após o cadastro do plano
        sucesso("msg.sucesso.cadastro", "Plano");

        return SUCCESS;
    }

2 answers

4

All your controller is instantiated again to each request, including these requests you make by Ajax, because its scope is "request" (@Scope("request")). So in the second Ajax request the data you set in the first is no longer there.

Switch to a more comprehensive scope such as "view" (in Struts it is called ConversationController and the controller instance is maintained while the user is on the page, on the same browser tab) or switch to "Session" (once created, the controller instance is maintained throughout the user session lifecycle).

See that this can affect in various ways the logic of your application.

0

Thank you for the reply!

We ended up seeing that we could keep the list in the session like this too :

List<VigenciaCanalVendaVO> listaVIgenciaCanalVenda = (List<VigenciaCanalVendaVO>) getRequest().getSession().getAttribute("listaVigenciaCanalVenda");

    if(listaVIgenciaCanalVenda == null){
        listaVIgenciaCanalVenda = new ArrayList<VigenciaCanalVendaVO>();
    }    listaVIgenciaCanalVenda.add(vigenciaCanalVendaVO);                                       getRequest().getSession().setAttribute("listaVigenciaCanalVenda",listaVIgenciaCanalVenda);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.