Java by API/javax.servlet.http/HttpServlet — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 14:35, 31 мая 2010
HttpServlet: destroy()
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MainServlet extends HttpServlet {
int count;
public void init() throws ServletException {
FileReader fileReader = null;
BufferedReader bufferedReader = null;
try {
fileReader = new FileReader("InitDestroyCounter.initial");
bufferedReader = new BufferedReader(fileReader);
String initial = bufferedReader.readLine();
count = Integer.parseInt(initial);
return;
} catch (Exception ignored) {
}
finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException ignored) {
}
}
String initial = getInitParameter("initial");
try {
count = Integer.parseInt(initial);
return;
} catch (NumberFormatException ignored) {
}
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
FileWriter fileWriter = null;
PrintWriter printWriter = null;
try {
fileWriter = new FileWriter("InitDestroyCounter.initial");
printWriter = new PrintWriter(fileWriter);
printWriter.println(count);
return;
} catch (IOException e) { // problem during write
// Log the exception. See Chapter 5.
} finally {
// Make sure to close the file
if (printWriter != null) {
printWriter.close();
}
}
}
}
HttpServlet: doGet(HttpServletRequest req, HttpServletResponse resp)
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MainServlets extends HttpServlet {
int count;
public void init() throws ServletException {
String initial = getInitParameter("initial");
try {
count = Integer.parseInt(initial);
} catch (NumberFormatException e) {
count = 0;
}
}
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
count++;
out.println("Since loading (and with a possible initialization");
out.println("parameter figured in), this servlet has been accessed");
out.println(count + " times.");
}
}