歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

Java運用echart進行圖形展示

前段時間項目中要做一個根據數據生成折線圖的功能,並5分鐘刷新一次,進行數據更新。由於之前是用echarts來進行中國地圖展現的,所有這次也用echarts進行圖形展示。

項目目錄如下圖所示:

1.pom.xml文件

<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>test</groupId>
  <artifactId>test</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
 
  <properties>
        <spring.version>4.1.3.RELEASE</spring.version>
        <jackson.version>2.4.2</jackson.version>
        <jstl.version>1.2</jstl.version>
        <servlet-api.version>2.5</servlet-api.version>
        <jsp-api.version>2.0</jsp-api.version>
    </properties>
 
  <dependencies>
      <!-- JSP相關 -->
    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>${jstl.version}</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <scope>provided</scope>
        <version>${servlet-api.version}</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jsp-api</artifactId>
        <scope>provided</scope>
        <version>${jsp-api.version}</version>
    </dependency>
    <!-- Jackson Json處理工具包 -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>${jackson.version}</version>
    </dependency>
    <!-- Spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</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-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>${spring.version}</version>
    </dependency>
  </dependencies>
 
  <build>
      <plugins>
          <plugin>
              <groupId>org.apache.tomcat.maven</groupId>
            <artifactId>tomcat7-maven-plugin</artifactId>
            <configuration>
                <port>8080</port>
                <path>/</path>
            </configuration>
          </plugin>
      </plugins>
  </build>
</project>

2.web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="taotao" version="2.5">
    <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>

    <!-- 加載spring容器 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/applicationContext*.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 解決post亂碼 -->
    <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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- springmvc的前端控制器 -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- contextConfigLocation不是必須的, 如果不配置contextConfigLocation, springmvc的配置文件默認在:WEB-INF/servlet的name+"-servlet.xml" -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
   
</web-app>

3.applicationContext-service.xml文件

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    <context:component-scan base-package="service"/>
</beans>

4.springmvc.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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    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-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="controller" />
    <mvc:annotation-driven />
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
          value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
   
    <mvc:resources location="/WEB-INF/js/" mapping="/js/**"/>
    <mvc:resources location="/WEB-INF/css/" mapping="/css/**"/>
   
   
</beans>

5.EchartsEntity.java

package po;

import java.util.List;

public class EchartsEntity {

    public String name;
    public String type;
    public List<?> data;
   
    public EchartsEntity() {
       
    }

    public EchartsEntity(String name, String type, List<?> data) {
        super();
        this.name = name;
        this.type = type;
        this.data = data;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public List<?> getData() {
        return data;
    }

    public void setData(List<?> data) {
        this.data = data;
    }
   
   
}

6.EchartsServiceImpl.java

package service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import po.EchartsEntity;
import service.EchartsService;

@Service
public class EchartsServiceImpl implements EchartsService {

    private ObjectMapper mapper = new ObjectMapper();
    public String getLineImage() {
        List<EchartsEntity> echarts = new ArrayList<EchartsEntity>();
        //自定義橫坐標
        String[] xAxis = {"周一","周二","周三","周四","周五","周六","周日"};
        //自定義三條線
        EchartsEntity entity1 = new EchartsEntity("郵件營銷","line",Arrays.asList(120, 132, 101, 134, 90, 230, 210));
        EchartsEntity entity2 = new EchartsEntity("聯盟廣告","line",Arrays.asList(220, 182, 191, 234, 290, 330, 310));
        EchartsEntity entity3 = new EchartsEntity("視頻廣告","line",Arrays.asList(150, 232, 201, 154, 190, 330, 410));
        echarts.add(entity1);
        echarts.add(entity2);
        echarts.add(entity3);
       
        String[] legend = {"郵件營銷","聯盟廣告","視頻廣告"};
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("xAxis", xAxis);
        resultMap.put("series", echarts);
        resultMap.put("legend", legend);
        try {
            return mapper.writeValueAsString(resultMap);
        } catch (JsonProcessingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    }

}

7.EchartsTestController.java

package controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import service.EchartsService;

@RestController
@RequestMapping(value="/echarts",produces=MediaType.TEXT_HTML_VALUE+";charset=utf-8")
public class EchartsTestController {

    @Autowired
    public EchartsService echartsService;
   
    @RequestMapping("/showImage")
    public String showImage() {
        String value = echartsService.getLineImage();
        System.out.println(value);
        return value;
    }
}

8.ShowPageController.java

package controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ShowPageController {

    @RequestMapping("/{page}")
    public String showPage(@PathVariable String page) {
   
        return page;
    }
}

9.前台jsp頁面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/jquery-2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="js/ehcarts/echarts-all.js"></script>
<!-- 
<script type="text/javascript" src="js/echarts-2.2.7/build/dist/echarts-all.js"></script>
-->
<title>Insert title here</title>
</head>
<body>
<div id='line' ></div>
<script type="text/javascript">
var myChart = echarts.init(document.getElementById('line'));
var lineOption = {
        title : {
            text: '',
            subtext: ''
        },
        tooltip : {
            trigger: 'axis' //item 點在哪條線上顯示哪條線上的數據,axis點在哪個坐標點上顯示對於點上所有數據
        },
        legend: {
            data:[]
        },
        toolbox: {
            show : true,
            orient : 'vertical',
            x: 'right',
            y: 'center',
            feature : {
                mark : {show: true},
                dataView : {show: true, readOnly: false},
                magicType : {show: true, type: ['line', 'bar']},
                restore : {show: true},
                saveAsImage : {show: true}
            }
        },
        calculable : true,
        xAxis : [
            {
                type : 'category',
                boundaryGap : false,
                data : []
            }
        ],
        yAxis : [
            {
                type : 'value',
                axisLabel : {
                    formatter: '{value} '
                }
            }
        ],
        series : []
    };

myChart.setOption(lineOption);
var ajax = function() {
    $.ajax({
        url : '/echarts/showImage',
        success: function(responseText) {
            //請求成功時處理
            var responseText = eval('(' + responseText + ')');
            lineOption.legend.data=responseText.legend;
            lineOption.xAxis[0].data = responseText.xAxis;
            var serieslist = responseText.series;
            //alert(serieslist);
            for(var i=0;i<serieslist.length;i++) {
                lineOption.series[i] = serieslist[i];
            }
            //alert(lineOption.series);
            myChart.setOption(lineOption,true);
        },
        complete: function() {
            //請求完成的處理
        },
        error: function() {
            //請求出錯處理
            alert("加載失敗");
        }
    })
}

window.setTimeout(ajax,100);
//window.setInterval(ajax,1000*60*5);
</script>
</body>

</html>

運行項目,結果如圖所示:

Copyright © Linux教程網 All Rights Reserved