1. 程式人生 > >servlet-servletContext網站計數器

servlet-servletContext網站計數器

在web.xml檔案配置

<servlet>
     <description>This is the description of my J2EE component</description>
     <display-name>This is the display name of my J2EE component</display-name>
     <servlet-name>NumServlet</servlet-name>
     <servlet-class>servlet.NumServlet</servlet-class>
     <load-on-startup>1</load-on-startup>
   </servlet>

 

 

public class NumServlet extends HttpServlet {
    
     //複寫init初始化方法,將資料讀取到ServletContext物件中
     @Override
     public void init() throws ServletException {
         //獲取檔案路徑
         String path=this.getServletContext().getRealPath("/nums/nums.txt");
         //宣告流物件
         FileReader fr=null;
         BufferedReader br=null;
         try{
             fr=new FileReader(path);
             br=new BufferedReader(fr);
             String nums=br.readLine();
             System.out.println(nums);
             this.getServletContext().setAttribute("nums",nums);
         }catch(Exception e){
             e.printStackTrace();
         }finally{
             try {
                 br.close();
             } catch (IOException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
             }
             try {
                 fr.close();
             } catch (IOException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
             }
         }
        
     }
    
    
     //複寫銷燬方法,儲存計數器到檔案中
     @Override
     public void destroy(){
         //獲取網頁計數器
         int nums=(int)this.getServletContext().getAttribute("nums");
         //獲取檔案路徑
         String path=this.getServletContext().getRealPath("/nums/nums.txt");
         //宣告流物件
         BufferedWriter bw=null;
         FileWriter fw=null;
         try{
             fw=new FileWriter(path);
             bw=new BufferedWriter(fw);
             bw.write(nums+"");
             bw.flush();
         }catch(Exception e){
             e.printStackTrace();
         }finally{
             try {
                 fw.close();
             } catch (IOException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
             }
             try {
                 bw.close();
             } catch (IOException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
             }
            
         }
     }
    
}