日期:2014-05-17  浏览次数:20569 次

关于用session设置属性等问题
Java code

<%@ 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程序指点迷津,谢谢

------解决方案--------------------
1st temp 定义在try{}里的话,其作用域只在try的{}块里,所以外头会说temp未定义

2nd 你确信这行执行到了么: session.setAttribute("count",new Integer(tem));//问2:session为何无法被解析?