码迷,mamicode.com
首页 > Web开发 > 详细

使用JSON数据格式模拟股票实时信息

时间:2015-06-14 16:22:38      阅读:267      评论:0      收藏:0      [点我收藏+]

标签:

JQueryStock.html

<!DOCTYPE html>
<head>
    <meta charset="UTF-8">
    <title>itcast.cn的JQuery实例:动态股票信息</title>
    <script type="text/javascript" src="../jslib/jquery-2.1.4.min.js"></script>
    <script type="text/javascript" src="../jslib/jquerystock.js"></script>
</head>
<body>
<div id="300001"><a href="#">上证指数:</a><span></span></div>
<div id="000001"><a href="#">浦发银行:</a><span></span></div>
<div id="stock">
    <div id="yes">昨收:<span></span></div>
    <div id="tod">今开:<span></span></div>
    <div id="now">当前:<span></span></div>
</div>
</body>
</html>

Stock.java

/**
 * Created by IntelliJ IDEA.
 * User: ming
 * Date: 2008-6-14
 * Time: 9:29:13
 * To change this template use File | Settings | File Templates.
 * 用于保存股票的基本信息
 */
public class Stock {
    /**
     * 昨天的收盘价
     */
    private double yesterday;
    /**
     * 今天的开盘价
     */
    private double today;
    /**
     * 当前价
     */
    private double now;
    /**
     * 股票名称
     */
    private String name;
    /**
     * 股票代码
     */
    private String id;

    public Stock(double yesterday, double today, String name, String id) {
        this.yesterday = yesterday;
        this.today = today;
        this.name = name;
        this.id = id;
        this.now = today;
    }

    public double getYesterday() {
        return yesterday;
    }

    public void setYesterday(double yesterday) {
        this.yesterday = yesterday;
    }

    public double getToday() {
        return today;
    }

    public void setToday(double today) {
        this.today = today;
    }

    public double getNow() {
        return now;
    }

    public void setNow(double now) {
        this.now = now;
    }

    public String getName() {
        return name;
    }

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

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String toString() {
        return this.name + ":" + this.now;
    }
}

GetStocksInfo.java

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import javax.servlet.ServletConfig;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * Created by IntelliJ IDEA.
 * User: ming
 * Date: 2008-6-14
 * Time: 9:35:50
 * To change this template use File | Settings | File Templates.
 * 返回股票当前信息的servlet
 */
public class GetStocksInfo extends HttpServlet {
    //保存股票对象的map
    private HashMap<String,Stock> stocks;
    protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
        System.out.println("进入后台计算");
        //返回两只股票的价格信息

        //1。计算随机数
        double sz = Math.random() * 20;
        double pf = Math.random() * 0.5;

        //通过随机数是奇数还是偶数来判断股票上涨还是下跌
        boolean flagsz = ((int)(Math.random() * 10)) % 2 == 0;
        boolean flagpf = ((int)(Math.random() * 10)) % 2 == 0;

        //2。将随机数和股票的当前价格进行加或减的操作,得到新的当前价格
        Stock szzs = stocks.get("300001");
        Stock pfyh = stocks.get("000001");
        double temp;
        if (flagsz) {
            temp = szzs.getNow() + sz;
        } else {
            temp = szzs.getNow() - sz;
        }
        //需要对新的当前价格进行截取,只保留小数点后两位
        temp = (int)(temp * 100) / 100.0;
        szzs.setNow(temp);
        if (flagpf) {
            temp = pfyh.getNow() + pf;
        } else {
            temp = pfyh.getNow() - pf;
        }
        temp = (int)(temp * 100) / 100.0;
        pfyh.setNow(temp);


        httpServletResponse.setContentType("text/html;charset=UTF-8");
        PrintWriter out = httpServletResponse.getWriter();
        //out.println(szzs + "<br />" + pfyh);
        //3。返回两只股票的昨天收盘,今天开盘和当前价格
        //采用json的数据格式返回股票的信息
        StringBuilder builder = new StringBuilder();
        //采用数组的方式回传两个股票对象
        /*
        builder.append("[{name:\"").append(szzs.getName()).append("\",id:\"").append(szzs.getId())
                .append("\",yes:").append(szzs.getYesterday()).append(",tod:").append(szzs.getToday())
                .append(",now:").append(szzs.getNow())
                .append("},")
                .append("{name:\"").append(pfyh.getName()).append("\",id:\"").append(pfyh.getId())
                .append("\",yes:").append(pfyh.getYesterday()).append(",tod:").append(pfyh.getToday())
                .append(",now:").append(pfyh.getNow())
                .append("}]");
        */
        //采用对象的方式回传两个股票对象
        //如果回传表示对象的json,需要在最外层加上一个括号,否则页面解析会出错
        builder.append("({")
                .append("\"").append(szzs.getId()).append("\":{name:\"").append(szzs.getName())
                .append("\",yes:").append(szzs.getYesterday()).append(",tod:").append(szzs.getToday())
                .append(",now:").append(szzs.getNow())
                .append("},")
                .append("\"").append(pfyh.getId()).append("\":{name:\"").append(pfyh.getName())
                .append("\",yes:").append(pfyh.getYesterday()).append(",tod:").append(pfyh.getToday())
                .append(",now:").append(pfyh.getNow())
                .append("}})");
        out.println(builder);

    }

    protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
        doGet(httpServletRequest, httpServletResponse);
    }

    public void init(ServletConfig servletConfig) throws ServletException {
        stocks = new HashMap<String,Stock>();
        //创建股票
        Stock szzs = new Stock(3000.0,2990.1,"上证指数","300001");
        Stock pfyh = new Stock(23.22, 23.50,"浦发银行","000001");

        //将两只股票保存在stocks的map中
        stocks.put(szzs.getId(),szzs);
        stocks.put(pfyh.getId(),pfyh);

        System.out.println(stocks);
    }
}

