环境:SpringMVC+spring+mybatis、前端数据来源为Oracle数据库Scott用户下的emp表
report.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html> <html> <head> <!-- 页面meta --> <meta charset="utf-8"> <title>highcharts测试</title> <script> var contextPath = "${pageContext.request.contextPath}"; var data = [ parseInt("${mapList[0]['NUM']}"), parseInt("${mapList[1]['NUM']}"), parseInt("${mapList[2]['NUM']}"), parseInt("${mapList[3]['NUM']}"), parseInt("${mapList[4]['NUM']}") ]; </script> <!-- 引入jQuery --> <script type="text/javascript" src="../js/jquery-1.8.0.js"></script> <!-- 引入highcharts.js --> <script type="text/javascript" src="../js/highcharts.js"></script> <!-- 引入自定义js --> <script type="text/javascript" src="../js/report.js"></script> </head> <body> <div> <!-- 柱状图容器 --> <div id="container" style=" 500px;height:400px;float:left"></div> <!-- 饼状图容器 --> <div id="container1" style=" 500px;height:400px;float:left"></div> </div> <div id="detail" style="clear: left"> </div> </body> </html>
report.js
$(function(){ // 初始化柱状图 $('#container').highcharts(initMcRete(data)); // 初始化饼状图 initPieChart(); console.log(contextPath); }); function initMcRete(data){ $('#container').highcharts({ chart: { type: 'column' }, credits: { enabled: false }, title: { text: "大标题" }, subtitle: { text: "小标题" }, xAxis: { type: 'category' }, yAxis: { min: 0, title: { text: '人数 (个)' } }, plotOptions: { series: { borderWidth: 0, dataLabels: { enabled: true, format: '{y}' } } }, series: [{ name: '各个职业人数统计', colorByPoint: true, data: [{ name: 'CLERK', y: data[0] }, { name: 'SALESMAN', y: data[1] }, { name: 'MANAGER', y: data[2] } ,{ name: 'ANALYST', y:data[3] } ,{ name: 'PRESIDENT', y: data[4] }] }] }); } function initPieChart() { var clickFunc = function(e) { var param = e.point.name; queryPieChartDetail(param); }; // 查询饼状图数据 queryData(function(response){ if (response.total <= 0) { $('#container1').html("<div class='nodata'>暂无数据!</div>"); } else { var data = [ ["800~2000", response['A1']], ["2001~4000", response['A2']], ["4001~6000", response['A3']] ]; //var total = data[0]+ data[1] + data[2]; $('#container1').highcharts(getOptions(data, clickFunc, "薪资分布饼状图")); } }); } function queryData(successCallback) { $.ajax({ type :"POST", dataType : "json", url : contextPath + "/employee/getPieChart", success : function(data) { successCallback(data); }, error : function(data) { alert("数据获取异常!" + data); return; } }); } function queryPieChartDetail(param) { $.ajax({ type :"POST", data : {"param" : param}, dataType : "json", async : false, url : contextPath + "/employee/getPieDetail", success : function(data) { var div = document.getElementById("detail"); var str = "<table border='1px'>"; str += "<th>empno</th><th>ename</th><th>job</th><th>sal</th>"; $.each(data, function (index, item) { str += "<tr>"; var empno = "<td>" + item.empno + "</td>"; var ename = "<td>" + item.ename + "</td>"; var job = "<td>" + item.job + "</td>"; var sal = "<td>" + item.sal + "</td>"; str += empno + ename + job + sal; str += "</tr>"; }); str += "</table>"; console.log(str); div.innerHTML = str; }, error : function(data) { alert("数据获取异常!" + data); return; } }); } function getOptions(data, clickFunc, title) { var noop = function(e) {}; clickFunc = clickFunc || noop; return { chart: { plotBackgroundColor: null, plotBorderWidth: null, plotShadow: false }, credits: { enabled: false }, title :{ text:title }, legend:{ verticalAlign:'middle', align:'right', layout: "vertical", labelFormat: "{name}:{percentage:.1f}%" }, colors: ['#7cb5ec', '#f7a35c', '#90ed7d', '#8085e9', '#f15c80', '#e4d354', '#8085e8', '#8d4653', '#91e8e1', '#434348'], tooltip: { headerFormat: '', pointFormat: '<b>{point.name} : {point.percentage:.1f}% ({point.y})</b>', }, plotOptions: { pie: { allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: true, format: '{point.percentage:.1f}%', connectorWidth:0, connectorPadding:0, distance:-30 }, showInLegend: true, events: { click: clickFunc } } }, series: [{ type: 'pie', data: data }] }; }
spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd "> <!-- 扫描controller的注解,别的不扫描 --> <context:component-scan base-package="com.alphajuns.controller"> </context:component-scan> <!-- 配置视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- JSP文件所在的目录 --> <property name="prefix" value="/pages/" /> <!-- 文件的后缀名 --> <property name="suffix" value=".jsp" /> </bean> <!-- 设置静态资源不过滤 --> <mvc:resources location="/css/" mapping="/css/**" /> <mvc:resources location="/img/" mapping="/img/**" /> <mvc:resources location="/js/" mapping="/js/**" /> <mvc:resources location="/plugins/" mapping="/plugins/**" /> <!-- 开启对SpringMVC注解的支持 --> <mvc:annotation-driven /> <!-- 支持AOP的注解支持,AOP底层使用代理技术 JDK动态代理,要求必须有接口 cglib代理,生成子类对象,proxy-target-class="true" 默认使用cglib的方式 --> <aop:aspectj-autoproxy proxy-target-class="true"/> </beans>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 开启注解扫描,管理service和dao --> <context:component-scan base-package="com.alphajuns.service.*"> </context:component-scan> <context:component-scan base-package="com.alphajuns.dao"> </context:component-scan> <context:property-placeholder location="classpath:db.properties"/> <!-- 配置连接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${oracle.driver}"/> <property name="jdbcUrl" value="${oracle.url}"/> <property name="user" value="${oracle.username}"/> <property name="password" value="${oracle.password}"/> </bean> <!-- 把交给IOC管理 SqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 扫描dao接口 --> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.alphajuns.dao"/> </bean> <!-- 配置Spring的声明式事务管理 --> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
db.properties
oracle.driver=oracle.jdbc.driver.OracleDriver
oracle.url=jdbc:oracle:thin:@localhost:1521:orcl
oracle.username=scott
oracle.password=tiger
log4j.properties
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE debug info warn error fatal
log4j.rootCategory=debug, CONSOLE
# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m
# LOGFILE is set to be a File appender using a PatternLayout.
# log4j.appender.LOGFILE=org.apache.log4j.FileAppender
# log4j.appender.LOGFILE.File=d:axis.log
# log4j.appender.LOGFILE.Append=true
# log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
# log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <!-- 配置加载类路径的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:applicationContext.xml</param-value> </context-param> <!-- 配置监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener> <!-- 解决中文乱码过滤器 --> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 前端控制器(加载classpath:springmvc.xml 服务器启动创建servlet) --> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置初始化参数,创建完DispatcherServlet对象,加载springmvc.xml配置文件 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <!-- 服务器启动的时候,让DispatcherServlet对象创建 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.alphajuns</groupId> <artifactId>util</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>util Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> <spring.version>5.0.2.RELEASE</spring.version> <slf4j.version>1.6.6</slf4j.version> <log4j.version>1.2.12</log4j.version> </properties> <dependencies> <!-- mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <!-- spring-mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <!-- ant --> <dependency> <groupId>org.apache.ant</groupId> <artifactId>ant</artifactId> <version>1.9.7</version> </dependency> <!-- pdf --> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.13</version> </dependency> <!-- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log end --> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.9</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency> <!-- json --> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> </dependency> <!-- spring --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.8</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <!-- oracle --> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc6</artifactId> <version>12.1.0.1-atlassian-hosted</version> </dependency> <!-- 编码识别 --> <dependency> <groupId>com.ibm.icu</groupId> <artifactId>icu4j</artifactId> <version>59.1</version> </dependency> <!-- c3p0 --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> <type>jar</type> <scope>compile</scope> </dependency> <!-- 引入junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-mapper-asl --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.10.3</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.10.3</version> </dependency> </dependencies> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.2</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> <showWarnings>true</showWarnings> </configuration> </plugin> </plugins> </pluginManagement> </build> </project>
EmployeeController.java
package com.alphajuns.controller; import com.alphajuns.pojo.Employee; import com.alphajuns.service.EmployeeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @ClassName EmployeeController * @Description TODO * @Author AlphaJunS * @Date 2020/3/25 19:50 * @Version 1.0 */ @Controller @RequestMapping("/employee") public class EmployeeController { @Autowired private EmployeeService employeeService; @RequestMapping("/findAllEmp") public ModelAndView findAllEmp() { ModelAndView mv = new ModelAndView(); List<Employee> allEmp = employeeService.findAllEmpByAnnotation(); mv.addObject("allEmp", allEmp); System.out.println(allEmp); mv.setViewName("report"); return mv; } @RequestMapping("/queryPersonNumGroupByJob") public ModelAndView queryPersonNumGroupByJob() { ModelAndView mv = new ModelAndView(); List<Map<String, ?>> mapList = employeeService.queryPersonNumGroupByJob(); mv.addObject("mapList", mapList); mv.setViewName("report"); return mv; } @RequestMapping("/getPieChart") @ResponseBody public Map getPieChart() { Map pieChartMap = new HashMap(); pieChartMap = employeeService.getPieChart(); return pieChartMap; } @RequestMapping("/getPieDetail") @ResponseBody public List<Employee> getPieDetail(@RequestParam String param) { List<Employee> pieDetailList = employeeService.getPieDetail(param); return pieDetailList; } }
EmployeeService.java
package com.alphajuns.service; import com.alphajuns.pojo.Employee; import java.util.List; import java.util.Map; public interface EmployeeService { List<Employee> findAllEmpByAnnotation(); List<Map<String, ?>> queryPersonNumGroupByJob(); Map<String, ?> getPieChart(); List<Employee> getPieDetail(String param); }
EmployeeServiceImpl.java
package com.alphajuns.service.impl; import com.alphajuns.dao.IEmpDao; import com.alphajuns.pojo.Employee; import com.alphajuns.service.EmployeeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; /** * @ClassName EmployeeServiceImpl * @Description TODO * @Author AlphaJunS * @Date 2020/3/25 19:51 * @Version 1.0 */ @Service public class EmployeeServiceImpl implements EmployeeService { @Autowired private IEmpDao empDao; @Override public List<Employee> findAllEmpByAnnotation() { List<Employee> allEmp = empDao.findAllEmpByAnnotation(); return allEmp; } @Override public List<Map<String, ?>> queryPersonNumGroupByJob() { List<Map<String, ?>> mapList = empDao.queryPersonNumGroupByJob(); return mapList; } @Override public Map<String, ?> getPieChart() { Map<String, ?> pieChartMap = empDao.getPieChart(); return pieChartMap; } @Override public List<Employee> getPieDetail(String param) {// "800~2000" String[] split = param.split("~"); // 800 int min = Integer.parseInt(split[0]); // 2000 int max = Integer.parseInt(split[1]); List<Employee> pieDetailList = empDao.getPieDetail(min, max); return pieDetailList; } }
IEmpDao.java
package com.alphajuns.dao; import com.alphajuns.pojo.Employee; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import java.util.List; import java.util.Map; public interface IEmpDao { @Select("select * from emp") List<Employee> findAllEmpByAnnotation(); @Select("SELECT job, count(*) AS NUM FROM EMP group by job") List<Map<String, ?>> queryPersonNumGroupByJob(); @Select("SELECT " + " count( a1 ) AS A1, " + " count( a2 ) AS A2, " + " count( a3 ) AS A3 " + "FROM " + " ( " + " SELECT " + " ( CASE WHEN sal <= 2000 AND sal >= 800 THEN SAL END ) AS a1, " + " ( CASE WHEN sal <= 4000 AND sal > 2000 THEN SAL END ) AS a2, " + " ( CASE WHEN sal <= 6000 AND sal > 4000 THEN SAL END ) AS a3 " + " FROM " + " emp " + " ) t") Map<String, ?> getPieChart(); @Select("select * from emp where sal >= #{min} and sal <= #{max}") List<Employee> getPieDetail(@Param("min") int min, @Param("max") int max); }