JSP  简单计数器
本练习中,使用application内置对象编写一个简单的网页计数器。即每当有人访问该页面,计数器自动加一。
(1)创建一个命名为counter.jsp的JSP页面。【新建】|【JSP (advanced Templates)】命令,弹出【新建JSP页面】对话框,在对话框的文件名称中输入counter.jsp,单击【完成】按钮。
(2)添加JSP文件要用到的Java类包、编码。
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
(3)在JSP文件中输入如下内容并保存。
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
  Integer count = null;
  //同步处理
  synchronized (application)
  {
    //从内存当中读取访问量
    count = (Integer) Attribute("unter");
    if (count == null)
    count = new Integer(0);
    count = new Integer(count.intValue() + 1);
    //将访问量保存到内存当中
    application.setAttribute("unter", count);
  }
%>
<html>
<head><title>简单计数器</title></head>
<body> <center>
<font size=10 color=blue>简单计数器</font>
<br><hr><br>
<font size=5 color=blue>您好!您是本站的第 <%= count %> 位客人</font>
</center></body> </html>
在上述代码中,当用户访问该网页时,application内置对象会从内存中记取访问量并使访问量加1,然后再将访问量保存到内存中。
(4)执行上述代码,结果如图3-1所示。
图3-1  网页计数器

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。