利用java實現簡單圖片的計數器,運行圖:html
想學習更多關於java的知識,能夠點擊《Java EE軟件工程師》進行學習。java
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page language="java" import="java.io.*"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>計數器</title>
</head>session
<%!
//同步更新計數器app
synchronized void counter(){ ide
ServletContext application=getServletContext(); //構造application對象(可選)學習
String szPath=application.getRealPath("/"); //獲得當前路徑ui
szPath=szPath+"hits.txt"; //計數器文件 0-9999999999999...spa
String szRecord=""; //記數 Stringorm
int nRecord=0; //記數 inthtm
try{
BufferedReader file=new BufferedReader(new FileReader(szPath));
szRecord=file.readLine(); //讀取計數器文件
}
catch(Exception e){
System.out.println(e);
}
if(szRecord==null){
szRecord="0"; //若是計數器文件爲空
}
nRecord=java.lang.Integer.parseInt(szRecord)+1; //計數器+1
try{
File f=new File(szPath);
PrintWriter pw=new PrintWriter(new FileWriter(f));
pw.print(nRecord); //寫文件。這種頻繁寫文件保存記數的方法,不可取。
pw.close();
}
catch(Exception e){
System.out.println(e);
}
}
%>
<%
//顯示計數器
if(session.isNew()){ //若是是新會話
counter();
}
String Path=application.getRealPath("/");
// out.println(Path);
String szPath=Path+"hits.txt";
String szRecord="";
BufferedReader file=new BufferedReader(new FileReader(szPath));
try{
szRecord=file.readLine();
if(szRecord==null){
szRecord="0";
}
}
catch(Exception e){
System.out.println(e);
}
//顯示7位數字gif圖像
String szOut="<body topmargin='0' leftmargin='0'>當前訪問量:";
int i=0;
int k=7-szRecord.length(); //"0"的個數
for (i=0;i<k;i++){ //顯示"0"
szOut=szOut+"<img src='p_w_picpaths/0.gif'>";
}
for (i=0;i<szRecord.length();i++){ //顯示非"0"
szOut=szOut+"<img src='p_w_picpaths/"+ szRecord.charAt(i) +".gif'>";
}
szOut=szOut+"</body>";
out.println(szOut);
%>
</html>
想了解更多java學習課程,能夠關注e良師益友。