本demo旨在通过JSON与AJAX实现jsp与servlet在页面不刷新的情况下后台通信,刷新页面数据
jsp代码:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript" src="<%=basePath%>/jquery-2.1.4/jquery.min.js"></script></head>
<body>
<table style="width: 30%" cellspacing="0" border="1" align="center" background-color="red" ">
<tr style="background-color: black;color:#fff">
<th>股票代码</th>
<th>股票名称</th>
<th>股票价格</th>
</tr>
<tbody id="tbo">
</tbody>
</table>
</body>
<script type="text/javascript">
/**加载成功启动定时器*/
$(function(){
myTime();
setInterval(myTime,3000);
});
/** $.post()方法
function myTime(){
$("#tbo").empty();
$.post("stock.do?task=stock",function(data){
for(var i=0;i<data.length;i++){
$("#tbo").append("<tr><td>"+data[i].code+"</td><td>"+data[i].name+"</td><td>"+data[i].price+"</td></tr>");
}
},"JSON");
}
*/
//$.ajax()方法
function myTime(){
$("#tbo").empty();
$.ajax({
url:"stock.do?task=stock",
data:{"username":"shengge"},
type:"POST",
dataType:"json",
success:function(data){
for(var i=0;i<data.length;i++){
$("#tbo").append("<tr><td>"+data[i].code+"</td><td>"+data[i].name+"</td><td>"+data[i].price+"</td></tr>");
}
}
});
}
</script>
</html>
StockServlet类代码:
public class StockServlet extends HttpServlet{
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
String task = req.getParameter("task");
PrintWriter writer = resp.getWriter();
if("stock".equals(task)){
List<StockBean> list = new ArrayList<StockBean>();
//测试如何拿到数据
String str = req.getParameter("username");
for (int i = 0; i < 10; i++) {
StockBean stockBean = new StockBean();
Random random = new Random();
stockBean.setCode(60000+random.nextInt(100));
stockBean.setName("沪深成指"+random.nextInt(10));
stockBean.setPrice(random.nextInt(100));
list.add(stockBean);
}
writer.write(JSONArray.fromObject(list).toString());
writer.flush();
System.out.println(str);
}
}
}
ps:要使用JSON转换格式,一定要导入以下六个包至项目下:
其中 json-lib是主要的包,一定要符合自己的jdk版本,笔者的jdk版本为1.6.0_13,所以用json-lib-jdk13.jar包。其他都是依赖于此包。
演示效果如下:
根据定时器所设置,每过三秒跳动一次数据,后台传输数据实现页面更新,完成!
欢迎广大博友留言交流~