一、application
- application实现用户之间的数据共享
- application对象的常用方法
实例:统计网站访问次数
思路:
- 去除application中原始计数器的值
- 判断计数器的值,若存在则累加1;不存在则设置为1
- 使用application保存计数器
- 在页面显示计数器的值
<body>
<%
//获得application的数据
Integer in = (Integer)application.getAttribute("count");
if(in == null){
in = 1;
}else{
in+=1;
}
application.setAttribute("count", in);
%>
网站访问次数:<%=in %>
</body>
作用域:
- page:作用在当前页面
- request:作用对象与客户端的请求绑定在一起
- session:作用在整个会话范围内
实例:使用application创建一个聊天室
源码:
源码
login.jsp
<%@ page language="java" pageEncoding="gb2312"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>欢迎进入聊天室</title>
</head>
<body>
<h1>欢迎进入聊天室</h1>
<form action="dochat.jsp" method="post">
帐号:<input type="text" name="username" />
<input type="submit" value="确认" />
</form>
</body>
</html>
dochat.jsp
<%
request.setCharacterEncoding("utf-8");
String name = request.getParameter("username");
String msg = request.getParameter("msg");
//获得application存储的内容
//使用集合来存取信息
List list = (List) application.getAttribute("msg");
//第一次进去的时候集合为空,所以创建一个集合数组
if (list == null) {
list = new ArrayList();
}
if (msg != null) {
//trim()用来消除空格
msg = name + "说:" + msg.trim() + "\n";
list.add(msg);
}
//把聊天内容list存储在application中
application.setAttribute("msg", list);
response.sendRedirect("chat.jsp?username="+name);
%>
<%@ 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 'chat.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">
<script type="text/javascript">
function check() {
var content = document.getElementById("msg").value;
if (content == "") {
alert("请输入聊天内容");
document.getElementById("msg").focus();
return false;
}
}
</script>
</head>
<body>
<h1>开心聊天室欢迎您</h1>
<textarea rows="30" cols="80"><%
String name = request.getParameter("username");
//获得application存储的内容
List list = (List) application.getAttribute("msg");
if(list!=null){
for (int i = 0; i < list.size(); i++) {
String message = (String) list.get(i);
if (message != null) {
out.print(message);
}
}
}
%>
</textarea>
<form action="dochat.jsp" method="post" οnsubmit="return check()">
请输入聊天内容:<input type="text" name="msg" id="msg">
<input type="hidden" name="username" value=<%=name%>>
<input type="submit" value="提交">
</form>
</body>
</html>