81,092
社区成员
发帖
与我相关
我的任务
分享
@WebServlet("/testBug")
public class testBug extends HttpServlet {
private static final long serialVersionUID = 1L;
public testBug() {
super();
// TODO Auto-generated constructor stub
}
public void init(ServletConfig config) throws ServletException {
super.init(config);
String filePath = this.getServletContext().getRealPath("record.txt");
FileReader fr = null;
BufferedReader br = null;
try{
fr = new FileReader(filePath);
br = new BufferedReader(fr);
String num = br.readLine();
this.getServletContext().setAttribute("num", num);
}catch(Exception e){
e.printStackTrace();
}finally{
try {
br.close();
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void destroy() {
String filePath = this.getServletContext().getRealPath("record.txt");
FileWriter fw= null;
BufferedWriter bw= null;
try{
fw = new FileWriter(filePath);
bw = new BufferedWriter(fw);
String num = (String)this.getServletContext().getAttribute("num");
bw.write(num);
}catch(IOException e){
e.printStackTrace();
}finally{
try {
bw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String num = (String)this.getServletContext().getAttribute("num");
this.getServletContext().setAttribute("num",(Integer.parseInt(num)+1)+"");
String nums = (String)this.getServletContext().getAttribute("num");
out.println("该网页被访问了"+nums+"次");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}