Spring + JavaScript

-1

I have a JSP form, which embeds Javascript, and once I do the client side validations, I created a javaScript function "save (param)". When you click the save button, the "save (param)" javaScript function is invoked, which in turn first invokes the function that validates the data of the object to be saved through the "validate ()" method and finally activates the controller method save ()) that saves the object.

The bug that is occurring is that once this method save() of the controller receives the object to be saved as a parameter, by triggering this same method via javaScrip (save (param), Note param = Object to be saved), the param arrives at the empty controller, ie as a null object.

I also tried to capture this object to be saved, using an instance of HttpServletRequest , as follows:

tipopagamento = (TipoPagamentoVO) request.getSession().getAttribute(“tipopagamento”);

But in the same the object arrives nullo, even having passed the validation.

I do not understand why the object is getting there in the save () method of my controller (TypePayActionAction) to null

My JSP Form:

<script src="http://code.jquery.com/jquery-latest.min.js"></script><scripttype="text/javascript" >

function salvar(tipopagamento) {

    if (!validar()) return;

    $.post("tipopagamento/save?tipopagamento="+tipopagamento);
}



function validar(){

    if (document.getElementById('designacao').value == ''){
        alert("O campo 'Designacao' deve ser preenchido");
        return false;
    }
    if (document.getElementById('descricao').value == ''){
        alert("O campo 'Descricao' deve ser preenchido");
        return false;
    }                            

    return true;
}

</script>

</head>
<body>

    <form method="post" action="/sigra/tipopagamento/save" name="tipopagamentoForm"  modelAttribute="tipopagamento" > 


        <fieldset>
            <table width="100%">
                <tr>
                    <td>${statusMessage}</td>
                </tr>   
                <tr>
                    <td>
                        <fieldset>
                            <table>
                                <tr>
                                    <td width="15%">
                                        <label> Designa&ccedil;&atilde;o</label>
                                    </td>
                                    <td width="85">
                                        <span id="refresh_01">              
                                            <input type="text" id="designacao" name="designacao" style=" width: 100%" value="${tipopagamento.designacao}" >
                                        </span>
                                    </td>

                                </tr>
                                <tr>
                                    <td width="15%">
                                        <label>Descri&ccedil;&atilde;o</label>
                                    </td>
                                    <td width="85">
                                        <span id="refresh_02">
                                            <textarea name="descricao" id="descricao" rows="5" cols="40" style="width: 100%" >${tipopagamento.descricao}</textarea>
                                        </span>
                                    </td>
                                </tr>
                            </table>
                        </fieldset>
                    </td>
                </tr>
                <tr>
                    <td>
                        <fieldset>
                            <table>
                                <tr>
                                    <td>
                                <!--  <a id="save"  href="/sigra/tipopagamento/save.html" onclick="testFunction()">teste</a> -->    
                                    </td>
                                    <td>
                                        <input type="button" id="sa" value="Salvar" onclick="salvar(${tipopagamento});">    
                                    </td>
                                    <td id="abc">
                                        <input type="button" value="Limpar" onclick="limpar();">    
                                    </td>
                                    <td>
                                        <input type="button" value="Cancelar" onclick="testFunction();">    
                                    </td>
                                </tr>
                            </table>
                        </fieldset>
                    </td>
                </tr>

            </table>
        </fieldset>

    </form>
</body>

TypePayment ()

package iim.sigra.model.parametrizacao.tippagamento;

import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import javax.servlet.http.HttpServletRequest; import javax.validation.constraints.NotNull; import org.hibernate.annotations.GenericGenerator;

