【问题标题】:Spring Thymeleaf shortening url (form - get) parametersSpring Thymeleaf 缩短 url (form-get) 参数
【发布时间】:2019-05-28 19:06:53
【问题描述】:

当前状态:

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

期望的状态: https://localhost:8443/workaround/?q=dasda&atn=s&fst=ANY.....

使用 q 代替 query 和 fst 代替 filterSoftwareType 来缩短 url

我的 thymeleaf html 看起来像这样,简短的示例:

<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...

控制器

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

搜索对象具有查询等属性,但我不想重命名这些属性!通过我只想为 URL 使用简短版本的代码,这将是一个可怕的命名。

有人知道怎么做吗?我在输入芽上尝试了 name 属性,但没有帮助:/.

我还想保留表单中的内容,以便自动构建 url。 我还想将此保留为 get 而不是帖子,以便用户可以通过 URL 栏中的复制粘贴等轻松共享此链接。有了帖子,他就看不到了。

【问题讨论】:

    标签: java spring thymeleaf


    【解决方案1】:

    th:field 属性用于从 Java 对象轻松构建表单,并使用相同名称回发字段,以便可以将值自动分配回相同类型的 Java 对象,在服务器。

    如果你想要不同的名字,那么你并没有将它用于它的预期目的,所以停止使用它。

    如果您查看文档,即章节 7.2 Inputs,您会看到 th:fields 做了什么:

    现在让我们看看如何向表单添加输入:

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

    ...在这种情况下(input[type=text]),上面这行代码类似于:

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

    所以,改变你的代码来做到这一点:

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

    您是否还需要id="q" 取决于您。

    注意,如果你使用th:value="${search.query}",那么就不需要th:object="${search}"

    【讨论】:

    • 该死的,就像你说的那样工作。谢谢这解决了我的问题!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-23
    • 2012-01-18
    • 1970-01-01
    相关资源
    最近更新 更多