需求是这样的:我有一张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>
这样就实现了下拉菜单显示的完整过程。。。