- DAO 객체를 ServletContext 보관소에 저장한다.
- AppInitServlet 변경
import java.sql.Connection;
import java.sql.DriverManager;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import com.bitcamp.board.dao.MariaDBBoardDao;
import com.bitcamp.board.dao.MariaDBMemberDao;
@WebServlet(value = "/init", loadOnStartup = 1)
public class AppInitServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void init() throws ServletException {
System.out.println("공유 자원을 준비 중!");
try {
Class.forName("org.mariadb.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mariadb://localhost:3306/studydb", "study", "1111");
ServletContext ctx = this.getServletContext();
ctx.setAttribute("boardDao", new MariaDBBoardDao(con));
ctx.setAttribute("memberDao", new MariaDBMemberDao(con));
} catch (Exception e) {
throw new ServletException(e);
}
}
}
- 서블릿은 DAO를 사용할 때 ServletContext에서 꺼낸다.
BoardDao boardDao;
@Override
public void init() throws ServletException {
boardDao = (BoardDao) this.getServletContext().getAttribute("boardDao");
}