模型层需要提供数据选项,设置错误信息
关键代码
@NotEmpty(message = "请选择兴趣爱好") private String[] hobbies;
控制器层需要在显示视图前,通过model传递数据选项到视图层
数据代码
final static Map<String,String>SELECT_HOBBIES =Collections.unmodifiableMap(new LinkedHashMap<String,String>(){ private static final long serialVersionUID = 1L; { put("打球","打球"); put("听歌","听歌"); put("玩游戏","玩游戏"); put("写代码","写代码"); put("吃烧烤","吃烧烤"); } });
关键代码
@GetMapping("/adduser") public String showAddUserForm(Model model) { User user = new User(); user.setId(userDao.getMaxId()); model.addAttribute("user", user); model.addAttribute("selectItems", SELECT_HOMETOWN);//通过此行设置信息到视图层 return "add-user"; }
视图层循环显示
关键代码
<select th:field="*{hobbies}" multiple="multiple" size="3" class="form-control"> <option th:each="item : ${multipleItems}" th:value="${item.value}" th:text="${item.key}" /> </select>
详情列表显示代码
<td><p th:each="h:*{user.hobbies}" th:text="${h}"></p></td>