Multi Select Drop Down with check box example:
How to convert below html code to thymeleaf to display in Spring controller
Select Hobby Type :
<form action="#" th:action="@{/display}" method="POST">
<div class="container">
<p><strong>Select Hobbies(Multiple):</strong>
<select id="multiple-hobbies" multiple="multiple">
<option value="reading">Reading</option>
<option value="cricket">Cricket</option>
<option value="cooking">Cooking</option>
<option value="movies">Watching Movies</option>
<option value="music">Listening Music</option>
<option value="sleeping">Sleeping</option>
</select>
</p>
<input type="submit" value="submit"/>
</div>
</form>
I implemented the following ,it works succesfully
<form action="#" th:action="@{/display}" th:object="${hobbyobj}" method="POST">
<div class="container">
<p><strong>Select Hobbies(Multiple):</strong>
<select id="multiple-hobbies" th:field="*{hobbieslist}" multiple="multiple">
<option th:each="hobby: ${predefinedhobbylist}"
th:value="${hobby}" th:text="${hobby}">
</select>
</p>
<input type="submit" value="submit"/>
</div>
</form>
Controllers Class Implementation :
@Controller
public class HobbiesController {
private static final Logger logger = LoggerFactory.getLogger(HobbiesController.class);
@GetMapping("/")
public ModelAndView smartphoneselect(Model model) {
ModelAndView mav = new ModelAndView();
mav.setViewName("index.html");
mav.addObject("hobbyobj",new Hobby());
mav.addObject("predefinedhobbylist", gethobbieslist());
return mav;
}
@PostMapping("/display")
public ModelAndView hobbiesdisplay(@ModelAttribute Hobby hobby) {
ModelAndView mav = new ModelAndView();
mav.setViewName("display.html");
logger.info("Hobbies Selected:"+hobby.getHobbieslist());
mav.addObject("hobbiesselected",hobby.getHobbieslist());
return mav;
}
public List<String> gethobbieslist(){
List<String> hobbieslist=new ArrayList<String>();
hobbieslist.add("Reading");
hobbieslist.add("Cricket");
hobbieslist.add("Cooking");
hobbieslist.add("Sleeping");
hobbieslist.add("Waching Movies");
hobbieslist.add("Listening Music");
return hobbieslist;
}
}
Model class implemented as :
public class Hobby {
private List<String> hobbieslist;
public List<String> getHobbieslist() {
return hobbieslist;
}
public void setHobbieslist(List<String> hobbieslist) {
this.hobbieslist = hobbieslist;
}
}