서블릿에서 파일 시스템을 사용하여 데이터를 관리할 때 중요한 것이 경로를 관리하는 것이다.
웹에서는 ServletContext 객체를 사용하면 된다. 현재 서블릿이 실행되는 서버의 환경 정보를 관리하기 때문에 원하는 디렉터리까지의 주소를 추출할 수 있다.
ServletContext context = this.getServletContext();
String realPath = context.getRealPath("/");
getRealPath() 메서드의 매개 변수에 "/" 를 사용하면 해당 프로젝트까지의 주소가 반환된다.
해당 프로젝트의 특정 디렉터리에 접근하려면 매개변수에 상대경로를 써주면 된다.
예를 들어 프로젝트 내의 test 디렉터리에 접근하려면 다음과 같이 쓰면 된다.
String realPath = context.getRealPath("/test");
예제) 서버 시작 시 파일로 저장된 카운트를 읽어 표시하고 서버 종료시에 파일에 저장한다.
web.xml
....
<servlet>
<servlet-name>CountServlet</servlet-name>
<servlet-class>com.study.CountServlet</servlet-class>
<init-param>
<param-name>countFileDir</param-name>
<param-value>count</param-value>
</init-param>
<init-param>
<param-name>countFile</param-name>
<param-value>count.dat</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CountServlet</servlet-name>
<url-pattern>/count.do</url-pattern>
</servlet-mapping>
....
countServlet.java
package com.study;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CountServlet extends HttpServlet {
private int count = 0;
public void init() {
String dirName = this.getInitParameter("countFileDir");
String fileName = this.getInitParameter("countFile");
ServletContext context = this.getServletContext();
String realPath = context.getRealPath("/"); // 현재 프로젝트까지의 실제 경로 얻음
System.out.println("---- init() called ----");
System.out.println("dirName: " + dirName);
System.out.println("fileName: " + fileName);
System.out.println("realPath: " + realPath);
try {
// 파일에 기록된 카운트를 읽어 변수에 저장
File dir = new File(realPath, dirName);
if (!dir.exists()) {
dir.mkdir(); // 디렉토리가 없다면 생성
}
File file = new File(dir, fileName);
if (file.exists()) {
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
/* 이렇게 사용할 수 도 있다.
DataInputStream dis = new DataInputStream(
new BufferedInputStream(
new FileInputStream(file))); */
this.count = dis.readInt();
dis.close();
System.out.println("count: " + this.count);
} else {
file.createNewFile();
}
} catch(Exception _ex) {
System.out.println("init() Error: " + _ex.getLocalizedMessage());
}
}
public void service(HttpServletRequest _request, HttpServletResponse _response)
throws IOException, ServletException {
this.count++;
ServletContext context = this.getServletContext();
RequestDispatcher dispatcher =
context.getRequestDispatcher("/countView.jsp?count=" + this.count);
dispatcher.forward(_request, _response); // 뷰 페이지로 포워딩
}
public void destroy() {
String dirName = this.getInitParameter("countFileDir");
String fileName = this.getInitParameter("countFile");
ServletContext context = this.getServletContext();
String realPath = context.getRealPath("/");
System.out.println("---- destroy() called ----");
System.out.println("dirName: " + dirName);
System.out.println("fileName: " + fileName);
System.out.println("realPath: " + realPath);
System.out.println("count: " + this.count);
try {
// 현재까지의 카운트를 파일에 저장
File dir = new File(realPath, dirName);
File file = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
DataOutputStream dos = new DataOutputStream(bos);
dos.writeInt(this.count);
dos.close();
} catch(Exception _ex) {
System.out.println("destroy() Error: " + _ex.getLocalizedMessage());
}
}
}
countView.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<%
String count = request.getParameter("count");
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>카운트 보기</title>
</head>
<body>
<center>현재 카운트는 <%= count %>입니다.</center>
</body>
</html>
서버 시작 시 자동으로 init()이 호출되어(web.xml에 설정됨) count에 저장된다.
처음 실행 시킨다면 파일이 없으므로 콘솔에 아래와 같이 출력될 것이다.

countServlet 서블릿이 불러지도록 해보면 (http://*********/count.do) 뷰 페이지에 카운팅 될 것이다.
페이지를 계속 갱신해보면 카운트가 올라갈 것이다.
그 다음, 서버를 종료하면 콘솔에 최종 카운트가 보이면서 파일로 저장될 것이다.

다시 서버를 구동시키면 앞서 기록한 내용과 동일함을 확인할 수 있을 것이다.
