模拟实现一个动态显示股票价格的经典例子:
实体类 :Stock.java
由于篇幅问题,此处省略了get Set 方法
/**
* Created by IntelliJ IDEA.
* User: 赵光鹏
* Date: 2011-11-24
* Time: 10:51:15
* 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 String toString(){
return this.name+":"+this.now;
}
}
Servlet: GetStocksInfo.java
import ...
/**
* Created by IntelliJ IDEA.
* User: 赵光鹏
* Date: 2011-11-24
* Time: 10:52:01
* To change this template use File | Settings | File Templates.
*/
public class GetStocksInfo extends HttpServlet {
private HashMap<String,Stock> stocks;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet( request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//返回两只股票的价格信息
//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.将随机数和当前价格进行加减的操作
//2.1首先获取到先前实例化好的两个数据
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);
//采用json数据格式返回股票的信息
StringBuilder builder = new StringBuilder();
//采用数组的形式 在此处略过
//采用对象的方式回传两个股票对象
//前台效果:{
// 300001:{name:"上证指数",yes:3000.0",tod:2990.0,now:3010.02},
// 000001:{name:"浦发银行",yes:23.22",tod:23.55,now:24.4}
// }
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("}})");
response.setContentType("text/html;charset=gb2312");
PrintWriter out = response.getWriter();
out.print(builder);
}
//在服务器启动时(配置文件中配置好),执行该方法,虚拟出两条股票信息
@Override
public void init(ServletConfig servletConfig) throws ServletException {
stocks = new HashMap<String, Stock>();
Stock szzs = new Stock(3000.0, 2990.0, "上证指数", "300001");
Stock pfyh = new Stock(23.22, 23.55, "浦发银行", "000001");
//将两支股票保存在Stock的Map中
stocks.put(szzs.getId(),szzs);
stocks.put(pfyh.getId(),pfyh);
System.out.println(stocks);
}
}
Html页面:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="jslib/jquery-1.4.2.js"></script>
<script type="text/javascript " src="jslib/jquerystock.js"></script>
<title>动态显示股票信息</title>
</head>
<body>
<div id="300001">[url=#]上证指数:[/url]<span></span></div>
<div id="000001">[url=#]浦发银行:[/url]<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>
Js文件:
//期望进入页面后就可以开始从服务器端获取数据,然后显示股票价格
//获取服务器端返回的数据对象
var obj;
var sid;
$(function(){
//页面载入时隐藏弹出框
var stockNode = $("#stock").css("border","1px solid black").width("150px").css("background-color","green");
stockNode.hide();
var as = $("a");
as.mouseover(function(){
//
var aNode = $(this);
var divNode = aNode.parent();
sid = divNode.attr("id");
//找到对应的股票对象
updatediv();
//控制弹出框的位置
//找出当前a的位置
var offset = aNode.offset();
stockNode.css("left",offset.left+"px").css("top",offset.top + aNode.height() +"px").css("position","absolute");
// var myEvent = event || window.event;
// stockNode.css("left",myEvent.clientX + "px").css("top",myEvent.clientY + "px");
stockNode.show();
});
as.mouseout(function(){
//弹出框隐藏
stockNode.hide();
});
//获取服务端信息
getInfo();
//3.每隔1秒钟和服务器交互一次,用户不需要刷新页面
setInterval(getInfo,1000);
});
function getInfo(){
//向服务器发起请求,获取数据
$.get("GetStocksInfo", null, function(data){
obj = eval(data);//在参数栏加上json参数之前
// obj = data;
//获取两只股票当前的指数信息 ,对于较多个对象
//遍历一个较多的js对象for(var stockid in obj){var stock =
// obj[stockid]}
var szzs = obj["300001"];
var pfyh = obj["000001"];
//2.2找到页面中对应的节点,然后填充最新的股票价格
var span3 = $("#300001").children("span");
span3.html(szzs.now);
if(szzs.now > szzs.yes){
span3.css("color","red");
}else{
span3.css("color","green");
}
var span0 = $("#000001").children("span");
span0.html(pfyh.now);
if(pfyh.now > pfyh.yes){
span0.css("color","red");
}else{
span0.css("color","green");
}
updatediv();
})
}
function updatediv(){
var stockObj = obj[sid];
for(var proname in stockObj){
if(proname != "name"){
//找到对应的div节点,然后将数据放到子节点span内
$("#" + proname).children("span").html(stockObj[proname]);
}
}
}
在配置文件中注册servlet,应该在启动服务器时,自动加载该servlet,以实现对两个模拟数据的初始化,:具体配置如下 web.xml
<!--load-on是在服务器启动时自动加载该servlet-->
<servlet>
<servlet-name>GetStocksInfo</servlet-name>
<servlet-class>GetStocksInfo</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>GetStocksInfo</servlet-name>
<url-pattern>/GetStocksInfo</url-pattern>
</servlet-mapping>