从Servlet写入文件

时间:2012-05-12 11:14:42

标签: java xml servlets

这是我写的代码片段:

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方法。我写的代码是不完整的,但是我被卡住了,尝试了几件事似乎没什么用。

1 个答案:

答案 0 :(得分:2)

如果您正在尝试计算网页点击次数,那么Filter将是一个不错的方法

拦截每个请求并在应用程序范围内获取synchronized变量并将其递增