How to create a variable in thymeleaf and pass it to spring

2

Well, my problem is that I do not know how to declare a variable in thymeleaf and that it recognizes me spring with @Pathvariable. I leave the methods of the html and the controller. Thanks

This is the controller:

    @GetMapping(value = "/testing/{username}")
public String test2 (@PathVariable (value ="username") String user , Model model ) {
    model.addAttribute("titulo", user);     


    return "testing";

}

The html

<div class="form-group col-sm-6"> <input type="text" name="username" id="username" class="form-control" placeholder="UserName" autofocus required th:whith ="username "/> </div>

    
asked by Jorge 29.03.2018 в 23:15
source

1 answer

0

Actually it's very simple. You only need to add the data you want to your url. It has nothing to do with Thymeleaf, you can do it with jquery or for testing purposes directly with the browser.

According to the example you use, you can use the following as url:

localhost:8080/testing/rafaelRamirez

You can automate it with jquery. This is a simple example that I use:

$('.miBoton').click(function(event) {
        var a = $('.mi-input-que-coincide-con-la-info-que-quiero-mandar').value();

        var url = "localhost:8080/testing/"+a;
        //COMO TU CONTROLLER ESTA POR DEFECTO EN GET ESTO FUNCIONA CON
        //LA MISMA LÓGICA QUE LA URL DIRECTA EN EL NAVEGADOR.
        window.location.href = url;

    });

And you will receive the data in your controller. It can be improved so that you get the current variable and work with it for all the controller. For example:

testing/eliminar/{id}
testing/modificar/{id}

otro-testing/eliminar/{usuario}
otro-testing/modificar/{usuario}

The same works with POST and with GET, although with post you can serialize the form (with thymeleaf generating the template) and you receive it directly as an object plus the data of the URL that you pass. But that is another issue.

    
answered by 02.04.2018 в 17:18