gpt4 book ai didi

java - 与服务器实例混淆

转载 作者:行者123 更新时间:2023-12-01 19:09:12 25 4
gpt4 key购买 nike

我有以下一段代码,它工作正常,没有问题,但我很困惑,如何制作多个实例。每次运行此代码时,我都会得到“有 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.");
}
}

最佳答案

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

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

关于java - 与服务器实例混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8849632/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com