Spring MVC and Thymeleaf - how to retrieve selected value in dropdown menu
How to get selected value in dropdown menu in Thymeleaf and execute Spring MVC process?
Here is my thymeleaf code:
<form style="display:inline-block" th:action="@{/search}"
th:object="${searchOptions}" method="get">
<select id="optionsList" name="optionsListId">
<option th:each="option : ${searchOptions}"
th:value="${option.getOption()}"
th:text="${option.getOptionName()}"
th:selected="${selectedOptionsList.contains(option.getOption())}">Options</option>
</select>
</form>
"SearchOptions" is the name of the model attribute, which is an ArrayList of objects SearchOption
.
Here is the SearchOptions class:
package formBeans;
public class SearchOption {
private String option;
private String optionName;
public SearchOption() {
}
public SearchOption(String option, String optionName) {
this.option = option;
this.optionName = optionName;
}
public String getOption() {
return option;
}
public String getOptionName() {
return optionName;
}
public void setOption(String option) {
this.option = option;
}
public void setOptionName(String optionName) {
this.optionName = optionName;
}
}
How to write code with Spring mvc to retrieve selected value in dropdown. I tried looking for examples on the internet and they didn't help.
thank
source to share
Controller:
searchOptions
contains only data for generating option items. selectedOption
must be added to the model before the form is displayed and at the endpoint of the view.
@RequestMapping("/myFormPage")
public String myFormPage(
Model model,
@ModelAttribute("selectedOption") SearchOption selectedOption) {
List<SearchOption> searchOptions = new ArrayList<>();
searchOptions.add(new SearchOption("option1", "optionName1"));
searchOptions.add(new SearchOption("option2", "optionName2"));
model.addAttribute("searchOptions", searchOptions);
return "myFormPage";
}
@RequestMapping("/search")
public String search(
@ModelAttribute("selectedOption") SearchOption selectedOption) {
System.out.println(selectedOption.getOption());
return "search";
}
HTML:
On a form element, th:object="${selectedOption}"
specifies a model attribute that will be used to store view data. th:field="*{option}"
defines the selectedOption property to hold the selected value.
<form th:action="@{/search}" th:object="${selectedOption}" th:method="get">
<select th:field="*{option}">
<option th:each="option : ${searchOptions}"
th:value="${option.getOption()}"
th:text="${option.getOptionName()}">Options</option>
</select>
<button type="submit">submit</button>
</form>
source to share