【问题标题】:Creating drop down menu and form in Thymeleaf在 Thymeleaf 中创建下拉菜单和表单
【发布时间】:2015-10-08 07:23:55
【问题描述】:

我想创建一个下拉菜单,允许客户端通过下拉菜单中指定的字段搜索用户。例如,按州搜索、按城市搜索等。

这是我目前所拥有的:

<p>Search options:</p>
<form action="#" th:action="@{/get/{value}" method="get">
    <select>
        <option th:value="AllUsers">Search all users</option>
        <option th:value="ByUsername">Search by user name</option>
        <option th:value="ByFirstname">Search by first name</option>
        <option th:value="ByLastname">Search by last name</option>
        <option th:value="ByAddress">Search by address</option>
        <option th:value="ByCity">Search by city</option>
        <option th:value="ByState">Search by state</option>
        <option th:value="ByZipCode">Search by zip code</option>
        <option th:value="ByPhoneNumber">Search by phone number</option>
        <option th:value="ByEmail">Search by email</option>
    </select>
    <input type="text" th:field="value" name="searchField"/>
    <input type="submit" value="Search" name="searchButton"/>
</form>

我只是不知道如何连接下拉列表中当前选定项目的actionvalue 标记以指定URI。如果用户选择,按州搜索,输入“马里兰”,如何指定对应的URI标签?

这将是我在 Spring 中执行操作的方法:

@RequestMapping(value = "/get/ByState", method = RequestMethod.GET)
public String getByState() {
    // ...
}

@RequestMapping(value = "/get/ByCity", method = RequestMethod.GET)
public String getByCity() {
    // ...
}

【问题讨论】:

    标签: html spring spring-mvc thymeleaf


    【解决方案1】:

    因为接受的答案没有使用 Thymeleaf,而且这个问题在 Google 中排名第一,所以我在这里添加我的解决方案。

    在我的情况下,statues 是一个枚举值列表。模型属性像在 Spring 中一样被填充:

    mav.addObject("statuses", EnumSet.allOf(Status.class));
    

    组有一个状态类型的字段(枚举)。

    <div class="form-group row">
        <select class="form-control" id="status" name="status">
            <option th:each="stat : ${statuses}"
                    th:value="${stat}"
                    th:text="${stat}"
                    th:selected="${stat.equals(group.status)}"/>
        </select>
    </div>
    

    这会自动填充列表并选择在我的 Group 实例中选择的值:

    【讨论】:

    • 这里的组是什么&& group.status 意味着什么?在百里香中分组是关键字吗/
    • 答案是:组有一个状态类型的文件(枚举
    • 是的,谢谢.. 通过此更改,我可以在 UI 上显示选定的值,但 ENUM 中的剩余值没有被填充?有没有办法做到这一点 ?现在我的下拉列表只包含一个值(男性代表性别),我需要显示所有值男性、女性,并让用户能够在填充之前选择的值后更改它
    • 这就是mav.addObject("statuses", EnumSet.allOf(Status.class)); 的用途。 mav 是 ModelAndView 对象。
    • 啊,明白了。谢谢
    【解决方案2】:

    您在此链接中只有所需的答案:

    http://fruzenshtein.com/spring-mvc-form-select-tag/

    【讨论】:

    • 链接中的这篇文章使用的是JSP,不是Thymeleaf
    • 不使用百里香。
    猜你喜欢
    • 2020-09-02
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多