@Entity @Table (name="TIPOPAGAMENTO") public class PayPasswordVO {

@Id
@GeneratedValue(generator="increment")
@GenericGenerator(name="increment", strategy = "increment")
protected long selfId;

@NotNull
protected String designacao;
protected String descricao;


public TipoPagamentoVO() {

}

public TipoPagamentoVO(HttpServletRequest rq) {

    }


public TipoPagamentoVO(long SelfId, String designacao, String descricao){

    this.selfId = 0;
    this.designacao = designacao;
    this.descricao = descricao;

}

public long getSelfId() {
    return selfId;
}

public void setSelfId(long selfId) {
    this.selfId = selfId;
}

public String getDesignacao() {
    return designacao;
}

public void setDesignacao(String designacao) {
    this.designacao = designacao;
}

public String getDescricao() {
    return descricao;
}

public void setDescricao(String descricao) {
    this.descricao = descricao;
}

@Override
public boolean equals(Object object) {

    TipoPagamentoVO tipo = (TipoPagamentoVO) object;

    return (this.selfId==tipo.selfId && tipo.selfId!=0) || (this.designacao!=null && this.designacao.equalsIgnoreCase(tipo.designacao));
}

@Override
public String toString() {

    return "SelfId: "+this.selfId +","+" Designação: "+this.designacao +","+" Descrição: "+this.descricao;
}

}

My Controller:

@Controller
@RequestMapping(value={"/tipopagamento"})
public class TipoPagamentoAction {

@RequestMapping(method=RequestMethod.GET)
public ModelAndView listAllPagamentos(){

    ArrayList<TipoPagamentoVO> allTipoPagamentos = new ArrayList<TipoPagamentoVO>();
    TipoPagamentoDAO dao = new TipoPagamentoDAO();

    allTipoPagamentos = dao.getAll();

    return new ModelAndView("/tipopagamento/tipopagamento", "allTipoPagamentos", allTipoPagamentos);
}


@RequestMapping(value="/save", method= {RequestMethod.POST, RequestMethod.GET})
public  ModelAndView save(TipoPagamentoVO tipopagamento , UsuarioVO user, HttpServletRequest request) throws Exception{



    //  tipopagamento = (TipoPagamentoVO) request.getSession().getAttribute("tipopagamento");


    TipoPagamentoDAO dao = new TipoPagamentoDAO();
    ArrayList<TipoPagamentoVO> allTipoPagamentos = new ArrayList<TipoPagamentoVO>();

    dao.save(tipopagamento, user);
    allTipoPagamentos = dao.getAll();

    return new ModelAndView("/tipopagamento/tipopagamento", "allTipoPagamentos", allTipoPagamentos);
}

}

    
asked by anonymous 02.12.2017 / 11:52

1 answer

0

The expression language is rendered server-side. In the section below, when you use the expression ${tipopagamento} , the server will invoke the toString method of the class and pass as argument to the save method. That way, your save method will always use the parameter that you have stipulated on the server, and will never take parameters from inputs .

<input type="button" id="sa" value="Salvar" onclick="salvar(${tipopagamento});">

On your POST request:

$.post("tipopagamento/save?tipopagamento="+tipopagamento);

The value of tipopagamento is sent as a parameter of the GET method in toString format. Your controller does not know what to do.

As you apparently do a page redirect on your controller, there is no need for the call to be asynchronous ( $.post ). You could simply use the input type submit to send the data and use jQuery to intercept the submission and validate the information. Example:

Script

<head>  
    <!-- Resto do que você tem no seu head -->

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><scripttype="text/javascript" >

        function validar(){
            if (document.getElementById('designacao').value === ''){
                alert("O campo 'Designacao' deve ser preenchido");
                return false;
            }
            if (document.getElementById('descricao').value === ''){
                alert("O campo 'Descricao' deve ser preenchido");
                return false;
            }                            
            return true;
        }

        $(document).ready(function() {
            $("#tipoPagamentoForm").submit(function(e) {
                if(!validar()) {
                    e.preventDefault();
                }
            });             
        });
    </script>
</head>

Form

<form id="tipoPagamentoForm" action="/sigra/tipopagamento/save" method="POST">
    <label for="designacao">Designação:</label>
    <input type="text" id="designacao" name="designacao" style=" width: 100px" value="${tipopagamento.designacao}" >
    <br />

    <label for="descricao">Descrição:</label>
    <textarea name="descricao" id="descricao" style="width: 100px" >${tipopagamento.descricao}</textarea>
    <br />

    <input type="submit" />
</form>
    
04.12.2017 / 12:53