与服务器实例混淆

时间:2012-01-13 11:07:59

标签: java servlets

我有以下一段代码,它的工作正常,没有问题,但我很困惑,如何制作多个这个实例。每次运行这个我得到“有1个实例运行”

public class HolisticCounter extends HttpServlet {


    private static final long serialVersionUID = 1L;
static int classCount = 0;  // shared by all instances
  int count = 0;              // separate for each servlet
  static Hashtable instances = new Hashtable();  // also shared

  public void doGet(HttpServletRequest req, HttpServletResponse res) 
                               throws ServletException, IOException {
    res.setContentType("text/plain");
    PrintWriter out = res.getWriter();

    count++;
    out.println("Since loading, this servlet instance has been accessed " +
                count + " times.");

    // Keep track of the instance count by putting a reference to this
    // instance in a Hashtable. Duplicate entries are ignored. 
    // The size() method returns the number of unique instances stored.
    instances.put(this, this);
    out.println("There are currently " + 
                instances.size() + " instances.");

    classCount++;
    out.println("Across all instances, this servlet class has been " +
                "accessed " + classCount + " times.");
  }
}

1 个答案:

答案 0 :(得分:4)

在绝大多数情况下,每个<servlet>条目只有一个servlet实例。容器不再需要实例化,因此它为每个请求重用相同的实例。

服务器允许实例化几个,但通常没有理由这样做。