본문 바로가기

Servlet/getRealPath()

ServletContext.getRealPath() example

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;

 public class CounterServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
   static final long serialVersionUID = 1L;
   private long cnt;
  
   private DataInputStream din;
   private DataOutputStream dout;
   private FileInputStream fin;
   private FileOutputStream fout; 
   private String counterPath ;

 public void init(){
  // 자주 사용되면서 한번만 초기화하면 되는 값을 설정함
  counterPath = this.getServletContext().getRealPath("/WEB-INF/count.dat");
  // 카운트 파일이 없는 경우 즉, 카운트를 처음 시작하는 경우에는 파일을 새로 생성해 준다.
  File f = new File(counterPath);
  if(!f.exists()){
   createCounterFile();
  }
 }
 
 protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  response.setContentType("text/html;charset=KSC5601");
  PrintWriter out = response.getWriter();
  out.println("<html><body>");
 
  if(cnt==0){ // 서블릿 인스턴스가 생성되어 최초로 호출되었을 경우
   cnt = getCountFromFile()+1; //파일에 있는 카운트를 메모리에 복사함
   out.println("Count:"+cnt);
  }else{
   cnt++;
   out.println("Count:"+cnt);
   if(cnt%5==0){ // 카운트가 5의 배수에 도달할 때마다 파일에 저장함
    saveCount();
    out.println("파일에 저장했음");
   }
  }
  out.println("</body></html>");
 }
 
 private long getCountFromFile() throws IOException {
  try{
   fin = new FileInputStream(counterPath);
   din = new DataInputStream(fin);
   long cnt = din.readLong();
   din.close();
   return cnt;
  }catch(FileNotFoundException fe){
   try{
    if(din!=null)din.close();
   }catch(Exception e){}
   createCounterFile();
   return 0L;
  }catch(IOException ioe){
   throw ioe;
  }
 }
 
 private void createCounterFile(){
  try{
   fout = new FileOutputStream(counterPath);
   dout = new DataOutputStream(fout);
   dout.writeLong(0L);
   dout.close();
  }catch(Exception e){}
 }
 
 private void saveCount(){
  try{
   dout = new DataOutputStream(new FileOutputStream(counterPath));
   dout.writeLong(cnt);
   dout.close();
  }catch(FileNotFoundException fe){
  }catch(IOException ie){}
 }
}