日期:2014-05-17 浏览次数:20611 次
<%@ page contentType="text/html;charset=gbk"%> <%@ page import="java.io.*"%> <%! int temp=0;//问1:为什么temp不能直接定义在load方法的try{}里?如果定义在里面就会出现temp cannot be resolved int load(File f){//取得count.txt中的访问量 try{ temp=new Integer(new BufferedReader(new InputStreamReader(new FileInputStream(f))).readLine()); }catch(Exception e){e.getMessage();} return temp; } public synchronized void save(int c,File f){//向count.txt中保存访问量 try{ int tem=++c; session.setAttribute("count",new Integer(tem));//问2:session为何无法被解析? PrintStream ps=new PrintStream(new FileOutputStream(f)); ps.println(c); ps.close(); }catch(Exception e){ e.getMessage();} } %> <% String fileName=getServletContext().getRealPath("/")+"application"+File.separator+"count.txt"; File f=new File(fileName); int count=load(f); if(session.isNew()) save(count,f);//如果是一个新的会话,计数器加1 %> <h1>你是第<%=session.getAttribute("count")%>个访问本站的人!</h1>