<%@ 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>望大虾能为我的这个toy程序指点迷津,谢谢
解决方案 »
- 用java怎么简便的开发本地socks5代理,求框架及中文API文档
- ext3.0+java+servlet 不能显示数据
- 一道关于servlet的面试问题
- 关于LIST和VECTOR
- 请教dwr和openjpa结合后的问题
- 如何将2007-07-25 00:00:00.000 自动转变成星期三
- 为什么服务器会开许多自己连自己的端口?
- 附件批量上传的问题。小弟前面已经提过一次,还没有解决。恳求高手能够出手相助!
- 遇到无法理解的问题。请高手解答,我是新手
- SSM中把使用查询语句后的结果集进行了改变,要传到easyui前端的filed,怎么做
- jquery用Iframe方式通过超链接调用action,报找不到action
- java.lang.NoSuchMethodError: 错误
修改后如下:<%@ page contentType="text/html;charset=gbk"%>
<%@ page import="java.io.*"%>
<%!
int tem=0;//增设了一个全局变量
int load(File f){
int temp=0;
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){
try{
tem=++c;
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);
session.setAttribute("counter",tem);//session重定位于此
}
%><h1>你是第<%=session.getAttribute("counter")%>个访问本站的人!</h1>其实不用session直接输出tem好像也可以,但是在代码修改后,页面重刷新tem会重初始化为0,而session已old所以我选择将访问量记录到了session的属性中。