here is the piece of code that i wrote:
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();
}
}
}
What i need is every time someone opens my Servlet, it should open “counter.txt” file and store a number of how many times the Servlet was opened. for example if the file hold number 8 then after someone accesses the servlet it should store number 9 and delete number 8. does it make sense? can anyone help me override writeToFile method. the code that i wrote is incomplete, but i’m stuck, tried several things and nothing seems to work.
If you are trying to count page hit, then
Filterwould be the nice approachIntercept each request and take a
synchronizedvariable in application scope and increment it