Gipsy
Gipsy

Reputation: 265

write to File from Servlet

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.

Upvotes: 1

Views: 550

Answers (1)

Jigar Joshi
Jigar Joshi

Reputation: 240996

If you are trying to count page hit, then Filter would be the nice approach

Intercept each request and take a synchronized variable in application scope and increment it

Upvotes: 2

Related Questions