While reading this book about servlets i came across an example that uses FileWriter class to save a persistent state of a servlet before it gets destroyed. Tested the example and works fine, this is the code:
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.
}
}
}
After stoping glassfish server, i copy/paste the war file from the deploy folder, unjar it and look for "InitDestroyCounter.initial" file, but cant be found in there so it got me wondering where does glassfish save this created file?