jquerystock.js

 1 //期望进入页面后就可以开始从服务器段获取数据,然后显示股票价格
 2 //保存服务器段返回的股票对象
 3 var obj;
 4 var sid;
 5 $(document).ready(function() {
 6     //页面载入时隐藏弹出框
 7     var stockNode = $("#stock").css("border","1px solid black").width("150px")
 8         .css("position","absolute").css("z-index","99").css("background-color","blue")
 9         .css("color","yellow");
10     stockNode.hide();
11     var as = $("a");
12     //定义鼠标进入股票名称时的操作
13     as.mouseover(function(event){
14         //获取到当前股票的代码
15         var aNode = $(this);
16         var divNode = aNode.parent();
17         sid = divNode.attr("id");
18         //找到对应的股票对象
19         updatediv();
20 
21         //需要控制弹出框的位置
22         /*
23          //1.找到当前连接的位置
24          var offset = aNode.offset();
25          //2。设置弹出框的位置
26          stockNode.css("left",offset.left + "px").css("top",offset.top + aNode.height() + "px");
27          */
28         //期望出现在鼠标的右下方
29         var myEvent = event || window.event;
30         stockNode.css("left",myEvent.clientX + 5 + "px").css("top",myEvent.clientY + 5 + "px");
31 
32 
33 
34 
35         //弹出框显示
36         stockNode.show();
37 
38     });
39     //定义鼠标离开股票名称时的操作
40     as.mouseout(function() {
41         //弹出框隐藏
42         stockNode.hide()
43     })
44     getInfo();
45     //3。每隔一秒钟和服务器交互一次,用户不用刷新页面就可以不断地看到最新的股票信息
46     setInterval(getInfo,1000);
47 });
48 
49 //从服务器段获取数据并显示在页面上的的方法
50 function getInfo() {
51     //1。向服务器发起请求,获取数据
52     $.get("/Lesson6_jQuery_Demo1/GetStockInfo", null, function(data) {
53         //2.接收并解析数据
54         obj = eval(data);
55         //2.1获取两只股票的当前指数信息
56         var szzs = obj["300001"];  //obj.300001
57         var pfyh = obj["000001"];
58         /*
59          遍历一个js的对象
60          for (var stockid in obj) {
61          var stock = obj[stockid];
62          }
63          */
64         //2.2找到页面中对应的节点,然后填充最新的股票价格
65         var span3 = $("#300001").children("span");
66         span3.html(szzs.now);
67         if (szzs.now > szzs.yes) {
68             //当前价格大于昨天收盘,则显示红色
69             span3.css("color","red");
70         } else {
71             span3.css("color","green");
72         }
73         var span1 = $("#000001").children("span");
74         span1.html(pfyh.now);
75         if (pfyh.now > pfyh.yes) {
76             //当前价格大于昨天收盘,则显示红色
77             span1.css("color","red");
78         } else {
79             span1.css("color","green");
80         }
81         updatediv();
82     })
83 }
84 
85 //更新弹出框中得内容
86 function updatediv() {
87     var stockobj = obj[sid];
88     for (var proname in stockobj) {
89         if (proname != "name") {
90             //找到对应的弹出框中的div节点,然后找到span字节点,将数据填充
91             $("#" + proname).children("span").html(stockobj[proname]);
92         }
93     }
94 }

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">

    <servlet>
        <servlet-name>GetStockInfo</servlet-name>
        <servlet-class>GetStocksInfo</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>GetStockInfo</servlet-name>
        <url-pattern>/GetStockInfo</url-pattern>
    </servlet-mapping>
</web-app>

JSON格式相当于是键值对对象

使用JSON数据格式模拟股票实时信息

标签:

原文地址:http://www.cnblogs.com/sherrykid/p/4575136.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!