我的结构如下:
然后我多次请求main.java
,声明一个变量并在每次调用时递增它,这反映了旧值。我遵循正确的方法吗?为什么不每次都创建新线程?
答案 0 :(得分:1)
将变量OUTSIDE声明为get / post方法范围,然后您可以在每次调用servlet时递增它。见下文:
private int counter;
private Object lock;
public void init() throws ServletException{
//init lock
lock = new Object();
// create variable
counter = 0;
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
//increment your counter here
synchronized(lock){
counter++;
}
response.setContentType("text/html");
// here you can actually return the counter to the browser.
PrintWriter out = response.getWriter();
out.println("<h1>" + counter + "</h1>");
}