Search code examples
javaspringthymeleaf

Spring Thymeleaf shortening url (form - get) parameters


Current state :

https://localhost:8443/workaround/?query=dasda&atn=s&filterSoftwareType=ANY.....

Desired state : https://localhost:8443/workaround/?q=dasda&atn=s&fst=ANY.....

Shorten url by using q instead of query and fst instead of filterSoftwareType

My thymeleaf html looks like this, short sample :

<form action="#" class="card card-sm rounded"
                  method="get"
                  th:action="@{${T(com.bisciak.workaround.util.Utils).MAPPING_INDEX}}" th:object="${search}">

     <div class="col">
           <input class="form-control form-control-lg form-control-borderless"
                               placeholder="Search here"
                               style="padding-left: 1rem"
                               th:field="${search.query}" type="search"/>
     </div> etc...

Controller :

  @GetMapping(value = Utils.MAPPING_INDEX, params = "atn=s")
 public ModelAndView indexActionSearch(@ModelAttribute(name = "s") Optional<Search> search .....

Search object has properties like query etc, bud I dont want to rename those for sure! It would be just horrible naming thruought the code I only want to use short versions for URL.

Anyone has idea how to do this? I have tried name attribute on input bud that didnt helped :/.

I also want to keep stuff in the form so url is automatically build. I also want to keep this as get and not a post so user can share easily this link via copy paste etc from URL bar. With post he would not see that.


Solution

  • The th:field attribute is to easily build a form from a Java object, and for the fields to post back using same names so the values can be auto-assigned back into a Java object, of the same type, on the server.

    If you want different names, then you're not using it for it's intended purpose, so stop using it.

    If you look at the documentation, i.e. chapter 7.2 Inputs, you see what th:fields does:

    Let’s see now how to add an input to our form:

    <input type="text" th:field="*{datePlanted}" />
    

    ... In this case (input[type=text]), the above line of code is similar to:

    <input type="text" id="datePlanted" name="datePlanted" th:value="*{datePlanted}" />
    

    So, change your code to do this:

    <form ... th:object="${search}">
    
        <input ... name="q" th:value="*{query}"/>
    

    Whether you also need id="q" is up to you.

    Note that if you use th:value="${search.query}", then there is no need for th:object="${search}"