application的常用方法:
<%@ page language="java" contentType="text/html;charset=gb2312"%>
<html>
<head>
</script>
</head>
<body>
<%=application.getServerInfo()%>//返回servlet的版本信息
<%=application.getRealPath("a.jsp")%>//返回虛擬路徑的真實路徑
<%=application.getResource("/a.jsp")%>//返回一個URL對象,該對象反映位於給定URL地址的servlet環境中的資源
</body>
</html>
(一)運用application的三個典型的應用:
1.網絡日誌
2.聊天室
3.網頁計數器
(二)網站日誌
用application.log("");將信息寫入web應用程序系統日誌中。默認情況下,servlet系統日誌存放在tomcat安裝文件夾下的logs文件夾中,文
件名稱通常是“域名.日期.log”
(三)聊天室
chatroom.html
*********
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>//分割窗口,注意這種情況下不能用<body></body>標籤
<frameset rows="*,150">
<frame src="message.jsp">
<frame src="talk.jsp">
</frameset>
</HTML>
message.jsp
setTimeout("hanshu",200)函數是延時200毫秒再執行操作hanshu
********
<%@ page language="java" contentType="text/html;charset=gb2312"%>
<html>
<head>
<meta HTTP-EQUIV="REFRESH" CONTENT="3;url=message.jsp">//通過http頭配置信息,使網頁週期性刷新
<script language="javaScript">
function scrollWindow()
{
this.scroll(0,65000);
setTimeout('scrollWindow()',200);
}
scrollWindow();
</script>
</head>
<body>
<%=application.getAttribute("words")%>
</body>
</html>
talk.jsp
********
<%@ page language="java" contentType="text/html;charset=gbk"%>
<%
request.setCharacterEncoding("GBK");
String mywords=request.getParameter("message");
application.log(mywords);//爲系統寫日誌文件
//先判斷myword是否爲空
if(mywords!=null)
{
int len_mywords=mywords.length();
int flag=1;
application.log(""+len_mywords);
for(int i=0;i<len_mywords;i++)
{
if(mywords.charAt(i)=='<')
flag=0;
}
if(flag==1)
{
mywords=">>: "+mywords;
Object obj=application.getAttribute("words");
if(obj==null)
{
application.setAttribute("words",mywords);
}
else
{
application.setAttribute("words",obj.toString()+mywords+"<br>");
}
}
}
%>
<html>
<head>
<body>
<form action="talk.jsp" method="post">
<input name="message" type="text" size=50>
<input type="submit" value="發送">
</form>
</body>
</head>
</html>
(四)網頁計數器
只針對一個jsp程序的作用。application.getAttribute()返回的是一個Object類型的對象,要用到toString()方法轉換成字符串。
<%@ page language="java" contentType="text/html;charset=gb2312"%>
<html>
<head>
</script>
</head>
<body>
<%
if(application.getAttribute("count")==null)
{
application.setAttribute("count","1");
}
else
{
String str=application.getAttribute("count").toString();
int ncount=Integer.valueOf(str).intValue()+1;
application.setAttribute("count",""+ncount);
}
%>
你是第<%=application.getAttribute("count")%>的訪客。。。。。。。
</body>
</html>