美文网首页
html+js+servlet实现echarts图表展示

html+js+servlet实现echarts图表展示

作者: nicklbx | 来源:发表于2017-06-18 16:49 被阅读0次

    一、需求:

    • 提供登录页面,登录成功后跳转到echarts展示页面,登录失败回到登录页面
    • 使用拦截器过滤请求,必须登录后才能够访问echarts展示页面
    • echarts页面读取后台传递过来的json数据,在前台正确显示
    • 设置session过期时间为5分钟
    • 登录帐号和密码为:admin/123456(项目代码路径在最后)

    二、简易架构图

    架构.png

    三、代码结构

    代码结构.png

    四、代码

    1. 后台代码

    1.1 CheckAccountServlet.java

    package com.servlet;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    import com.beans.AccountBean;
    
    
    public class CheckAccountServlet extends HttpServlet {
        /**
         * 
         */
        private static final long serialVersionUID = 1L;
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            doGet(req, resp);
        }
    
        @Override
        public void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            HttpSession session = req.getSession();
            AccountBean account = new AccountBean();
            String username = req.getParameter("username");
            String pwd = req.getParameter("password");
            account.setPassword(pwd);
            account.setUsername(username);
            if ((username != null) && (username.trim().equals("admin"))) {
                if ((pwd != null) && (pwd.trim().equals("123456"))) {
                    System.out.println("success");
                    session.setAttribute("account", account);
                    String login_suc = "print.html";
                    resp.sendRedirect(login_suc);
                    return;
                }
            }
            String login_fail = "index.html";
            System.out.println("failed");
            resp.sendRedirect(login_fail);
            return ;
        }
    
    }
    

    1.2 EchartsServlet.java

    package com.servlet;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.json.JSONException;
    import org.json.JSONObject;
    
    /**
     * 
     * @author Administrator
     *
     */
    //@WebServlet("/EchartsServlet")
    public class EchartsServlet extends HttpServlet {
    
        /**
         * 
         */
        private static final long serialVersionUID = 1L;
    
        @Override
        protected void doGet(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {
            doPost(request, response);
        }
    
        @SuppressWarnings("unused")
        @Override
        protected void doPost(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {
            //设置response响应头格式
            //解决中文乱码问题
            response.setContentType("application/json-rpc;charset=utf-8");
            // response.setHeader("Cache-Control", "no-cache");
            // response.setHeader("Expires", "0");
            // response.setHeader("Pragma", "No-cache");
            // response.setHeader("Access-Control-Allow-Origin", "*");
            // response.setHeader("Access-Control-Allow-Credentials","true");
            // response.setHeader("Access-Control-Allow-Headers",
            // "*, X-Requested-With, Content-Type");
            response.setHeader("Access-Control-Allow-Methods",
                    "GET, OPTIONS, POST, DELETE, PUT");
            response.setHeader("Content-Type: text/html", "charset=UTF-8");
        
            String[] categories = { "衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子" };
            Integer[] values = { 5, 20, 36, 10, 10, 20 };
            String[] categories2 = { "衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子" };
            Integer[] values2 = { 30, 60, 32, 30, 10,50 };
                
            //使用json将数据进行封装
             JSONObject json = new JSONObject();
             try {
             json.put("categories", categories);
             json.put("values", values);
             json.put("categories2", categories2);
             json.put("values2", values2);
             } catch (JSONException e) {
             e.printStackTrace();
             }
    
            if (json != null) {
                PrintWriter writer = response.getWriter();
                writer.write(json.toString());
                writer.flush();
                writer.close();
            } else {
                response.getWriter().print(1);
            }
    
        }
    
    }
    
    

    1.3 AccountBean.java

    package com.beans;
    
    public class AccountBean {
        private String username;
        private String password;
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    }
    

    1.4 LoginFilter.java

    package com.filter;
    
    import java.io.IOException;
    
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.beans.AccountBean;
    
    /**
     * 登录页面拦截器
     * @author Administrator
     *
     */
    public class LoginFilter implements Filter {
    
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
    
        }
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response,
                FilterChain chain) throws IOException, ServletException {
    
            // 在过滤器中检查是否已经登录
    
            HttpServletRequest req = (HttpServletRequest) request;
            HttpServletResponse resp = (HttpServletResponse) response;
    
            AccountBean account = (AccountBean) req.getSession().getAttribute("account");
            
            //如果请求AccountBean为空即未登录或并且请求url不是以index.html结尾并且不是以CheckAccount
            //(注:servlet)结尾,将请求跳转到index.html页面
            //即未登录如果访问其他页面则自动跳转到登录页面,必须登录后才能进行访问
            if (account == null && !req.getRequestURI().endsWith("index.html")
                    && !req.getRequestURI().endsWith("CheckAccount")) {
                resp.sendRedirect("index.html"); 
            
    //          req.getRequestDispatcher("index.html").forward(request, response);
            } else {
                chain.doFilter(request, response);
            }
    
        }
    
        @Override
        public void destroy() {
    
        }
    
    }
    

    1.5 web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
        version="3.1">
    
        <welcome-file-list>
            <welcome-file>index.html</welcome-file>
        </welcome-file-list>
    
        <servlet>
            <description>This is the description of my J2EE component</description>
            <display-name>This is the display name of my J2EE component</display-name>
            <servlet-name>CheckAccountServlet</servlet-name>
            <servlet-class>com.servlet.CheckAccountServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>CheckAccountServlet</servlet-name>
            <url-pattern>/login</url-pattern>
        </servlet-mapping>
    
        <servlet>
            <servlet-name>EchartsServlet</servlet-name>
            <servlet-class> com.servlet.EchartsServlet</servlet-class>
        </servlet>
    
    
        <servlet-mapping>
            <servlet-name>EchartsServlet</servlet-name>
            <url-pattern>/EchartsServlet</url-pattern>
        </servlet-mapping>
    
        <!-- 拦截器 -->
        <filter>
            <filter-name>loginFilter</filter-name>
            <filter-class>com.filter.LoginFilter</filter-class>
        </filter>
    
        <filter-mapping>
            <filter-name>loginFilter</filter-name>
            <url-pattern>/print.html</url-pattern>
        </filter-mapping>
        
        <!-- session过期时间 (分钟) -->
        <session-config>
          <session-timeout>5</session-timeout>
    </session-config>
    </web-app>
    

    1.6 第三方jar包

    ![Paste_Image.png](https://img.haomeiwen.com/i5903023/8813b14da0698145.png?
    imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

    jar包都在最后的项目代码当中,在WEB-INF下的lib包下,引用类的情况大致如下:
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.json.JSONException;

    import org.json.JSONObject;

    2. 前台代码

    注:前台登录页面采用的是网上下载的模版,链接为http://www.cssmoban.com/cssthemes/4908.shtml

    2.1 index.html

    <!DOCTYPE html>
    <html lang="en" class="no-js">
    
        <head>
    
            <meta charset="utf-8">
            <title>FJJF screen Login</title>
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <meta name="description" content="">
            <meta name="author" content="">
    
            <!-- CSS -->
            <link rel='stylesheet' href='http://fonts.googleapis.com/css?family=PT+Sans:400,700'>
            <link rel="stylesheet" href="assets/css/reset.css">
            <link rel="stylesheet" href="assets/css/supersized.css">
            <link rel="stylesheet" href="assets/css/style.css">
    
            <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
            <!--[if lt IE 9]>
                <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
            <![endif]-->
    
        </head>
    
        <body>
    
            <div class="page-container">
                <h1>Login</h1>
                <form action="login" method="post">
                    <input type="text" name="username" class="username" placeholder="Username">
                    <input type="password" name="password" class="password" placeholder="password">
                    <button type="submit">Sign me in</button>
                    <div class="error"><span>+</span></div>
                </form>
                <div class="connect">
                    <p>Or connect with:</p>
                    <p>
                        <a class="facebook" href="http://www.qq.com/"></a>
                        <a class="twitter" href="http://weibo.com/"></a>
                    </p>
                </div>
            </div>
         
    
            <!-- Javascript -->
            <script src="assets/js/jquery-1.8.2.min.js"></script>
            <script src="assets/js/supersized.3.2.7.min.js"></script>
            <script src="assets/js/supersized-init.js"></script>
            <script src="assets/js/scripts.js"></script>
    
        </body>
    </html>
    

    2.2 print.html

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>ECharts</title>
        <!-- 引入 echarts.js -->
        <script src="./js/echarts.common.min.js"></script>
        <script type="text/javascript" src="./js/jquery-1.7.1.js"></script>
        <!--设置div不换行-->
        <style type="text/css">
            div{
                float:left;
            }
        </style>
    </head>
    
    <body style="background-image: url("./assets/img/backgrounds/2.jpg"); background-repeat:no-repeat;">
        <!-- 为ECharts准备一个具备大小(宽高)的Dom -->
        <div id="main" style="width: 600px;height:420px;color: #411F2D;border: 1px solid gray;"></div>
        <script type="text/javascript" src="./js/echartsFigure/barTest.js"> </script>
    
        <div id="chart"
            style="width: 600px; height: 420px; margin: 0 auto; border: 1px solid gray;"></div>
            <script type="text/javascript" src="./js/echartsFigure/barTest2.js"> </script>
    </body>
    </html>
    

    2.3 barTest.js

    // 基于准备好的dom,初始化echarts实例
            var myChart = echarts.init(document.getElementById('main'));
            
            var categories = [];
            var values = [];
            
            // 同步执行
            $.ajaxSettings.async = false;
            
            // 加载数据
        
            $.getJSON('EchartsServlet', function (json) {
                categories = json.categories;
                values = json.values;
            });
            
            // 指定图表的配置项和数据
            var option = {
                title: {
                    text: 'ECharts 入门示例'
                },
                tooltip: {},
                legend: {
                    data:['销量']
                },
                xAxis: {
                    data: categories
                },
                yAxis: {},
                series: [{
                    name: '销量',
                    type: 'bar',
                    data: values
                }]
            };
    
            // 使用刚指定的配置项和数据显示图表。
            myChart.setOption(option);
    

    2.4 barTest2.js

    // 基于准备好的dom,初始化echarts实例
    var myChart = echarts.init(document.getElementById('chart'));
    
    var categories = [];
    var values = [];
    
    // 同步执行
    $.ajaxSettings.async = false;
    
    // 加载数据
    
    $.getJSON('EchartsServlet', function (json) {
        categories = json.categories2;
        values = json.values2;
    });
    
    
    
    // 指定图表的配置项和数据
    var option = {
        title : {
            text: '销量分析',
        },
        tooltip : {
            trigger: 'axis'
        },
        legend: {
            data:['销量']
        },
        toolbox: {
            show : true,
            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',
                data : categories
            }
        ],
        yAxis : [
            {
                type : 'value',
                 axisLabel : {
                    formatter: '{value} 元'
                }
            }
        ],
        series : [
            {
                name:'销量',
                type:'bar',
                itemStyle:{
                     
                    normal:{
                        
                        color:'#2EC7C9',
                         barBorderRadius: 10,
                     
                    }
                },
                data:values,
                markPoint : {
                    data : [
                        {type : 'max', name: '最大值'},
                        {type : 'min', name: '最小值'}
                    ],
                    itemStyle:{
                    normal:{
                        
                        label:{
                            show:true,
                           textStyle:{
                            color:'#090909'
                           }
                        }   
                    }
            },
                }
               
            }
            
        ]
    };
                        
                                     
    // 使用刚指定的配置项和数据显示图表。
    myChart.setOption(option);
    

    效果图

    login.png echarts.png
    整个项目代码链接:http://pan.baidu.com/s/1hsbyF44 密码: fg3j

    由于对web开发不太熟,刚开始只能用最基本的东西来展现了,后面考虑用spring+springMVC+MyBatis来完善后台,前台用echarts做图表展示,后台数据处理考虑用hadoop+spark+es或hbase做数据计算、存储和索引处理,楼主菜鸟一枚,各位看客老爷们见谅,勿喷!

    相关文章

      网友评论

          本文标题:html+js+servlet实现echarts图表展示

          本文链接:https://www.haomeiwen.com/subject/jvoiqxtx.html