日期:2014-05-18  浏览次数:20803 次

请教session的问题
public class CountServlet extends HttpServlet {
  public void service(
        HttpServletRequest request, 
        HttpServletResponse response)
        throws ServletExceptionIOException {

    PrintWriter out = response.getWriter();
    HttpSession session = request.getSession();    
    Integer count = (Integer) session.getAttribute("count");
    if(count == null){
        count = 1;
    }else{
        count++;
    }
    session.setAttribute("count", count);
    out.println("你是第 " + count + " 次访问");
    out.close();
  }
}



请教这个语句 Integer count = (Integer) session.getAttribute("count"); 此时还没有setattribute是count为什么就getattribute呢
------解决方案--------------------
调用不分先后的,找了下tomcat的session实现类StandardSession
  public Object getAttribute(String name)
  {
    if (!isValidInternal()) {
      throw new IllegalStateException(sm.getString("standardSession.getAttribute.ise"));
    }

    if (name == null) return null;

    return this.attributes.get(name);
  }
这样就比较清晰了