Spring + Javascript

Asked

Viewed 455 times

-1

I have a JSP form, in which I embed Javascript, and once I do client-side validations, I created a Java function "save(param)".
When clicking on the save button, the function Avascript "save(param)" is invoked, which in turn first invokes the function that calls the data of the object to be saved through the "validate()" method and finally triggers the controller method (save()) that saves the object.

The bug that is occurring is that once this method save() from the controller, takes the object to be saved as parameter, when triggering this same method via javaScrip(save(param), Note param=Object to be saved), param arrives in the empty controller, or as null object.

I also tried to capture this object to be saved, using a HttpServletRequest, as follows:

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

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

I don’t understand why the object is getting there in the save() method of my controller (type gamentoaction) as null

My Form JSP:

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

<script type="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>

Typopagamentovo()

package Iim.sigra.model.parametrizacao.type;

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 = "TYPE") public class Typopagamentovo {

@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);
}

}

  • Edit your question and add class code TipoPagamentoVO, please.

  • Viva @Felipe Marinho! All right? I edited my question, I don’t know if it’s clearer now, the fact is that the object to be saved is coming in my action as null and so can’t be saved. Thank you very much for your attention. Please ask for your help

1 answer

0

To Expression language is processed on the server side. In the section below, when you use the expression ${tipopagamento}, the server will invoke the method toString of the class and pass as argument to the save method. This way, your save method will always use the parameter you set on the server, and will never take the parameters of inputs.

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

In your request POST:

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

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

Since you apparently redirect the page on your controller, there is no need for the call to be asynchronous ($.post). You could just use the input type Submit to send data and use jQuery to intercept sending and validate 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>

    <script type="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>
  • @Filipe Marinho worked very hard from the bottom of his heart. His correction was a kind of watershed. The fact is, I’m new to Spring and I’ve hardly ever messed with Jquery, so I end up making elementary mistakes. Now after your tip I’m advanced, may God grant you more knowledge and willingness to share that same knowledge.

  • much working from the bottom of the heart. Its correction was a kind of watershed. The fact is, I’m new to Spring and I’ve hardly ever messed with Jquery, so I end up making elementary mistakes. Now after your tip I’m advanced, may God grant you more knowledge and willingness to share that same knowledge.

  • hint: If I already have a Typopagamentovo object saved in the BD and I can do Reftrieve to load it in the form, I need to edit that same object as I would to pass it as parameter, because in my controller I have a method "update (type)", I can easily send controller objects to the form, but my difficulty is to find the form object for the controller. cmprmntos!

  • @gtamele Just put you in the properties name of tags input the name of the corresponding attribute in your class. This way, Spring will populate the fields of your object with the form values when sent. As this is an update, you must have in your form the identifier of the object (in this case selfId). If you don’t want the user to see the identifier, you can put it on a input type="hidden", example: <input type="hidden" name="selfId" value="${tipopagamento.selfId}">.

  • ! Long live Illustrious, greatly relieved by your patience. Just to clarify k I do CRUD of the Object in the same form, and I have a button p save: <input type="Submit" value="Save" >, when I do save, the object reaches the controller c/ data and Spring populates the Obejcto fields. I have another button in the same form p Update Object:<input type="button" value="Update" onclick="update();">. By clicking this button, a Javascript method k is invoked to validate and finally trigger the update method (typopagamentovo typopagamento). The scream is k ...

  • !..Berro is k the typed object reaches the empty controller. So I would like to know how to proceed to ensure that the object arrives populated with the data of the form fields? I ask you once again to speak

  • ! Another aspect, comfort said that I use the same form, so in relation to the <input type="Hidden" name="selfId" value="${typopagamento.selfId}"> when the operation is save, there is a bug: Field error in Object 'typoPagamentoVO' on field 'selfId': Rejected value [];. How to get around this error?

  • @gtamele I don’t know how you’re doing the request to update the object, but I suppose it’s through jQuery. If this is true, the problem must be caused by the way you are sending the data. When you make a POST request by jQuery, the parameters should be assigned to a variable called data. To get the form data, you need to pick up the form by id and use the method serialize. Take a look in this example and use it as a template.

  • @gtamele About the error when saving: the id should only be sent in the update. Because your class identifier is automatically generated, it cannot be filled in at the time of persisting the object. It may be simpler to create separate pages to create and update.

  • Viva @Felipe Marinho! I was doing it this way, my jsp: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script type="text/javascript" >

  • Viva @Felipe Marinho! I was doing it this way, my jsp:<script> Function update(type){ if (!validate()) {Return;} $. post("update", {'typopagamento': typopagamento}); } </script> <body> <input type="button" id="Update" value="Update" onclick="update(${typing});" > </body>

  • Just like this, according to your recommendation,ñ I know what can be wrong so Pork the button does not charge action: <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <type script="text/javascript" > $("#Update"). click(Function()' $. post("update.html", $("#typPagamentoForm").serialize(), Function(data) { Alert(data); }); }); </script></head> <body> <! -- Things-> <input type="button" id="Update" value="Update" > <! -- Things-> </body>

  • On the Controller side: @Controller @Requestmapping(value={"/typesetting"}) public class Typegamentoaction { @Requestmapping(value="/update", method= {Requestmethod.POST, Requestmethod.GET}) public string update(Typegamentovo type, user user) throws Exception{ Typegamentodao = new Typegamentodao(); dao.update(type, user); Return "redirect:"; } }

Show 8 more comments

Browser other questions tagged

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