这是我写的一段代码:
public class ServletCounter extends HttpServlet {
private final Object lock = new Object();
private int serviceCounter = 0;
private FileOutputStream out;
private boolean shuttingDown;
@Override
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
}
@Override
protected void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
enteringServiceMethod();
try {
super.service(httpServletRequest, httpServletResponse);
out = new FileOutputStream("C:\\xampp\\tomcat\\webapps\\myapp\\WEB-INF\\lib\\counter.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
@Override
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
if (!shuttingDown) {
writeToFile("number of servlet access = " + serviceCounter );
}
}
@Override
public void destroy() {
...
}
private void enteringServiceMethod() {
synchronized (lock) {
serviceCounter++;
writeToFile("method enteringServiceMethod serviceCounter = " + serviceCounter);
}
}
private int getNumServices() {
synchronized (lock) {
return serviceCounter;
}
}
private void writeToFile(String text) {
System.out.println(text);
text += "\r\n";
try {
out.write(text.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
我需要的是每次有人打开我的 Servlet 时,它应该打开“counter.txt”文件并存储打开 Servlet 的次数。例如,如果文件保存数字 8,那么在有人访问 servlet 后,它应该存储数字 9 并删除数字 8。这有意义吗?谁能帮我重写 writeToFile 方法。我写的代码不完整,但我被卡住了,尝试了几件事,但似乎没有任何效果。