2014-12-30 3 views
0

순수한 서블릿 API를 사용하여 간단한 프레임 워크를 사용하고 있습니다. 앱은 사용자 폴더 내의 사전 정의 된 위치에서 HSQLDB를 사용합니다. 처음 시작하거나 배포하는 동안 내부 응용 프로그램에서 테이블 구조를 만들어야합니다.Tomcat 시작시 데이터베이스 설정 방법

어떻게하면됩니까?

+0

https://confluence.atlassian.com/display/DOC/Configuring+an+Oracle+Datasource+in+Apache+Tomcat,이 링크는 당신을 도울 것입니다? –

+0

@ 예 아니요, 실제로 저는 이미 완벽하게 기능하는 응용 프로그램을 가지고 있습니다. 방금 배포 프로세스를 자동화하고 싶습니다. 기본적으로 배포 또는 첫 시작 중에 SQL 스크립트를 실행하는 방법이 필요합니다. –

+0

아, 봄도 사용하고 싶지 않으세요? –

답변

0

약간의 연구 끝에 ServletContextListener를 사용하는 솔루션을 찾았습니다. 나는 설명을 건너 뛰고 코드를 보여줄 것이다.

@WebListener 
public class DatabaseCreator implements ServletContextListener { 

    protected final Logger logger = LoggerFactory.getLogger(this.getClass()); 

    @Resource(
      name = "jdbc/rssDS", 
      type = javax.sql.DataSource.class, 
      authenticationType = Resource.AuthenticationType.CONTAINER 
    ) 
    private DataSource dataSource; 

    @Override 
    public void contextInitialized(ServletContextEvent sce) { 
     if (dataSource == null) { 
      logger.error("Data source wasn't initialized"); 
     } 
     String sql = readStreamToString(sce.getServletContext()); 
     if (StringUtils.isBlank(sql)) { 
      logger.error("SQL script is empty"); 
     } 
     try { 
      logger.debug("Executing SQL script"); 
      Connection connection = dataSource.getConnection(); 
      Statement statement = connection.createStatement(); 
      statement.execute(sql); 
     } catch (SQLException e) { 
      logger.error("Unable to create database table structure", e); 
     } 
    } 

    private String readStreamToString(ServletContext ctx) { 
     //skipped, reads stream contents into String 
    } 

    @Override 
    public void contextDestroyed(ServletContextEvent sce) { 

    } 
}