当glassfish web容器中的servlet使用FileTriter实例保存文件时,我怎么知道呢?

时间:2013-01-27 18:57:51

标签: java servlets glassfish

在阅读有关servlet的本书时,我遇到了一个示例,它使用FileWriter类在servlet被破坏之前保存它的持久状态。测试了示例并且工作正常,这是代码:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class InitDestroyCounter extends HttpServlet {

  int count;

  public void init(ServletConfig config) throws ServletException {
    // Always call super.init(config) first  (servlet mantra #1)
    super.init(config);

    // Try to load the initial count from our saved persistent state
    try {
      FileReader fileReader = new FileReader("InitDestroyCounter.initial");
      BufferedReader bufferedReader = new BufferedReader(fileReader);
      String initial = bufferedReader.readLine();
      count = Integer.parseInt(initial);
      return;
    }
    catch (FileNotFoundException ignored) { }  // no saved state
    catch (IOException ignored) { }            // problem during read
    catch (NumberFormatException ignored) { }  // corrupt saved state

    // No luck with the saved state, check for an init parameter
    String initial = getInitParameter("initial");
    try {
      count = Integer.parseInt(initial);
      return;
    }
    catch (NumberFormatException ignored) { }  // null or non-integer value

    // Default to an initial count of "0"
    count = 0;
  }

  public void doGet(HttpServletRequest req, HttpServletResponse res) 
                               throws ServletException, IOException {
    res.setContentType("text/plain");
    PrintWriter out = res.getWriter();
    count++;
    out.println("Since the beginning, this servlet has been accessed " +
                count + " times.");
  }

  public void destroy() {
    saveState();
  }

  public void saveState() {
    // Try to save the accumulated count
    try {
      FileWriter fileWriter = new FileWriter("InitDestroyCounter.initial");
      String initial = Integer.toString(count);
      fileWriter.write(initial, 0, initial.length());
      fileWriter.close();
      return;
    }
    catch (IOException e) {  // problem during write
      // Log the exception.
    }
  }
}

在停止glassfish服务器之后,我从deploy文件夹中复制/粘贴war文件,解开它并查找“InitDestroyCounter.initial”文件,但是在那里找不到所以它让我想知道glassfish在哪里保存这个创建的文件?

5 个答案:

答案 0 :(得分:2)

(不是答案,但对于清晰的评论来说太长了。)

  1. 您无法将文件保存为战争。 1

  2. 您应该通过写入绝对路径来写入已知文件位置。这可以通过JNDI,init上下文参数,启动参数,环境变量等来定义。

  3. IMO即使不是战争,你也不应该写入网络应用程序,因为你的文件将受到你的部署机制的支配,并且可能会被淘汰

  4. 1是的,你可以。不。

答案 1 :(得分:2)

所有其他人都对WAR修改是正确的,但对于上面的代码:

这个

FileWriter fileWriter = new FileWriter("InitDestroyCounter.initial");

的快捷方式
File f = new File("InitDestroyCounter.initial");
FileWriter fileWriter = new FileWriter(f);

请随意向File对象询问其绝对位置:

System.out.println(f.getAbsolutePath());

以上所有代码都将使用JVM的当前/工作目录来存储和读取文件。 请记住,应根据Java EE规范避免I / O访问:Java EE programmers do not write to files

答案 2 :(得分:1)

在任何java web / app服务器中,您都不应期望在部署的存档中直接进行修改。相反,它会将文件写入当前工作目录。

如果你在linux中,我找到了一个地方(http://www.java.net/forum/topic/glassfish/glassfish/paths-glassfish),他们声称你可以使用命令检索当前正在工作的目录:

asadmin generate-jvm-report | grep "user.dir" 

所以你可以看到它的内容。

但是据我所知,它应该是服务器的config目录。所以也许可以查看文件。

答案 3 :(得分:1)

GlassFish绝对保证当前工作目录始终是域的“config”目录。例如。在默认情况下:

/域/域1 /配置

保证仅适用于使用asadmin启动GlassFish的情况。

注意:我写了代码,所以我肯定知道!

答案 4 :(得分:0)

从我所做的答案和测试中,所有这些都可以指向路径:

System.getProperty("user.dir")

new File(".").getAbsolutePath()

getAbsolutePath();

正如你在这里看到的那样:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class InitDestroyCounter extends HttpServlet
{
    int Cnt;

    String FR_File_Str;

    @Override
    public void init(ServletConfig ServlConf) throws ServletException
    {
        // Always call super.init(ServletConfig) first;
        super.init(ServlConf);

        // Try to load the initial Cnt from our saved persistent state;
        try
        {
            File FR_File = new File("InitDestCounter.init");
            FileReader FR = new FileReader(FR_File);

            BufferedReader BR = new BufferedReader(FR);

            String Initial_str = BR.readLine();

            Cnt = Integer.parseInt(Initial_str);

            FR_File_Str = FR_File.getAbsolutePath();

            return;
        }
        catch(FileNotFoundException Ignored){} // No saved state;
        catch(IOException Ignored){} // Problem during read;
        catch(NumberFormatException Ignored){} // Corrupted saved state;

        // No luck with the saved state, check for and init parameter;
        String Initial_str = getInitParameter("initial_cnt");

        try
        {
            Cnt = Integer.parseInt(Initial_str);
            return;
        }
        // Null or non-integer value;
        catch(NumberFormatException NFE){}

        // Default, if non of the above worked;
        Cnt = 0;
    }

    @Override
    public void doGet(HttpServletRequest  Request,
                      HttpServletResponse Response)
                      throws ServletException, IOException
    {
        Response.setContentType("text/html");

        PrintWriter PW = Response.getWriter();

        Cnt++;

        PW.println("<H4>Since the beginning this servlet had been "+
                   "accessed "+Cnt+" times.</H4>");
        PW.println("<H4>"+System.getProperty("user.dir")+"</H4>");
        PW.println("<H4>"+new File(".").getAbsolutePath()+"</H4>");
        PW.println("<H4>FR_File_Str = "+FR_File_Str+"</H4>");
    }

    public void SaveState()
    {
        // Try to save the accumulated count;
        try
        {
            FileWriter FW = new FileWriter("InitDestCounter.init");

            String Initial_str = Integer.toString(Cnt);

            FW.write(Initial_str, 0, Initial_str.length());

            FW.close();

            return;
        }
        catch(IOException IOE){} // Problem during write;
    }

    @Override
    public void destroy()
    {
        SaveState();
    }
}

为了礼貌,我不会接受我自己的答案。感谢大家的回答和评论。