需求是這樣的:我有一張charts表,屬性有type,name之類,type類型可以有很多種,如1,2,3.......同時charts表中有很多又有相同的type,如chart1的類型是1,chart2的類型是1,chart3的類型是1,chart4的類型是2.......在下拉菜單中,我的類型只想顯示1,2,3......而不是1,1,1,2.......接下來我們就來在chartDao中實現這個功能。
dao中代碼如下:首先用distinct實現去重,得到1,2,3.......但是首先要新建一個類Types,代碼如下
public class Types { private String type; public String getType() { return type; } public void setType(String type) { this.type = type; } }
@SqlQuery("select distinct(type) type from vis_chart") List<Types> getTypes();
這樣之後就再到Service(此處我用的是spring mvc框架)
public List<Types> getTypes() { ChartDao chartDao = dbi.onDemand(ChartDao.class); return chartDao.getTypes(); }
再到Controller:
@RequestMapping("charts" ) public String chartList(Model m) { List<Types> types = chartService.getTypes(); List<Chart> charts = chartService.findAllCharts(null,null); m.addAttribute("types",types); m.addAttribute("charts",charts); return ADMIN_HOME + "charts"; }通過Model將Types傳到jsp中。
jsp代碼如下:
<select id="selectType" class="form-control"> <option value="please">請選擇</option> <c:forEach items="${types}" var="t"> <option value="${t.type}">${t.type}</option> </c:forEach>這樣就實現了下拉菜單顯示的完整過程。。。