| |
25. 20. 2. 加载文件内容,然后将其保存在一个servlet |
|
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class MyServlet 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);
bufferedReader.close();
return;
}
catch (Exception ignored) { }
String initial = getInitParameter("initial");
try {
count = Integer.parseInt(initial);
return;
}
catch (NumberFormatException ignored) { } // null or non-integer value
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() {
super.destroy();
saveState();
}
public void saveState() {
FileWriter fileWriter = null;
PrintWriter printWriter = null;
try {
fileWriter = new FileWriter("InitDestroyCounter.initial");
printWriter = new PrintWriter(fileWriter);
printWriter.println(count);
printWriter.close();
return;
}
catch (IOException e) {
}
}
}
|
|
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<servlet><servlet-name>MyServletName</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping><servlet-name>MyServletName</servlet-name>
<url-pattern>/index.html</url-pattern>
</servlet-mapping>
</web-app>
|
|
Download: ServletLoadFileContentAndSaveBack.zip( 89 k) |
25. 20. 保存文件阅读 | | 25. 20. 1. | 读取文件servlet | | | | 25. 20. 2. | 加载文件内容,然后将其保存在一个servlet | | |
|