上次(中间隔了很久)做了一个用post请求获取数据库中的数据给ECharts使用的Demo,这次写一个用Action实现的。两种方法的转换很简单,只是多了Struts框架!
1.创建数据表
在上次创建的test数据库中新建line表,如下:
CREATE TABLE `line` ( `day` varchar(20) DEFAULT NULL COMMENT '日期',`num` int(11) DEFAULT NULL COMMENT '出游人数' ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2.导入Struts相关包
在上次创建的echarts_demo项目中,导包,分别是:
commons-logging-1.0.4.jar
freemarker-2.3.8.jar
ognl-2.6.11.jar
struts2-core-2.0.14.jar
xwork-2.0.7.jar
3.创建Bean对象
在com.lgw.bean中创建Line对象,代码如下:
package com.lgw.bean; public class Line { private String day; //日期 private int num; //出游人数 public String getDay() { return day; } public void setDay(String day) { this.day = day; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } }
4.创建DAO
在com.lgw.dao中新建LineDao对象,作用是取MysqL中的数据,代码如下:
package com.lgw.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.sqlException; import java.util.ArrayList; import com.lgw.bean.Line; public class LineDao { /** * @author wen * * 查询所有出游人数数据 * @return 存放所有数据的线性表 */ public ArrayList<Line> query() { ArrayList<Line> lineArr = new ArrayList<Line>(); try { //JDBC方式连接MysqL数据库 Class.forName("com.MysqL.jdbc.Driver"); Connection conn = DriverManager.getConnection( "jdbc:MysqL://localhost:3306/test?characterEncoding=utf8","root",""); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM line"); ResultSet rs = stmt.executeQuery(); //将line表中的数据存储到线性表中 while(rs.next()) { Line line = new Line(); line.setDay(rs.getString("day")); line.setNum(rs.getInt("num")); lineArr.add(line); } //关闭连接 conn.close(); } catch (sqlException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return lineArr; } }
5.创建action
新建com.lgw.action包,在包中创建Action对象,代码如下:
package com.lgw.action; import java.util.ArrayList; import com.lgw.bean.Line; import com.lgw.dao.LineDao; import com.lgw.util.Toolkit; import com.opensymphony.xwork2.ActionSupport; public class LineAction extends ActionSupport { private String day; private String num; public String getDay() { return day; } public void setDay(String day) { this.day = day; } public String getNum() { return num; } public void setNum(String num) { this.num = num; } @Override public String execute() throws Exception { LineDao lineDao = new LineDao(); ArrayList<Line> lineArr = lineDao.query(); ArrayList<String> dayArr = new ArrayList<>(); ArrayList<Integer> numArr = new ArrayList<>(); for(int i=0; i<lineArr.size(); i++) { dayArr.add(lineArr.get(i).getDay()); numArr.add(lineArr.get(i).getNum()); } this.day = Toolkit.convertStringArray(dayArr); this.num = numArr.toString(); return lineArr!=null && !lineArr.equals("") ? SUCCESS : ERROR; } }
在JSP中,一切皆为字符串。在JavaScript中,ECharts的构建使用的数据是字符串,即可以在JSP中通过获取request对象中的字符串来构建图表。因此,这里在Action中定义两个字符串day和num。例如,day字符串的值为:['2016-11-01','2016-11-02','2016-11-03','2016-11-04','2016-11-05','2016-11-06','2016-11-07','2016-11-08','2016-11-09','2016-11-10'],num字符串的值为:[2000,1500,1000,500,2000,2500,3000,3500,4000,5000]。但是注意,构建字符串的ArrayList数组中的元素如果也是字符串,那么应该给数组元素加单引号,经过测试如果不加单引号,则JavaScript会将其解析成你不希望的数据,所以,我还定义了一个工具类,新建com.lgw.utils.Toolkit.java,代码如下:
package com.lgw.util; import java.util.ArrayList; public class Toolkit { public static String convertStringArray(ArrayList<String> str) { StringBuffer result = new StringBuffer(); result.append("["); int i; for(i=0; i<str.size()-1; i++) { result.append("'"+str.get(i)+"',"); } result.append("'"+str.get(i)+"']"); return result.toString(); } }
6.配置struts
在src目录下,新建struts.xml,为上面创建的Action做配置,代码如下:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="default" extends="struts-default"> <action name="lineAction" class="com.lgw.action.LineAction"> <result name="success">/test_line.jsp</result> <result name="error">/test_line.jsp</result> </action> </package> </struts>
7.配置web.xml
不用忘了为Struts添加过滤器,与上次Servlet整合之后的web.xml代码如下:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <welcome-file-list> <welcome-file>test_line.jsp</welcome-file> </welcome-file-list> <!-- 注册servlet --> <servlet> <servlet-name>barService</servlet-name> <servlet-class>com.lgw.servlet.BarService</servlet-class> </servlet> <servlet-mapping> <servlet-name>barService</servlet-name> <url-pattern>/bar.do</url-pattern> </servlet-mapping> <!-- Struts配置 --> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.FilterDispatcher </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
8.创建页面
创建test_line.jsp,展示我们的ECharts图表,代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; String day = (String)request.getAttribute("day"); String num = (String)request.getAttribute("num"); %> <!DOCTYPE> <head> <Meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Hello ECharts</title> <!-- 使用单文件引入的方式使用ECharts.JS --> <script src="echarts-all.js"></script> <script src="jquery.js"></script> </head> <body> <form action="lineAction.action" method="post"> <input type="submit" value="查看折线图" /> </form> <!-- DOM用来设置展示ECharts图表的区域 --> <div id="myDiv" style="height: 400px"></div> <script type="text/javascript"> var myChart = echarts.init(document.getElementById('myDiv'),'macarons'); var data_x = <%=day%>; var data_y = <%=num%>; var option = { tooltip : { show : true },legend : { data : [ '出游人数' ] },xAxis : [ { type : 'category',data : data_x } ],yAxis : [ { type : 'value',} ],series : [ { name : '出游人数',type : 'line',data : data_y } ] }; //设置option myChart.setOption(option); </script> </body>
9.部署项目到tomcat
在tomcat中运行echarts_demo项目,在浏览器中输入http://localhost:8080/echarts_demo,运行结果如下: