【问题标题】:write to File from Servlet从 Servlet 写入文件
【发布时间】:2012-05-12 11:14:41
【问题描述】:

这是我写的一段代码:

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 方法。我写的代码不完整,但我被卡住了,尝试了几件事,但似乎没有任何效果。

【问题讨论】:

  • 我认为直接写不是一个好主意,因为您将不得不处理并发执行(在最好的情况下会延迟您的回答时间,在最坏的情况下会导致无效值)。发生这种情况时,将消息放入队列并让单个实例处理消息并更新值。

标签: java xml servlets


【解决方案1】:

如果您要计算页面点击,那么Filter 将是不错的方法

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

【讨论】:

  • 嗯,我想我不知道该怎么做。我试过使用过滤器,但我的 writetoFile 方法有问题。它确实可以编译,但是在运行时,当我启动我的 servlet 时,它会抛出异常并且我没有看到它在工作。
  • 但是为什么要在每个请求上写入文件,你可以在内存中管理它,并且可能在某个时间间隔你可以将它写入文件/DB
  • 嗯,这就是我被要求做的:每次访问 ServletCounret 时,都应该打开文件,记下条目数和关闭文件。
  • 如果你还是想这样做,那么使用同步方法,它应该可以工作,如果不适合你,请在这里告诉我们异常堆栈跟踪
  • 异常` java.lang.NullPointerException ServletCounter.writeToFile(ServletCounter.java:80) ServletCounter.enteringServiceMethod(ServletCounter.java:67) ServletCounter.service(ServletCounter.java:25) javax.servlet.http .HttpServlet.service(HttpServlet.java:722)`.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-27
  • 2013-02-14
  • 1970-01-01
  • 2011-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多