grails ui的插件功能众多,可以完成很多效果比如bar图、柱状图、拖拽、菜单、richEditor文本编辑等等。
我的目的是使用该插件实现柱状图,hql语句如下:
def hql ="select p.sellTime,sum(p.pureProfits) from Profit p where p.sellTime >= current_date()-7 and p.sellTime <= current_date() group by p.sellTime"
然后得到resultList:def resultList = Profit.executeQuery(hql)
我要在action中将resultList直接传到页面上:[profitChartList: resultList]
这样的做法导致,页面读取不到数据。
因为<gui:columnChart>标签中data属性存放的是一个二维数组。我们需要将resultList的结果改造成二维数组。做法如下:
def dataList = []
resultList.each { s->
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd")
def dateStr = sdf.format(s[0])
def bar = ['date': dateStr, 'pureProfit':s[1]]
dataList << bar
}
这里有必要贴出领域模型Profit类的代码:
class Profit {
BigDecimal pureProfits //每次卖出商品的纯利润
Date sellTime
}
我们看到sellTime是Date型的,但是在<gui:columnChart>标签中显示不出Date型的值,因此我把它转成String类型存放到数组中。
至此,该action已经完成,完整代码如下:
def weekColumnChar ={
def hql ="select p.sellTime,sum(p.pureProfits) from Profit p where p.sellTime >= current_date()-7 and p.sellTime <= current_date() group by p.sellTime"
def resultList = Profit.executeQuery(hql)
def dataList = []
resultList.each { s->
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd")
def dateStr = sdf.format(s[0])
def bar = ['date':dateStr, 'pureProfit':s[1]]
dataList << bar
}
[profitChartList: dataList]
}
前台gsp页面如下:
<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="layout" content="main" />
<title>最近七天利润柱状图</title>
<gui:resources components="['chart']" mode='debug'/>
</head>
<body class='yui-skin-sam'>
<div class="nav">
<span class="menuButton"><g:link class="home" controller="management" action="main">返回主菜单</g:link></span>
</div>
<div class="body">
<h1>最近七天利润柱状图</h1>
<div id='columnChart' style="width:600px; height: 300px"></div>
<gui:columnChart
id='myColChart'
renderTo="columnChart"
data="${profitChartList}"
seriesDefs="[
[
pureProfit:'The pure profit',
style:[
image: 'images/tube.png',
mode: 'no-repeat',
color: 0xc2d81e,
size: 40
]
]
]"
style="[
border: [color: 0x96acb4, size: 12],
font: [name: 'Arial Black', size: 14, color: 0x586b71],
dataTip:
[
border: [color: 0x2e434d, size: 2],
font: [name: 'Arial Black', size: 13, color: 0x586b71]
],
xAxis:
[
color: 0x2e434d
],
yAxis:
[
color: 0x2e434d,
majorTicks: [color: 0x2e434d, length: 4],
minorTicks: [color: 0x2e434d, length: 2],
majorGridLines: [size: 0]
]
]"
/>
</div>
</body>
</html>
效果图如下:
实现bar状图也是同样的道理,我实现的效果图如下: